📚 Net Library Source Code

Complete codebase export - November 29, 2026

347
Total Files
38
Hooks
93
Components
143
API Routes

📑 Table of Contents

🪝 Hooks 🧩 Components 🔌 APIs 🔗 Share Routes 📁 Other

🪝 Hooks (38)

src/hooks/use-active-members.ts
"use client";

import { useState, useEffect, useCallback } from "react";
import { useAppMode, type AppMode } from "@/lib/app-mode";

export function useActiveMembers() {
  const [activeCount, setActiveCount] = useState(0);
  const [farcasterCount, setFarcasterCount] = useState(0);
  const [baseAppCount, setBaseAppCount] = useState(0);
  const [webCount, setWebCount] = useState(0);
  const [isLoading, setIsLoading] = useState(true);
  const appMode = useAppMode();

  // Fetch active members count via our API (avoids CORS issues with storedon.net)
  const fetchActiveMembers = useCallback(async () => {
    try {
      const response = await fetch("/api/active-members");
      if (!response.ok) {
        setActiveCount(0);
        setFarcasterCount(0);
        setBaseAppCount(0);
        setWebCount(0);
        return;
      }

      const data = await response.json();
      setActiveCount(data.activeCount || 0);
      setFarcasterCount(data.farcasterCount || 0);
      setBaseAppCount(data.baseAppCount || 0);
      setWebCount(data.webCount || 0);
    } catch {
      // If fetch fails, show 0 active
      setActiveCount(0);
      setFarcasterCount(0);
      setBaseAppCount(0);
      setWebCount(0);
    } finally {
      setIsLoading(false);
    }
  }, []);

  // Report current user as active (call this when user does something)
  const reportActive = useCallback(async (address: string, memberId: number) => {
    // Get current app mode for reporting
    const currentAppMode: AppMode = appMode === "detecting" ? "farcaster" : appMode;

    try {
      await fetch("/api/active-members", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ address, memberId, appMode: currentAppMode }),
      });
    } catch {
      // Silently fail - not critical
    }
  }, [appMode]);

  // Fetch on mount and refresh periodically
  useEffect(() => {
    fetchActiveMembers();

    // Refresh every 30 seconds
    const interval = setInterval(fetchActiveMembers, 30000);
    return () => clearInterval(interval);
  }, [fetchActiveMembers]);

  return {
    activeCount,
    farcasterCount,
    baseAppCount,
    webCount,
    isLoading,
    reportActive,
    refresh: fetchActiveMembers,
  };
}
src/hooks/use-book-content.ts
"use client";

import { useState, useCallback } from "react";

export type MediaType = "audio" | "video" | "image" | "text" | "pdf" | null;

export interface BookContentResult {
  sentences: string[];
  pdfDataUrl: string | null;
  isPdf: boolean;
  // New media type fields
  mediaType: MediaType;
  cdnUrl: string | null;
  isLoading: boolean;
  error: string | null;
}

export function useBookContent() {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [sentences, setSentences] = useState<string[]>([]);
  const [pdfDataUrl, setPdfDataUrl] = useState<string | null>(null);
  const [isPdf, setIsPdf] = useState(false);
  const [mediaType, setMediaType] = useState<MediaType>(null);
  const [cdnUrl, setCdnUrl] = useState<string | null>(null);

  const fetchContent = useCallback(
    async (
      contentKey: string,
      operatorAddress: string,
      storageType: "regular" | "chunked" | "xml"
    ): Promise<{
      sentences: string[];
      pdfDataUrl: string | null;
      isPdf: boolean;
      mediaType: MediaType;
      cdnUrl: string | null;
    }> => {
      setIsLoading(true);
      setError(null);
      setPdfDataUrl(null);
      setIsPdf(false);
      setMediaType(null);
      setCdnUrl(null);

      try {
        // Fetch via our API route (avoids CORS issues with storedon.net)
        const apiUrl = `/api/book-content?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=${storageType}`;
        console.log("[useBookContent] Fetching via API:", apiUrl);

        const response = await fetch(apiUrl);
        const data = await response.json();

        if (!response.ok) {
          throw new Error(data.error || `Failed to fetch: ${response.status}`);
        }

        const resultSentences = data.sentences || ["No content available."];
        const resultPdfDataUrl = data.pdfDataUrl || null;
        const resultIsPdf = data.isPdf || false;
        const resultMediaType = data.mediaType || null;
        const resultCdnUrl = data.cdnUrl || null;

        console.log("[useBookContent] Result - mediaType:", resultMediaType, "cdnUrl:", resultCdnUrl);

        setSentences(resultSentences);
        setPdfDataUrl(resultPdfDataUrl);
        setIsPdf(resultIsPdf);
        setMediaType(resultMediaType);
        setCdnUrl(resultCdnUrl);
        setIsLoading(false);

        return {
          sentences: resultSentences,
          pdfDataUrl: resultPdfDataUrl,
          isPdf: resultIsPdf,
          mediaType: resultMediaType,
          cdnUrl: resultCdnUrl,
        };
      } catch (err) {
        console.error("[useBookContent] Error:", err);
        const errorMessage = err instanceof Error ? err.message : "Failed to fetch content";
        setError(errorMessage);
        setIsLoading(false);

        // Return fallback sentences
        const fallbackSentences = [
          "📖 This book is stored onchain on Base L2.",
          "Content loading encountered an issue.",
          'Click "Open" to try viewing the file directly.',
        ];
        setSentences(fallbackSentences);
        return { sentences: fallbackSentences, pdfDataUrl: null, isPdf: false, mediaType: null, cdnUrl: null };
      }
    },
    []
  );

  const reset = useCallback(() => {
    setSentences([]);
    setPdfDataUrl(null);
    setIsPdf(false);
    setMediaType(null);
    setCdnUrl(null);
    setError(null);
    setIsLoading(false);
  }, []);

  return {
    sentences,
    pdfDataUrl,
    isPdf,
    mediaType,
    cdnUrl,
    isLoading,
    error,
    fetchContent,
    reset,
  };
}
src/hooks/use-changelog.ts
"use client";

import { useState, useEffect, useCallback } from "react";

export interface ChangeEntry {
  type: "feature" | "fix" | "improvement" | "breaking" | "docs" | "internal";
  category: "ui" | "api" | "database" | "achievements" | "uploads" | "social" | "membership" | "other";
  title: string;
  description: string;
  technical?: string;
}

export interface ChangelogEntry {
  version: string;
  publishedAt: number;
  changes: ChangeEntry[];
  summary: string;
}

export function useChangelog(limit = 10) {
  const [entries, setEntries] = useState<ChangelogEntry[]>([]);
  const [currentVersion, setCurrentVersion] = useState<string>("1.0.0");
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchChangelog = useCallback(async () => {
    setIsLoading(true);
    try {
      const response = await fetch(`/api/changelog?limit=${limit}`);
      if (!response.ok) throw new Error("Failed to fetch changelog");

      const data = await response.json();
      setEntries(data.entries || []);
      setCurrentVersion(data.currentVersion || "1.0.0");
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to fetch changelog");
    } finally {
      setIsLoading(false);
    }
  }, [limit]);

  useEffect(() => {
    fetchChangelog();
  }, [fetchChangelog]);

  // Add a new changelog entry (for use after publish)
  const addEntry = useCallback(async (
    changes: ChangeEntry[],
    summary: string,
    versionType: "major" | "minor" | "patch" = "patch"
  ) => {
    try {
      const response = await fetch("/api/changelog", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ changes, summary, versionType }),
      });

      if (!response.ok) throw new Error("Failed to add changelog entry");

      const data = await response.json();

      // Refresh the list
      await fetchChangelog();

      return { success: true, version: data.entry.version };
    } catch (err) {
      return { success: false, error: err instanceof Error ? err.message : "Failed to add entry" };
    }
  }, [fetchChangelog]);

  // Generate documentation updates
  const generateDocsUpdate = useCallback(async () => {
    try {
      const response = await fetch("/api/changelog", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ action: "generate-docs-update" }),
      });

      if (!response.ok) throw new Error("Failed to generate docs update");

      return await response.json();
    } catch (err) {
      return { success: false, error: err instanceof Error ? err.message : "Failed to generate docs" };
    }
  }, []);

  return {
    entries,
    currentVersion,
    isLoading,
    error,
    refresh: fetchChangelog,
    addEntry,
    generateDocsUpdate,
  };
}

// Helper to create change entries
export function createChange(
  type: ChangeEntry["type"],
  category: ChangeEntry["category"],
  title: string,
  description: string,
  technical?: string
): ChangeEntry {
  return { type, category, title, description, technical };
}
src/hooks/use-collections.ts
"use client";

import { useState, useEffect, useCallback } from "react";

interface Collection {
  id: string;
  name: string;
  description: string;
  emoji: string;
  ownerAddress: string;
  bookIds: string[];
  isPublic: boolean;
  createdAt: number;
  updatedAt: number;
}

export function useCollections(userAddress?: string) {
  const [collections, setCollections] = useState<Collection[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Fetch user's collections
  const fetchCollections = useCallback(async () => {
    if (!userAddress) {
      setCollections([]);
      setIsLoading(false);
      return;
    }

    setIsLoading(true);
    try {
      const response = await fetch(`/api/collections?userAddress=${userAddress}`);
      if (response.ok) {
        const data = await response.json();
        setCollections(data.collections || []);
      }
    } catch (err) {
      console.error("[useCollections] Fetch error:", err);
      setError("Failed to load collections");
    } finally {
      setIsLoading(false);
    }
  }, [userAddress]);

  useEffect(() => {
    fetchCollections();
  }, [fetchCollections]);

  // Create new collection
  const createCollection = useCallback(async (
    name: string,
    options?: { description?: string; emoji?: string; isPublic?: boolean }
  ) => {
    if (!userAddress) return null;

    try {
      const response = await fetch("/api/collections", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "create",
          userAddress,
          name,
          ...options,
        }),
      });

      if (response.ok) {
        const data = await response.json();
        setCollections(prev => [...prev, data.collection]);
        return data.collection;
      }
    } catch (err) {
      console.error("[useCollections] Create error:", err);
    }
    return null;
  }, [userAddress]);

  // Update collection
  const updateCollection = useCallback(async (
    collectionId: string,
    updates: { name?: string; description?: string; emoji?: string; isPublic?: boolean }
  ) => {
    if (!userAddress) return false;

    try {
      const response = await fetch("/api/collections", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "update",
          userAddress,
          collectionId,
          ...updates,
        }),
      });

      if (response.ok) {
        const data = await response.json();
        setCollections(prev =>
          prev.map(c => c.id === collectionId ? data.collection : c)
        );
        return true;
      }
    } catch (err) {
      console.error("[useCollections] Update error:", err);
    }
    return false;
  }, [userAddress]);

  // Add book to collection
  const addBook = useCallback(async (collectionId: string, bookId: string) => {
    if (!userAddress) return false;

    try {
      const response = await fetch("/api/collections", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "add-book",
          userAddress,
          collectionId,
          bookId,
        }),
      });

      if (response.ok) {
        const data = await response.json();
        setCollections(prev =>
          prev.map(c => c.id === collectionId ? data.collection : c)
        );
        return true;
      }
    } catch (err) {
      console.error("[useCollections] Add book error:", err);
    }
    return false;
  }, [userAddress]);

  // Remove book from collection
  const removeBook = useCallback(async (collectionId: string, bookId: string) => {
    if (!userAddress) return false;

    try {
      const response = await fetch("/api/collections", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "remove-book",
          userAddress,
          collectionId,
          bookId,
        }),
      });

      if (response.ok) {
        const data = await response.json();
        setCollections(prev =>
          prev.map(c => c.id === collectionId ? data.collection : c)
        );
        return true;
      }
    } catch (err) {
      console.error("[useCollections] Remove book error:", err);
    }
    return false;
  }, [userAddress]);

  // Delete collection
  const deleteCollection = useCallback(async (collectionId: string) => {
    if (!userAddress) return false;

    try {
      const response = await fetch("/api/collections", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "delete",
          userAddress,
          collectionId,
        }),
      });

      if (response.ok) {
        setCollections(prev => prev.filter(c => c.id !== collectionId));
        return true;
      }
    } catch (err) {
      console.error("[useCollections] Delete error:", err);
    }
    return false;
  }, [userAddress]);

  // Check if a book is in any collection
  const isBookInCollection = useCallback((bookId: string, collectionId?: string) => {
    if (collectionId) {
      const collection = collections.find(c => c.id === collectionId);
      return collection?.bookIds.includes(bookId) || false;
    }
    return collections.some(c => c.bookIds.includes(bookId));
  }, [collections]);

  return {
    collections,
    isLoading,
    error,
    createCollection,
    updateCollection,
    addBook,
    removeBook,
    deleteCollection,
    isBookInCollection,
    refresh: fetchCollections,
  };
}
src/hooks/use-comment-upvotes.ts
"use client";
/**
 * Hook for upvoting comments via Score Protocol
 *
 * Comment upvotes work similarly to document upvotes, but use a comment-specific
 * storage key format: "netlib-comment-{commentId}"
 *
 * This allows each comment to have its own upvote count tracked onchain via Score Protocol.
 */

import { useState, useEffect, useCallback, useRef, useMemo } from "react";
import { useWriteContract, useWaitForTransactionReceipt, useAccount } from "wagmi";
import { keccak256, encodePacked, parseEther, stringToHex } from "viem";
import { base } from "viem/chains";

// Contract addresses on Base (same as document upvotes)
const UPVOTE_STORAGE_APP = "0x000000060CEB69D023227DF64CfB75eC37c75B62" as const;
const PURE_ALPHA_STRATEGY = "0x00000001b1bcdeddeafd5296aaf4f3f3e21ae876" as const;

// Cost per upvote in ETH (same as document upvotes)
export const COMMENT_UPVOTE_COST_ETH = 0.000025;
export const COMMENT_UPVOTE_COST_WEI = parseEther(COMMENT_UPVOTE_COST_ETH.toString());

// Operator address for comment upvotes (uses the same as documents - Net Library treasury)
// This should be the address that receives tips from comment upvotes
const COMMENT_UPVOTE_OPERATOR = "0x2c43A2556ED11dB7BA62D5B0e7F1D6dF5a926E9E" as const;

// ABI for UpvoteStorageApp
const UPVOTE_STORAGE_APP_ABI = [
  {
    name: "upvote",
    type: "function",
    stateMutability: "payable",
    inputs: [
      { name: "strategy", type: "address" },
      { name: "storageOperatorAddress", type: "address" },
      { name: "storageKey", type: "bytes32" },
      { name: "scoreDelta", type: "uint256" },
      { name: "scoreUnstoredContext", type: "bytes" },
    ],
    outputs: [],
  },
] as const;

/**
 * Generate a storage key for a comment
 * Format: keccak256("netlib-comment-{commentId}")
 */
export function generateCommentStorageKey(commentId: string): `0x${string}` {
  const prefix = "netlib-comment-";
  const fullKey = `${prefix}${commentId}`;
  // Hash the full key to get a bytes32
  return keccak256(stringToHex(fullKey));
}

/**
 * Generate the Score Protocol score key for a comment
 * This is used to query and track upvotes
 */
export function generateCommentScoreKey(commentId: string): `0x${string}` {
  const storageKey = generateCommentStorageKey(commentId);
  return keccak256(
    encodePacked(
      ["bytes32", "address"],
      [storageKey, COMMENT_UPVOTE_OPERATOR.toLowerCase() as `0x${string}`]
    )
  );
}

// Pending upvote info for tracking
interface PendingCommentUpvote {
  commentId: string;
  amount: number;
}

/**
 * Hook for upvoting a single comment
 */
export function useCommentUpvote() {
  const { address, isConnected } = useAccount();
  const [isUpvoting, setIsUpvoting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const pendingUpvoteRef = useRef<PendingCommentUpvote | null>(null);

  const { writeContract, data: txHash, isPending, reset } = useWriteContract();

  const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({
    hash: txHash,
  });

  // When transaction confirms, reset state
  useEffect(() => {
    if (isConfirmed && txHash && pendingUpvoteRef.current) {
      console.log("[useCommentUpvote] Comment upvote confirmed:", {
        commentId: pendingUpvoteRef.current.commentId,
        amount: pendingUpvoteRef.current.amount,
        txHash,
      });

      pendingUpvoteRef.current = null;
      setIsUpvoting(false);
      reset();
    }
  }, [isConfirmed, txHash, reset]);

  const upvoteComment = useCallback(
    async (commentId: string, count: number = 1) => {
      if (!isConnected || !address) {
        setError("Wallet not connected");
        return false;
      }

      if (count < 1) {
        setError("Must upvote at least 1");
        return false;
      }

      setIsUpvoting(true);
      setError(null);

      try {
        const totalCost = COMMENT_UPVOTE_COST_WEI * BigInt(count);
        const storageKey = generateCommentStorageKey(commentId);

        pendingUpvoteRef.current = {
          commentId,
          amount: count,
        };

        writeContract({
          address: UPVOTE_STORAGE_APP,
          abi: UPVOTE_STORAGE_APP_ABI,
          functionName: "upvote",
          args: [
            PURE_ALPHA_STRATEGY,
            COMMENT_UPVOTE_OPERATOR,
            storageKey,
            BigInt(count),
            "0x" as `0x${string}`, // empty scoreUnstoredContext
          ],
          value: totalCost,
          chainId: base.id,
        });

        return true;
      } catch (err) {
        console.error("[useCommentUpvote] Error:", err);
        const errorMsg = err instanceof Error ? err.message : "Failed to upvote comment";
        setError(errorMsg);
        setIsUpvoting(false);
        pendingUpvoteRef.current = null;
        return false;
      }
    },
    [isConnected, address, writeContract]
  );

  return {
    upvoteComment,
    isUpvoting: isUpvoting || isPending || isConfirming,
    isConfirmed,
    error,
    txHash,
    reset: () => {
      reset();
      setError(null);
      setIsUpvoting(false);
      pendingUpvoteRef.current = null;
    },
  };
}

/**
 * Hook for fetching upvote counts for multiple comments
 */
export function useCommentUpvoteCounts(commentIds: string[]) {
  const [counts, setCounts] = useState<Map<string, number>>(new Map());
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const hasFetchedRef = useRef(false);

  // Serialize comment IDs for stable dependency
  const idsKey = useMemo(() => JSON.stringify([...commentIds].sort()), [commentIds]);

  const fetchCounts = useCallback(async () => {
    if (commentIds.length === 0) {
      if (hasFetchedRef.current) {
        setCounts(new Map());
        setIsLoading(false);
      }
      return;
    }

    hasFetchedRef.current = true;
    setIsLoading(true);
    setError(null);

    try {
      // Generate score keys for all comments
      const scoreKeys = commentIds.map(generateCommentScoreKey);

      // Call the upvotes API to get counts
      const response = await fetch("/api/upvotes", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          scoreKeys,
          contentKeys: commentIds, // Use commentIds as contentKeys for mapping
        }),
      });

      if (!response.ok) {
        throw new Error("Failed to fetch comment upvote counts");
      }

      const data = await response.json();
      const newCounts = new Map<string, number>();

      if (data.counts) {
        commentIds.forEach((id, index) => {
          newCounts.set(id, data.counts[index] || 0);
        });
      }

      setCounts(newCounts);
    } catch (err) {
      console.error("[useCommentUpvoteCounts] Error:", err);
      setError(err instanceof Error ? err.message : "Failed to fetch counts");
    } finally {
      setIsLoading(false);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [idsKey]);

  useEffect(() => {
    fetchCounts();
  }, [fetchCounts]);

  const getCount = useCallback(
    (commentId: string) => counts.get(commentId) || 0,
    [counts]
  );

  return {
    counts,
    getCount,
    isLoading,
    error,
    refresh: fetchCounts,
  };
}

// Export operator address for reference
export const COMMENT_UPVOTE_CONTRACTS = {
  UPVOTE_STORAGE_APP,
  PURE_ALPHA_STRATEGY,
  OPERATOR: COMMENT_UPVOTE_OPERATOR,
};
src/hooks/use-comments.ts
"use client";
// Net Protocol onchain comments hook
// NOTE: This is the canonical file - use-onchain-comments.ts re-exports from here
import { useState, useCallback, useMemo, useEffect } from "react";
import { NetClient } from "@net-protocol/core";
import type { NetClient as NetClientType } from "@net-protocol/core";
import { useAccount, useWriteContract, useWaitForTransactionReceipt } from "wagmi";
import { BASE_CHAIN_ID } from "@/lib/net-protocol";
import { trackComment } from "@/lib/diagnostics";

// NetMessage type from Net Protocol
export interface NetMessage {
  app: `0x${string}`;
  sender: `0x${string}`;
  timestamp: bigint;
  data: `0x${string}`;
  text: string;
  topic: string;
}

// Comment metadata stored in the `data` field of NetMessage
interface CommentMetadata {
  username?: string;
  pfpUrl?: string;
  parentCommentId?: string; // For threaded replies (references another comment's id)
  version: 1 | 2; // v2 adds threading support
  isAgent?: boolean; // v2.1: track if comment is from an agent
}

// Parsed comment structure for UI
export interface OnchainComment {
  id: string; // Unique ID from sender + timestamp
  sender: `0x${string}`;
  text: string;
  timestamp: number;
  username?: string;
  pfpUrl?: string;
  parentCommentId?: string; // For threaded replies
  upvotes?: number; // From Score Protocol (added by hook)
  replyCount?: number; // Count of direct replies (computed)
  replies?: OnchainComment[]; // Nested replies for tree rendering
  isAgent?: boolean; // True if comment is from a registered AI agent
}

// Parse a NetMessage into our comment structure
function parseComment(msg: NetMessage): OnchainComment {
  let metadata: CommentMetadata | undefined;

  try {
    // Decode hex data to JSON if present
    if (msg.data && msg.data !== "0x") {
      const hex = msg.data.startsWith("0x") ? msg.data.slice(2) : msg.data;
      const bytes = new Uint8Array(hex.length / 2);
      for (let i = 0; i < hex.length; i += 2) {
        bytes[i / 2] = parseInt(hex.slice(i, i + 2), 16);
      }
      const jsonStr = new TextDecoder().decode(bytes);
      metadata = JSON.parse(jsonStr);
    }
  } catch {
    // Ignore parse errors - data field is optional
  }

  return {
    id: `${msg.sender}-${msg.timestamp.toString()}`,
    sender: msg.sender,
    text: msg.text,
    timestamp: Number(msg.timestamp) * 1000, // Convert to milliseconds
    username: metadata?.username,
    pfpUrl: metadata?.pfpUrl,
    parentCommentId: metadata?.parentCommentId,
    isAgent: metadata?.isAgent,
  };
}

// Convert string to hex
function stringToHex(str: string): `0x${string}` {
  const bytes = new TextEncoder().encode(str);
  let hex = "0x";
  for (let i = 0; i < bytes.length; i++) {
    hex += bytes[i].toString(16).padStart(2, "0");
  }
  return hex as `0x${string}`;
}

/**
 * FeedClient for preparing transactions
 */
class FeedClient {
  private netClient: NetClientType;

  constructor(params: { chainId: number }) {
    this.netClient = new NetClient({ chainId: params.chainId });
  }

  preparePostToFeed(params: { topic: string; text: string; data: string }) {
    const dataHex = stringToHex(params.data);
    return this.netClient.prepareSendMessage({
      topic: params.topic,
      text: params.text,
      data: dataHex,
    });
  }
}

/**
 * Hook for reading and writing onchain comments via Net Protocol
 *
 * Each book's comments are stored in a topic: "book-{contentKey}"
 * The comment text goes in `text`, and author metadata (username, pfp) goes in `data` as JSON.
 */
export function useOnchainComments(contentKey?: string) {
  const { address } = useAccount();
  const [isPosting, setIsPosting] = useState(false);
  const [postError, setPostError] = useState<string | null>(null);
  const [posts, setPosts] = useState<NetMessage[]>([]);
  const [totalCount, setTotalCount] = useState(0);
  const [isLoading, setIsLoading] = useState(true);

  // Topic for this book's comments
  const topic = contentKey ? `book-${contentKey}` : "";

  const netClient = useMemo(() => {
    return new NetClient({ chainId: BASE_CHAIN_ID });
  }, []);

  // Fetch comments from Net Protocol
  useEffect(() => {
    if (!contentKey) {
      setIsLoading(false);
      return;
    }

    let isMounted = true;

    async function fetchMessages() {
      setIsLoading(true);
      try {
        // Get total count for the topic
        const count = await netClient.getMessageCount({
          filter: {
            appAddress: "0x0000000000000000000000000000000000000000" as `0x${string}`,
            topic,
          },
        });

        if (!isMounted) return;
        setTotalCount(count);

        // Fetch last 100 messages
        const maxMessages = 100;
        const startIndex = Math.max(0, count - maxMessages);
        const endIndex = count;

        if (startIndex < endIndex) {
          const messages = await netClient.getMessages({
            filter: {
              appAddress: "0x0000000000000000000000000000000000000000" as `0x${string}`,
              topic,
            },
            startIndex: startIndex,
            endIndex: endIndex,
          });

          if (!isMounted) return;
          setPosts(messages as NetMessage[]);
        }
      } catch (error) {
        console.error("[useOnchainComments] Fetch error:", error);
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    }

    fetchMessages();

    return () => {
      isMounted = false;
    };
  }, [contentKey, topic, netClient]);

  // Parse messages into flat comment list
  const flatComments: OnchainComment[] = useMemo(() => {
    if (!posts || posts.length === 0) return [];
    return posts.map(parseComment);
  }, [posts]);

  // Build threaded tree structure sorted by upvotes then timestamp
  // Top-level comments are sorted by upvotes (desc), then timestamp (newest first for ties)
  // Replies are sorted chronologically (oldest first to read conversation top to bottom)
  const comments: OnchainComment[] = useMemo(() => {
    if (flatComments.length === 0) return [];

    // Separate top-level comments and replies
    const topLevel = flatComments.filter(c => !c.parentCommentId);
    const replies = flatComments.filter(c => c.parentCommentId);

    // Build a map of parentId -> replies
    const replyMap = new Map<string, OnchainComment[]>();
    for (const reply of replies) {
      const parentId = reply.parentCommentId!;
      if (!replyMap.has(parentId)) {
        replyMap.set(parentId, []);
      }
      replyMap.get(parentId)!.push(reply);
    }

    // Recursively attach replies and count them
    function attachReplies(comment: OnchainComment): OnchainComment {
      const directReplies = replyMap.get(comment.id) || [];

      // Sort replies chronologically (oldest first for reading)
      directReplies.sort((a, b) => a.timestamp - b.timestamp);

      // Recursively process each reply
      const processedReplies = directReplies.map(attachReplies);

      // Count total replies (direct + nested)
      const totalReplyCount = directReplies.length +
        processedReplies.reduce((sum, r) => sum + (r.replyCount || 0), 0);

      return {
        ...comment,
        replies: processedReplies,
        replyCount: totalReplyCount,
      };
    }

    // Attach replies to top-level comments
    const threaded = topLevel.map(attachReplies);

    // Sort top-level by upvotes (desc), then by timestamp (newest first for ties)
    threaded.sort((a, b) => {
      const upvoteDiff = (b.upvotes || 0) - (a.upvotes || 0);
      if (upvoteDiff !== 0) return upvoteDiff;
      return b.timestamp - a.timestamp; // Newest first for ties
    });

    return threaded;
  }, [flatComments]);

  // Setup write contract for posting
  const { writeContractAsync, data: txHash } = useWriteContract();
  const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({
    hash: txHash,
  });

  // Create a FeedClient for preparing transactions
  const feedClient = useMemo(() => {
    return new FeedClient({ chainId: BASE_CHAIN_ID });
  }, []);

  // Post a new comment onchain (or reply to an existing comment)
  const postComment = useCallback(async (
    text: string,
    options?: { username?: string; pfpUrl?: string; parentCommentId?: string; isAgent?: boolean }
  ): Promise<boolean> => {
    if (!contentKey || !address || !text.trim()) {
      setPostError("Missing required fields");
      return false;
    }

    setIsPosting(true);
    setPostError(null);

    try {
      // Prepare metadata for the data field (v2 supports threading, v2.1 adds agent tracking)
      const metadata: CommentMetadata = {
        version: 2,
        ...(options?.username && { username: options.username }),
        ...(options?.pfpUrl && { pfpUrl: options.pfpUrl }),
        ...(options?.parentCommentId && { parentCommentId: options.parentCommentId }),
        ...(options?.isAgent && { isAgent: options.isAgent }),
      };

      // Prepare the transaction using FeedClient
      const txConfig = feedClient.preparePostToFeed({
        topic: `book-${contentKey}`,
        text: text.trim().slice(0, 500), // Limit to 500 chars
        data: JSON.stringify(metadata),
      });

      // Submit the transaction
      await writeContractAsync({
        address: txConfig.to,
        abi: txConfig.abi,
        functionName: txConfig.functionName,
        args: txConfig.args,
        value: txConfig.value,
      });

      // Track successful comment post
      trackComment.post(contentKey, address, true, "success");

      return true;
    } catch (err) {
      console.error("[useOnchainComments] Post error:", err);
      const errorMsg = err instanceof Error ? err.message : "Failed to post comment";
      setPostError(errorMsg);

      // Track failed comment post
      trackComment.post(contentKey, address, true, "error", errorMsg);

      return false;
    } finally {
      setIsPosting(false);
    }
  }, [contentKey, address, feedClient, writeContractAsync]);

  // Get all comment IDs for upvote fetching (including nested replies)
  const allCommentIds = useMemo(() => {
    return flatComments.map(c => c.id);
  }, [flatComments]);

  return {
    comments, // Threaded tree structure
    flatComments, // Flat list for iteration
    allCommentIds, // All IDs for upvote count fetching
    totalCount,
    isLoading,
    postComment,
    isPosting: isPosting || isConfirming,
    isConfirmed,
    postError,
  };
}

// Backwards compatibility alias
export { useOnchainComments as useComments };
src/hooks/use-connectivity.ts
"use client";

import { useState, useEffect } from "react";

/**
 * Hook to monitor network connectivity status
 * Returns isOnline and a method to manually check connectivity
 */
export function useConnectivity() {
  const [isOnline, setIsOnline] = useState(
    typeof window !== "undefined" ? navigator.onLine : true
  );
  const [wasOffline, setWasOffline] = useState(false);

  useEffect(() => {
    const handleOnline = () => {
      console.log("[Connectivity] Back online");
      setIsOnline(true);
      // Mark that we were offline so UI can show "reconnected" message
      setWasOffline(true);
      // Clear the wasOffline flag after a short delay
      setTimeout(() => setWasOffline(false), 3000);
    };

    const handleOffline = () => {
      console.log("[Connectivity] Went offline");
      setIsOnline(false);
    };

    window.addEventListener("online", handleOnline);
    window.addEventListener("offline", handleOffline);

    return () => {
      window.removeEventListener("online", handleOnline);
      window.removeEventListener("offline", handleOffline);
    };
  }, []);

  return { isOnline, wasOffline };
}
src/hooks/use-cover-upload.ts
"use client";

import { useCallback, useState } from "react";

interface UploadCoverResult {
  success: boolean;
  url?: string;
  error?: string;
}

/**
 * Hook to upload base64 cover images to hosted storage
 * Returns a permanent URL that can be used in share images
 */
export function useCoverUpload() {
  const [isUploading, setIsUploading] = useState(false);

  /**
   * Upload a base64 data URL to get a hosted URL
   * @param dataUrl - Base64 data URL (e.g., "data:image/jpeg;base64,...")
   * @param contentKey - Optional content key for filename
   * @returns Hosted URL or null if upload fails
   */
  const uploadCover = useCallback(async (
    dataUrl: string,
    contentKey?: string
  ): Promise<UploadCoverResult> => {
    // Skip if not a data URL (already a hosted URL)
    if (!dataUrl.startsWith("data:")) {
      return { success: true, url: dataUrl };
    }

    setIsUploading(true);

    try {
      const response = await fetch("/api/upload-cover", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ dataUrl, contentKey }),
      });

      const result = await response.json();

      if (!response.ok) {
        console.error("[useCoverUpload] Upload failed:", result.error);
        return {
          success: false,
          error: result.error || "Upload failed",
        };
      }

      console.log("[useCoverUpload] Cover uploaded:", result.url);
      return {
        success: true,
        url: result.url,
      };
    } catch (error) {
      console.error("[useCoverUpload] Error:", error);
      return {
        success: false,
        error: error instanceof Error ? error.message : "Unknown error",
      };
    } finally {
      setIsUploading(false);
    }
  }, []);

  /**
   * Check if a cover URL needs to be uploaded (is base64)
   */
  const needsUpload = useCallback((coverUrl: string | undefined): boolean => {
    return !!coverUrl && coverUrl.startsWith("data:");
  }, []);

  return {
    uploadCover,
    needsUpload,
    isUploading,
  };
}
src/hooks/use-desktop-mode.ts
"use client";

/**
 * Desktop Mode Detection Hook
 *
 * Detects if the user is viewing the app in a desktop web browser
 * (NOT mobile, NOT Farcaster Mini App, NOT Coinbase Wallet browser).
 *
 * This is used to conditionally enable desktop-optimized UI features like:
 * - Wider layouts (up to 600-800px)
 * - Side-by-side panels
 * - Hover effects
 * - Right-click context menus
 * - Smaller/denser touch targets
 * - Multi-column grids
 * - Persistent headers with more actions
 *
 * CRITICAL: Desktop features MUST NOT affect mobile or in-app browser experiences!
 */

import { useState, useEffect, useMemo } from "react";
import { detectDesktopBrowser, useAppMode } from "@/lib/app-mode";

export interface DesktopModeState {
  // Core detection
  isDesktop: boolean;

  // Viewport info
  viewportWidth: number;
  viewportHeight: number;

  // Breakpoint helpers
  isWideDesktop: boolean;  // > 1024px - full side-by-side panels
  isMediumDesktop: boolean; // 768-1024px - wider single column

  // Feature flags
  canShowHoverEffects: boolean;
  canShowContextMenus: boolean;
  canUseSmallerTouchTargets: boolean;
  canShowMultiColumnGrids: boolean;
}

// Default state (mobile-first)
const defaultState: DesktopModeState = {
  isDesktop: false,
  viewportWidth: 424, // Farcaster default
  viewportHeight: 800,
  isWideDesktop: false,
  isMediumDesktop: false,
  canShowHoverEffects: false,
  canShowContextMenus: false,
  canUseSmallerTouchTargets: false,
  canShowMultiColumnGrids: false,
};

/**
 * Hook to detect desktop mode and provide desktop-specific feature flags
 */
export function useDesktopMode(): DesktopModeState {
  const appMode = useAppMode();
  const [state, setState] = useState<DesktopModeState>(defaultState);

  // Initial detection on mount + resize listener
  useEffect(() => {
    if (typeof window === "undefined") return;

    const updateState = () => {
      const isDesktop = detectDesktopBrowser();
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;

      // Only enable desktop features if:
      // 1. detectDesktopBrowser() returns true
      // 2. appMode is "web" (not farcaster or base-app)
      // 3. Viewport is wide enough
      const isActuallyDesktop = isDesktop && appMode === "web";

      const isWideDesktop = isActuallyDesktop && viewportWidth >= 1024;
      const isMediumDesktop = isActuallyDesktop && viewportWidth >= 768 && viewportWidth < 1024;

      setState({
        isDesktop: isActuallyDesktop,
        viewportWidth,
        viewportHeight,
        isWideDesktop,
        isMediumDesktop,
        // Only enable hover effects on actual desktop with pointer device
        canShowHoverEffects: isActuallyDesktop && !("ontouchstart" in window),
        // Context menus only on desktop
        canShowContextMenus: isActuallyDesktop,
        // Smaller touch targets only on desktop (no touch)
        canUseSmallerTouchTargets: isActuallyDesktop && !("ontouchstart" in window),
        // Multi-column grids on medium+ desktop
        canShowMultiColumnGrids: isActuallyDesktop && viewportWidth >= 768,
      });
    };

    // Initial check
    updateState();

    // Update on resize
    window.addEventListener("resize", updateState);
    return () => window.removeEventListener("resize", updateState);
  }, [appMode]);

  return state;
}

/**
 * CSS class generator for desktop-responsive styles
 *
 * Usage:
 * ```tsx
 * const { isDesktop } = useDesktopMode();
 * <div className={desktopClasses(isDesktop, "p-4", "p-6 max-w-[800px] mx-auto")}>
 * ```
 *
 * @param isDesktop - Whether desktop mode is active
 * @param mobileClasses - Classes to apply on mobile (always applied)
 * @param desktopClasses - Additional classes to apply on desktop
 */
export function desktopClasses(
  isDesktop: boolean,
  mobileClasses: string,
  desktopClasses?: string
): string {
  if (!isDesktop || !desktopClasses) return mobileClasses;
  return `${mobileClasses} ${desktopClasses}`;
}

/**
 * Get responsive container classes based on desktop mode
 *
 * Returns classes for:
 * - Mobile: Full width (424px max on Farcaster)
 * - Medium desktop (768-1024px): Wider container (~600px)
 * - Wide desktop (1024px+): Full wide container (~800px)
 */
export function useResponsiveContainer(): string {
  const { isWideDesktop, isMediumDesktop } = useDesktopMode();

  return useMemo(() => {
    if (isWideDesktop) {
      return "max-w-[800px] mx-auto px-6";
    }
    if (isMediumDesktop) {
      return "max-w-[600px] mx-auto px-4";
    }
    // Mobile - no max width, standard padding
    return "";
  }, [isWideDesktop, isMediumDesktop]);
}

/**
 * Get grid columns based on viewport and desktop mode
 *
 * @param mobileColumns - Columns on mobile (default 1)
 * @param desktopColumns - Columns on desktop (default 2)
 */
export function useGridColumns(
  mobileColumns: number = 1,
  desktopColumns: number = 2
): number {
  const { canShowMultiColumnGrids, isWideDesktop } = useDesktopMode();

  return useMemo(() => {
    if (!canShowMultiColumnGrids) return mobileColumns;
    // Wide desktop can show more columns
    if (isWideDesktop) return Math.min(desktopColumns + 1, 3);
    return desktopColumns;
  }, [canShowMultiColumnGrids, isWideDesktop, mobileColumns, desktopColumns]);
}
src/hooks/use-discovery-index.ts
"use client";

import { useState, useEffect, useCallback } from "react";
import {
  type DiscoveryEntry,
  getCdnUrl,
  BASE_CHAIN_ID,
} from "@/lib/net-protocol";

export function useDiscoveryIndex() {
  const [entries, setEntries] = useState<DiscoveryEntry[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      // Fetch from our local API (backed by KV database)
      const response = await fetch("/api/discovery");
      if (!response.ok) {
        throw new Error("Failed to fetch discovery index");
      }
      const data = await response.json();
      const index = data.entries || [];
      // Sort by uploadedAt descending (newest first)
      const sorted = index.sort((a: DiscoveryEntry, b: DiscoveryEntry) => b.uploadedAt - a.uploadedAt);
      setEntries(sorted);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to fetch index");
    } finally {
      setIsLoading(false);
    }
  }, []);

  // Fetch on mount
  useEffect(() => {
    refresh();
  }, [refresh]);

  // Helper to get CDN URL for an entry
  // Prefers: stored cdnUrl > /storage/load/ with fileName > /storage/raw/ fallback
  const getCdnUrlForEntry = useCallback((entry: DiscoveryEntry) => {
    // Use stored cdnUrl if available (preferred)
    if (entry.cdnUrl) return entry.cdnUrl;
    // Use fileName for /storage/load/ format if available
    return getCdnUrl(BASE_CHAIN_ID, entry.operator, entry.contentKey, entry.storageType, entry.fileName);
  }, []);

  // Filter entries by category
  const filterByCategory = useCallback(
    (category: string) => {
      if (category === "all") return entries;
      return entries.filter((e) => (e.categories || []).includes(category));
    },
    [entries]
  );

  // Full-text search across title, author, description, categories, and publisher
  const search = useCallback(
    (query: string) => {
      const lower = query.toLowerCase().trim();
      if (!lower) return entries;

      return entries.filter((e) => {
        // Search in title
        if ((e.title || '').toLowerCase().includes(lower)) return true;

        // Search in author
        if ((e.author || '').toLowerCase().includes(lower)) return true;

        // Search in publisher (if exists)
        if ((e.publisher || '').toLowerCase().includes(lower)) return true;

        // Search in categories
        if ((e.categories || []).some(cat => cat.toLowerCase().includes(lower))) return true;

        // Search in uploader username (if exists)
        if ((e.uploaderUsername || '').toLowerCase().includes(lower)) return true;

        return false;
      });
    },
    [entries]
  );

  // Get recent uploads (last N)
  const getRecent = useCallback(
    (count: number = 5) => {
      return entries.slice(0, count);
    },
    [entries]
  );

  return {
    entries,
    isLoading,
    error,
    refresh,
    getCdnUrlForEntry,
    filterByCategory,
    search,
    getRecent,
  };
}
src/hooks/use-engagement.ts
"use client";

import { useState, useEffect, useCallback, useRef } from "react";

export interface BookEngagementStats {
  opens: number;
  currentlyReading: number;
  addedToQueues: number;
}

export function useEngagement(contentKey?: string, userAddress?: string) {
  const [stats, setStats] = useState<BookEngagementStats>({
    opens: 0,
    currentlyReading: 0,
    addedToQueues: 0,
  });
  const [isLoading, setIsLoading] = useState(true);
  const heartbeatInterval = useRef<NodeJS.Timeout | null>(null);

  // Fetch engagement stats for a book
  const fetchStats = useCallback(async () => {
    if (!contentKey) {
      setIsLoading(false);
      return;
    }

    try {
      const response = await fetch(
        `/api/engagement?contentKey=${encodeURIComponent(contentKey)}`
      );
      const data = await response.json();

      if (response.ok) {
        setStats({
          opens: data.opens || 0,
          currentlyReading: data.currentlyReading || 0,
          addedToQueues: data.addedToQueues || 0,
        });
      }
    } catch (err) {
      console.error("Fetch engagement error:", err);
    } finally {
      setIsLoading(false);
    }
  }, [contentKey]);

  useEffect(() => {
    fetchStats();
  }, [fetchStats]);

  // Record an open event
  const recordOpen = useCallback(async () => {
    if (!contentKey) return;

    try {
      await fetch("/api/engagement", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "open",
          contentKey,
        }),
      });

      // Update local stats optimistically
      setStats((prev) => ({ ...prev, opens: prev.opens + 1 }));
    } catch (err) {
      console.error("Record open error:", err);
    }
  }, [contentKey]);

  // Start reading - tracks user as active reader
  const startReading = useCallback(async () => {
    if (!contentKey || !userAddress) return;

    try {
      const response = await fetch("/api/engagement", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "start-reading",
          contentKey,
          userAddress,
        }),
      });

      const data = await response.json();
      if (response.ok && data.stats) {
        setStats(data.stats);
      }

      // Start heartbeat to keep reading status active
      if (heartbeatInterval.current) {
        clearInterval(heartbeatInterval.current);
      }

      heartbeatInterval.current = setInterval(async () => {
        try {
          await fetch("/api/engagement", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              action: "heartbeat",
              contentKey,
              userAddress,
            }),
          });
        } catch {
          // Ignore heartbeat errors
        }
      }, 60000); // Every minute
    } catch (err) {
      console.error("Start reading error:", err);
    }
  }, [contentKey, userAddress]);

  // Stop reading - removes user from active readers
  const stopReading = useCallback(async () => {
    if (!contentKey || !userAddress) return;

    // Clear heartbeat
    if (heartbeatInterval.current) {
      clearInterval(heartbeatInterval.current);
      heartbeatInterval.current = null;
    }

    try {
      const response = await fetch("/api/engagement", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "stop-reading",
          contentKey,
          userAddress,
        }),
      });

      const data = await response.json();
      if (response.ok && data.stats) {
        setStats(data.stats);
      }
    } catch (err) {
      console.error("Stop reading error:", err);
    }
  }, [contentKey, userAddress]);

  // Record adding to queue
  const recordAddToQueue = useCallback(async () => {
    if (!contentKey || !userAddress) return;

    try {
      const response = await fetch("/api/engagement", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "add-to-queue",
          contentKey,
          userAddress,
        }),
      });

      const data = await response.json();
      if (response.ok && data.stats) {
        setStats(data.stats);
      }
    } catch (err) {
      console.error("Record add to queue error:", err);
    }
  }, [contentKey, userAddress]);

  // Record removing from queue
  const recordRemoveFromQueue = useCallback(async () => {
    if (!contentKey || !userAddress) return;

    try {
      const response = await fetch("/api/engagement", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "remove-from-queue",
          contentKey,
          userAddress,
        }),
      });

      const data = await response.json();
      if (response.ok && data.stats) {
        setStats(data.stats);
      }
    } catch (err) {
      console.error("Record remove from queue error:", err);
    }
  }, [contentKey, userAddress]);

  // Cleanup heartbeat on unmount
  useEffect(() => {
    return () => {
      if (heartbeatInterval.current) {
        clearInterval(heartbeatInterval.current);
      }
    };
  }, []);

  return {
    stats,
    isLoading,
    refresh: fetchStats,
    recordOpen,
    startReading,
    stopReading,
    recordAddToQueue,
    recordRemoveFromQueue,
  };
}

// Hook to fetch engagement stats for multiple books at once
export function useBulkEngagement(contentKeys: string[]) {
  const [stats, setStats] = useState<{
    [key: string]: BookEngagementStats;
  }>({});
  const [isLoading, setIsLoading] = useState(true);

  // Create a stable key from contentKeys for dependency tracking
  const contentKeysKey = contentKeys.join(",");

  const fetchBulkStats = useCallback(async () => {
    if (contentKeys.length === 0) {
      setStats({});
      setIsLoading(false);
      return;
    }

    try {
      const response = await fetch(
        `/api/engagement?contentKeys=${encodeURIComponent(contentKeys.join(","))}`
      );
      const data = await response.json();

      if (response.ok && data.stats) {
        setStats(data.stats);
      }
    } catch (err) {
      console.error("Fetch bulk engagement error:", err);
    } finally {
      setIsLoading(false);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [contentKeysKey]);

  useEffect(() => {
    fetchBulkStats();
  }, [fetchBulkStats]);

  return {
    stats,
    isLoading,
    refresh: fetchBulkStats,
    getStats: (key: string) =>
      stats[key] || { opens: 0, currentlyReading: 0, addedToQueues: 0 },
  };
}
src/hooks/use-epub-cover.ts
"use client";

import { useState, useCallback } from "react";

interface ExtractedCover {
  dataUrl: string;
  width: number;
  height: number;
}

/**
 * Hook for extracting cover images from EPUB files
 * EPUBs are ZIP files containing images - we look for the cover in the manifest
 */
export function useEpubCover() {
  const [isExtracting, setIsExtracting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  /**
   * Extract cover image from EPUB
   * @param source - File object or CDN URL to the XML-stored EPUB
   * @param maxWidth - Maximum width for the cover (default: 400)
   * @returns Promise with data URL of the cover image
   */
  const extractCover = useCallback(async (
    source: File | string,
    maxWidth: number = 400
  ): Promise<ExtractedCover | null> => {
    // Ensure we're in browser environment
    if (typeof window === "undefined") {
      return null;
    }

    setIsExtracting(true);
    setError(null);

    try {
      // Dynamic import JSZip
      const JSZip = (await import("jszip")).default;

      // Load EPUB content
      let epubData: ArrayBuffer;

      if (source instanceof File) {
        epubData = await source.arrayBuffer();
      } else {
        // Fetch from URL
        const response = await fetch(source);
        if (!response.ok) {
          throw new Error(`Failed to fetch EPUB: ${response.status}`);
        }
        epubData = await response.arrayBuffer();
      }

      // Load ZIP
      const zip = new JSZip();
      const contents = await zip.loadAsync(epubData);

      // Find container.xml to locate OPF
      const containerXml = await contents.file("META-INF/container.xml")?.async("string");
      if (!containerXml) {
        throw new Error("Invalid EPUB: Missing container.xml");
      }

      // Extract OPF path
      const opfPathMatch = containerXml.match(/full-path="([^"]+\.opf)"/i);
      if (!opfPathMatch) {
        throw new Error("Invalid EPUB: Cannot find OPF file path");
      }

      const opfPath = opfPathMatch[1];
      const opfDir = opfPath.substring(0, opfPath.lastIndexOf("/") + 1);

      // Parse OPF file
      const opfContent = await contents.file(opfPath)?.async("string");
      if (!opfContent) {
        throw new Error("Invalid EPUB: Cannot read OPF file");
      }

      // Strategy 1: Look for cover in metadata (most common)
      // <meta name="cover" content="cover-image-id"/>
      let coverHref: string | null = null;
      const coverMetaMatch = opfContent.match(/<meta[^>]+name="cover"[^>]+content="([^"]+)"[^>]*>/i)
        || opfContent.match(/<meta[^>]+content="([^"]+)"[^>]+name="cover"[^>]*>/i);

      if (coverMetaMatch) {
        const coverId = coverMetaMatch[1];
        // Find the item with this id
        const itemMatch = opfContent.match(new RegExp(`<item[^>]+id="${coverId}"[^>]+href="([^"]+)"[^>]*>`, "i"))
          || opfContent.match(new RegExp(`<item[^>]+href="([^"]+)"[^>]+id="${coverId}"[^>]*>`, "i"));
        if (itemMatch) {
          coverHref = decodeURIComponent(itemMatch[1]);
        }
      }

      // Strategy 2: Look for item with properties="cover-image"
      if (!coverHref) {
        const coverPropertyMatch = opfContent.match(/<item[^>]+properties="cover-image"[^>]+href="([^"]+)"[^>]*>/i)
          || opfContent.match(/<item[^>]+href="([^"]+)"[^>]+properties="cover-image"[^>]*>/i);
        if (coverPropertyMatch) {
          coverHref = decodeURIComponent(coverPropertyMatch[1]);
        }
      }

      // Strategy 3: Look for item with id containing "cover" and image media-type
      if (!coverHref) {
        const coverIdMatch = opfContent.match(/<item[^>]+id="[^"]*cover[^"]*"[^>]+href="([^"]+)"[^>]+media-type="image\/[^"]+"/i)
          || opfContent.match(/<item[^>]+href="([^"]+)"[^>]+id="[^"]*cover[^"]*"[^>]+media-type="image\/[^"]+"/i);
        if (coverIdMatch) {
          coverHref = decodeURIComponent(coverIdMatch[1]);
        }
      }

      // Strategy 4: Look for any image file with "cover" in the name
      if (!coverHref) {
        const allPaths = Object.keys(contents.files);
        const coverImagePath = allPaths.find(p =>
          p.toLowerCase().includes("cover") &&
          (p.endsWith(".jpg") || p.endsWith(".jpeg") || p.endsWith(".png") || p.endsWith(".gif"))
        );
        if (coverImagePath) {
          coverHref = coverImagePath;
        }
      }

      if (!coverHref) {
        console.log("[useEpubCover] No cover image found in EPUB");
        setIsExtracting(false);
        return null;
      }

      // Resolve cover path relative to OPF directory
      let coverPath = coverHref;
      if (!coverHref.startsWith("/") && opfDir) {
        // Handle relative paths
        if (coverHref.startsWith("../")) {
          const parts = opfDir.split("/").filter(p => p);
          const hrefParts = coverHref.split("/");
          for (const part of hrefParts) {
            if (part === "..") {
              parts.pop();
            } else if (part !== ".") {
              parts.push(part);
            }
          }
          coverPath = parts.join("/");
        } else {
          coverPath = opfDir + coverHref;
        }
      }

      // Try to get the cover image
      let coverFile = contents.file(coverPath);

      // Fallback: try without directory prefix
      if (!coverFile && coverHref !== coverPath) {
        coverFile = contents.file(coverHref);
      }

      // Fallback: search for file ending with the cover filename
      if (!coverFile) {
        const coverFilename = coverHref.split("/").pop() || coverHref;
        const allPaths = Object.keys(contents.files);
        const matchingPath = allPaths.find(p => p.endsWith(coverFilename));
        if (matchingPath) {
          coverFile = contents.file(matchingPath);
        }
      }

      if (!coverFile) {
        console.log("[useEpubCover] Cover file not found in ZIP:", coverPath);
        setIsExtracting(false);
        return null;
      }

      // Extract image data
      const imageData = await coverFile.async("base64");

      // Determine MIME type
      const ext = coverPath.split(".").pop()?.toLowerCase() || "jpeg";
      const mimeType = ext === "png" ? "image/png" : ext === "gif" ? "image/gif" : "image/jpeg";

      // Create data URL
      const originalDataUrl = `data:${mimeType};base64,${imageData}`;

      // Load image to get dimensions and optionally resize
      const img = new Image();
      await new Promise<void>((resolve, reject) => {
        img.onload = () => resolve();
        img.onerror = () => reject(new Error("Failed to load cover image"));
        img.src = originalDataUrl;
      });

      // Resize if needed
      let dataUrl = originalDataUrl;
      let width = img.width;
      let height = img.height;

      if (img.width > maxWidth) {
        const scale = maxWidth / img.width;
        width = maxWidth;
        height = Math.round(img.height * scale);

        const canvas = document.createElement("canvas");
        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext("2d");
        if (ctx) {
          ctx.drawImage(img, 0, 0, width, height);
          dataUrl = canvas.toDataURL("image/jpeg", 0.85);
        }
      }

      setIsExtracting(false);
      return { dataUrl, width, height };

    } catch (err) {
      console.error("[useEpubCover] Extraction error:", err);
      setError(err instanceof Error ? err.message : "Failed to extract cover");
      setIsExtracting(false);
      return null;
    }
  }, []);

  return {
    extractCover,
    isExtracting,
    error,
  };
}
src/hooks/use-farcaster-link-callback.ts
"use client";

import { useEffect, useState, useCallback } from "react";

// Storage key for pending link operation
const PENDING_LINK_KEY = "nl_pending_farcaster_link";

interface PendingLinkData {
  mode: "link" | "claim";
  address: string;
  memberId: number | null;
  timestamp: number;
}

interface AuthCallbackResult {
  fid: number;
  pendingData: PendingLinkData;
}

/**
 * Hook to detect and handle Farcaster auth callback at the app level.
 *
 * This handles the redirect back from Neynar's auth page.
 * When detected, it:
 * 1. Extracts the FID from URL params
 * 2. Retrieves pending link data from localStorage
 * 3. Cleans up the URL
 * 4. Returns the callback data for the LinkFarcasterModal to process
 */
export function useFarcasterLinkCallback() {
  const [callbackData, setCallbackData] = useState<AuthCallbackResult | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);

  // Check for callback on mount
  useEffect(() => {
    if (typeof window === "undefined") return;

    const urlParams = new URLSearchParams(window.location.search);
    const fid = urlParams.get("fid");
    const signerUuid = urlParams.get("signer_uuid");

    // Neynar returns fid and signer_uuid on success
    if (fid && signerUuid) {
      console.log("[FarcasterLinkCallback] Detected auth callback, FID:", fid, "signer_uuid:", signerUuid);
      setIsProcessing(true);

      // Get pending link data
      const pendingDataStr = localStorage.getItem(PENDING_LINK_KEY);
      if (pendingDataStr) {
        try {
          const pendingData: PendingLinkData = JSON.parse(pendingDataStr);

          // Check if data is stale (older than 10 minutes)
          if (Date.now() - pendingData.timestamp <= 10 * 60 * 1000) {
            setCallbackData({
              fid: parseInt(fid, 10),
              pendingData,
            });
          } else {
            console.log("[FarcasterLinkCallback] Session expired");
            localStorage.removeItem(PENDING_LINK_KEY);
          }
        } catch (e) {
          console.error("[FarcasterLinkCallback] Failed to parse pending data:", e);
        }
      } else {
        console.log("[FarcasterLinkCallback] No pending link data found");
      }

      // Note: Don't clean URL here - let the modal do it after processing
      setIsProcessing(false);
    }
  }, []);

  // Clear the callback data after it's been processed
  const clearCallback = useCallback(() => {
    setCallbackData(null);
    localStorage.removeItem(PENDING_LINK_KEY);
  }, []);

  return {
    callbackData,
    isProcessing,
    clearCallback,
    hasPendingCallback: !!callbackData,
  };
}
src/hooks/use-grid-archive.ts
"use client";

import { useState, useCallback, useEffect } from "react";
import type { ArchivedGrid, GridCell } from "@/lib/net-protocol";

interface UseGridArchiveOptions {
  gridId?: string;
  creator?: string;
  autoFetch?: boolean;
}

export function useGridArchive(options: UseGridArchiveOptions = {}) {
  const { gridId, creator, autoFetch = true } = options;

  const [archives, setArchives] = useState<ArchivedGrid[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Fetch archives
  const fetchArchives = useCallback(async () => {
    if (!gridId && !creator) return;

    setIsLoading(true);
    setError(null);

    try {
      const params = new URLSearchParams();
      if (gridId) params.set("gridId", gridId);
      if (creator) params.set("creator", creator);

      const response = await fetch(`/api/grids/archive?${params.toString()}`);
      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || "Failed to fetch archives");
      }

      setArchives(data.archives || []);
    } catch (err) {
      const message = err instanceof Error ? err.message : "Unknown error";
      setError(message);
      console.error("[useGridArchive] Fetch error:", err);
    } finally {
      setIsLoading(false);
    }
  }, [gridId, creator]);

  // Auto-fetch on mount
  useEffect(() => {
    if (autoFetch && (gridId || creator)) {
      fetchArchives();
    }
  }, [autoFetch, gridId, creator, fetchArchives]);

  // Create archive
  const createArchive = useCallback(
    async (
      targetGridId: string,
      creatorAddress: string,
      contentKey?: string,
      creatorFid?: number,
      archiveInfo?: { cdnUrl?: string; fileName?: string; operator?: string }
    ): Promise<{ archive: ArchivedGrid; cells: GridCell[] } | null> => {
      try {
        const response = await fetch("/api/grids/archive", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            gridId: targetGridId,
            creator: creatorAddress,
            creatorFid,
            contentKey,
            cdnUrl: archiveInfo?.cdnUrl,
            fileName: archiveInfo?.fileName,
            operator: archiveInfo?.operator,
          }),
        });

        const data = await response.json();

        if (!data.success) {
          throw new Error(data.error || "Failed to create archive");
        }

        // Refresh archives list
        if (gridId === targetGridId || creator === creatorAddress) {
          await fetchArchives();
        }

        return { archive: data.archive, cells: data.cells };
      } catch (err) {
        const message = err instanceof Error ? err.message : "Unknown error";
        setError(message);
        console.error("[useGridArchive] Create error:", err);
        return null;
      }
    },
    [gridId, creator, fetchArchives]
  );

  return {
    archives,
    isLoading,
    error,
    refresh: fetchArchives,
    createArchive,
  };
}

// Helper: Generate PNG with embedded metadata
// This uses the canvas API to render and embed metadata in tEXt chunks
export async function generateArchivePNG(
  gridName: string,
  gridSize: number,
  cells: GridCell[],
  cellImageUrls: Map<string, string> // Map of "row-col" to loaded image data URLs
): Promise<Blob> {
  const cellSize = 100; // Each cell is 100x100 pixels
  const padding = 2;
  const canvasSize = gridSize * (cellSize + padding) + padding;

  // Create canvas
  const canvas = document.createElement("canvas");
  canvas.width = canvasSize;
  canvas.height = canvasSize;
  const ctx = canvas.getContext("2d")!;

  // Fill background
  ctx.fillStyle = "#0a0a0a";
  ctx.fillRect(0, 0, canvasSize, canvasSize);

  // Draw cell borders
  ctx.strokeStyle = "rgba(0, 255, 0, 0.15)";
  ctx.lineWidth = 1;

  for (let row = 0; row < gridSize; row++) {
    for (let col = 0; col < gridSize; col++) {
      const x = padding + col * (cellSize + padding);
      const y = padding + row * (cellSize + padding);

      // Draw cell background
      ctx.fillStyle = "#111111";
      ctx.fillRect(x, y, cellSize, cellSize);

      // Draw cell border
      ctx.strokeRect(x, y, cellSize, cellSize);

      // Draw cell content if exists
      const key = `${row}-${col}`;
      const imageDataUrl = cellImageUrls.get(key);
      if (imageDataUrl) {
        try {
          const img = new Image();
          img.crossOrigin = "anonymous";
          await new Promise<void>((resolve, reject) => {
            img.onload = () => resolve();
            img.onerror = reject;
            img.src = imageDataUrl;
          });

          // Draw image centered/covered
          const imgAspect = img.width / img.height;
          let drawWidth = cellSize;
          let drawHeight = cellSize;
          let offsetX = 0;
          let offsetY = 0;

          if (imgAspect > 1) {
            drawWidth = cellSize * imgAspect;
            offsetX = -(drawWidth - cellSize) / 2;
          } else {
            drawHeight = cellSize / imgAspect;
            offsetY = -(drawHeight - cellSize) / 2;
          }

          ctx.save();
          ctx.beginPath();
          ctx.rect(x, y, cellSize, cellSize);
          ctx.clip();
          ctx.drawImage(img, x + offsetX, y + offsetY, drawWidth, drawHeight);
          ctx.restore();
        } catch {
          // Draw placeholder for failed images
          ctx.fillStyle = "rgba(0, 255, 0, 0.1)";
          ctx.fillRect(x, y, cellSize, cellSize);
        }
      } else {
        // Draw empty cell indicator
        ctx.fillStyle = "rgba(0, 255, 0, 0.05)";
        ctx.fillRect(x, y, cellSize, cellSize);
      }
    }
  }

  // Convert to blob with embedded metadata
  return new Promise((resolve) => {
    canvas.toBlob(async (blob) => {
      if (!blob) {
        resolve(new Blob([], { type: "image/png" }));
        return;
      }

      // Create metadata to embed
      const metadata = {
        gridName,
        gridSize,
        cellCount: cells.length,
        archivedAt: new Date().toISOString(),
        cells: cells.map((c) => ({
          row: c.row,
          col: c.col,
          cdnUrl: c.cdnUrl,
          title: c.title,
          contentType: c.contentType,
        })),
      };

      // Embed metadata in PNG tEXt chunk
      const pngWithMetadata = await embedPngMetadata(blob, metadata);
      resolve(pngWithMetadata);
    }, "image/png");
  });
}

// Embed metadata in PNG tEXt chunk
// PNG format: signature (8 bytes) + chunks (type + data + CRC)
// We insert a tEXt chunk after IHDR containing our JSON metadata
async function embedPngMetadata(blob: Blob, metadata: object): Promise<Blob> {
  const arrayBuffer = await blob.arrayBuffer();
  const data = new Uint8Array(arrayBuffer);

  // PNG signature is 8 bytes
  const PNG_SIGNATURE_LENGTH = 8;

  // Find the end of IHDR chunk (after signature)
  // Chunk format: 4 bytes length + 4 bytes type + data + 4 bytes CRC
  let offset = PNG_SIGNATURE_LENGTH;

  // Read IHDR chunk length
  const ihdrLength =
    (data[offset] << 24) |
    (data[offset + 1] << 16) |
    (data[offset + 2] << 8) |
    data[offset + 3];

  // Skip past IHDR: length(4) + type(4) + data(ihdrLength) + CRC(4)
  const insertPosition = offset + 4 + 4 + ihdrLength + 4;

  // Create tEXt chunk
  // tEXt format: keyword + null byte + text
  const keyword = "NetLibraryGridArchive";
  const metadataJson = JSON.stringify(metadata);
  const keywordBytes = new TextEncoder().encode(keyword);
  const textBytes = new TextEncoder().encode(metadataJson);

  // tEXt chunk data = keyword + null + text
  const textChunkData = new Uint8Array(keywordBytes.length + 1 + textBytes.length);
  textChunkData.set(keywordBytes, 0);
  textChunkData[keywordBytes.length] = 0; // null separator
  textChunkData.set(textBytes, keywordBytes.length + 1);

  // Create chunk: length(4) + "tEXt"(4) + data + CRC(4)
  const chunkType = new Uint8Array([0x74, 0x45, 0x58, 0x74]); // "tEXt"
  const chunkLength = textChunkData.length;

  // Calculate CRC32 over type + data
  const crcInput = new Uint8Array(4 + textChunkData.length);
  crcInput.set(chunkType, 0);
  crcInput.set(textChunkData, 4);
  const crc = crc32(crcInput);

  // Build complete chunk
  const chunk = new Uint8Array(4 + 4 + textChunkData.length + 4);
  // Length (big-endian)
  chunk[0] = (chunkLength >> 24) & 0xff;
  chunk[1] = (chunkLength >> 16) & 0xff;
  chunk[2] = (chunkLength >> 8) & 0xff;
  chunk[3] = chunkLength & 0xff;
  // Type
  chunk.set(chunkType, 4);
  // Data
  chunk.set(textChunkData, 8);
  // CRC (big-endian)
  chunk[chunk.length - 4] = (crc >> 24) & 0xff;
  chunk[chunk.length - 3] = (crc >> 16) & 0xff;
  chunk[chunk.length - 2] = (crc >> 8) & 0xff;
  chunk[chunk.length - 1] = crc & 0xff;

  // Combine: before insert + new chunk + after insert
  const result = new Uint8Array(data.length + chunk.length);
  result.set(data.subarray(0, insertPosition), 0);
  result.set(chunk, insertPosition);
  result.set(data.subarray(insertPosition), insertPosition + chunk.length);

  return new Blob([result], { type: "image/png" });
}

// CRC32 calculation for PNG chunks
function crc32(data: Uint8Array): number {
  // CRC32 lookup table
  const table: number[] = [];
  for (let i = 0; i < 256; i++) {
    let c = i;
    for (let j = 0; j < 8; j++) {
      c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
    }
    table[i] = c;
  }

  let crc = 0xffffffff;
  for (let i = 0; i < data.length; i++) {
    crc = table[(crc ^ data[i]) & 0xff] ^ (crc >>> 8);
  }
  return (crc ^ 0xffffffff) >>> 0;
}

// Extract metadata from PNG tEXt chunk (for reading archived grids)
export async function extractPngMetadata(blob: Blob): Promise<object | null> {
  try {
    const arrayBuffer = await blob.arrayBuffer();
    const data = new Uint8Array(arrayBuffer);

    const PNG_SIGNATURE_LENGTH = 8;
    let offset = PNG_SIGNATURE_LENGTH;

    while (offset < data.length) {
      // Read chunk length
      const length =
        (data[offset] << 24) |
        (data[offset + 1] << 16) |
        (data[offset + 2] << 8) |
        data[offset + 3];

      // Read chunk type
      const type = String.fromCharCode(
        data[offset + 4],
        data[offset + 5],
        data[offset + 6],
        data[offset + 7]
      );

      if (type === "tEXt") {
        // Read chunk data
        const chunkData = data.subarray(offset + 8, offset + 8 + length);

        // Find null separator between keyword and text
        let nullIndex = 0;
        while (nullIndex < chunkData.length && chunkData[nullIndex] !== 0) {
          nullIndex++;
        }

        const keyword = new TextDecoder().decode(chunkData.subarray(0, nullIndex));

        if (keyword === "NetLibraryGridArchive") {
          const text = new TextDecoder().decode(chunkData.subarray(nullIndex + 1));
          return JSON.parse(text);
        }
      }

      if (type === "IEND") break;

      // Move to next chunk: length(4) + type(4) + data(length) + CRC(4)
      offset += 4 + 4 + length + 4;
    }

    return null;
  } catch (error) {
    console.error("[extractPngMetadata] Error:", error);
    return null;
  }
}

// Load image from URL and return as data URL
export async function loadImageAsDataUrl(url: string): Promise<string | null> {
  try {
    // Try direct fetch first
    const response = await fetch(url, { mode: "cors" });
    const blob = await response.blob();
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.onloadend = () => resolve(reader.result as string);
      reader.onerror = () => resolve(null);
      reader.readAsDataURL(blob);
    });
  } catch {
    // If CORS fails, try through a proxy or just return null
    console.warn("[loadImageAsDataUrl] Failed to load:", url);
    return null;
  }
}
src/hooks/use-grids.ts
"use client";

import { useState, useCallback, useEffect } from "react";
import type {
  Grid,
  GridWithStats,
  GridCell,
  GridVisibility,
} from "@/lib/net-protocol";

interface UseGridsOptions {
  creator?: string;
  visibility?: GridVisibility | "all";
  autoFetch?: boolean;
}

interface CreateGridParams {
  name: string;
  subtitle?: string;
  description?: string;
  size: number;
  visibility?: GridVisibility;
  creator: string;
  creatorFid?: number;
  txHash?: string;
}

interface AddCellParams {
  gridId: string;
  row: number;
  col: number;
  cdnUrl: string;
  contentType?: string;
  title?: string;
  creator: string;
}

interface RemoveCellParams {
  gridId: string;
  row: number;
  col: number;
  creator: string;
}

interface UpdateGridParams {
  gridId: string;
  creator: string;
  name?: string;
  visibility?: GridVisibility;
}

interface ResizeGridParams {
  gridId: string;
  creator: string;
  newSize: number;
  txHash?: string;
}

export function useGrids(options: UseGridsOptions = {}) {
  const { creator, visibility, autoFetch = true } = options;

  const [grids, setGrids] = useState<GridWithStats[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Fetch grids
  const fetchGrids = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    try {
      const params = new URLSearchParams();
      if (creator) params.set("creator", creator);
      if (visibility && visibility !== "all") params.set("visibility", visibility);

      const response = await fetch(`/api/grids?${params.toString()}`);
      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || "Failed to fetch grids");
      }

      setGrids(data.grids || []);
    } catch (err) {
      const message = err instanceof Error ? err.message : "Unknown error";
      setError(message);
      console.error("[useGrids] Fetch error:", err);
    } finally {
      setIsLoading(false);
    }
  }, [creator, visibility]);

  // Auto-fetch on mount
  useEffect(() => {
    if (autoFetch) {
      fetchGrids();
    }
  }, [autoFetch, fetchGrids]);

  // Create a new grid
  const createGrid = useCallback(async (params: CreateGridParams): Promise<Grid | null> => {
    try {
      const response = await fetch("/api/grids", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(params),
      });

      const data = await response.json();

      if (!data.success) {
        if (data.requiresPayment) {
          throw new Error(`Payment required: $${data.cost} for 6×6+ grids`);
        }
        throw new Error(data.error || "Failed to create grid");
      }

      // Refresh grids list
      await fetchGrids();

      return data.grid;
    } catch (err) {
      const message = err instanceof Error ? err.message : "Unknown error";
      setError(message);
      console.error("[useGrids] Create error:", err);
      return null;
    }
  }, [fetchGrids]);

  // Add a cell to a grid
  const addCell = useCallback(async (params: AddCellParams): Promise<GridCell | null> => {
    try {
      const response = await fetch("/api/grids", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          gridId: params.gridId,
          action: "add-cell",
          creator: params.creator,
          row: params.row,
          col: params.col,
          cdnUrl: params.cdnUrl,
          contentType: params.contentType,
          title: params.title,
        }),
      });

      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || "Failed to add cell");
      }

      return data.cell;
    } catch (err) {
      const message = err instanceof Error ? err.message : "Unknown error";
      setError(message);
      console.error("[useGrids] Add cell error:", err);
      return null;
    }
  }, []);

  // Remove a cell from a grid
  const removeCell = useCallback(async (params: RemoveCellParams): Promise<boolean> => {
    try {
      const response = await fetch("/api/grids", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          gridId: params.gridId,
          action: "remove-cell",
          creator: params.creator,
          row: params.row,
          col: params.col,
        }),
      });

      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || "Failed to remove cell");
      }

      return true;
    } catch (err) {
      const message = err instanceof Error ? err.message : "Unknown error";
      setError(message);
      console.error("[useGrids] Remove cell error:", err);
      return false;
    }
  }, []);

  // Update grid metadata
  const updateGrid = useCallback(async (params: UpdateGridParams): Promise<Grid | null> => {
    try {
      const response = await fetch("/api/grids", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          gridId: params.gridId,
          action: "update-metadata",
          creator: params.creator,
          name: params.name,
          visibility: params.visibility,
        }),
      });

      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || "Failed to update grid");
      }

      // Refresh grids list
      await fetchGrids();

      return data.grid;
    } catch (err) {
      const message = err instanceof Error ? err.message : "Unknown error";
      setError(message);
      console.error("[useGrids] Update error:", err);
      return null;
    }
  }, [fetchGrids]);

  // Resize a grid
  const resizeGrid = useCallback(async (params: ResizeGridParams): Promise<Grid | null> => {
    try {
      const response = await fetch("/api/grids", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          gridId: params.gridId,
          action: "resize",
          creator: params.creator,
          newSize: params.newSize,
          txHash: params.txHash,
        }),
      });

      const data = await response.json();

      if (!data.success) {
        if (data.requiresPayment) {
          throw new Error(`Payment required: $${data.cost} for 6×6+ grids`);
        }
        throw new Error(data.error || "Failed to resize grid");
      }

      // Refresh grids list
      await fetchGrids();

      return data.grid;
    } catch (err) {
      const message = err instanceof Error ? err.message : "Unknown error";
      setError(message);
      console.error("[useGrids] Resize error:", err);
      return null;
    }
  }, [fetchGrids]);

  // Delete a grid
  const deleteGrid = useCallback(async (gridId: string, creator: string): Promise<boolean> => {
    try {
      const params = new URLSearchParams();
      params.set("id", gridId);
      params.set("creator", creator);

      const response = await fetch(`/api/grids?${params.toString()}`, {
        method: "DELETE",
      });

      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || "Failed to delete grid");
      }

      // Refresh grids list
      await fetchGrids();

      return true;
    } catch (err) {
      const message = err instanceof Error ? err.message : "Unknown error";
      setError(message);
      console.error("[useGrids] Delete error:", err);
      return false;
    }
  }, [fetchGrids]);

  return {
    grids,
    isLoading,
    error,
    refresh: fetchGrids,
    createGrid,
    addCell,
    removeCell,
    updateGrid,
    resizeGrid,
    deleteGrid,
  };
}

// Hook to fetch a single grid with its cells
export function useGrid(gridId: string | null, viewer?: string) {
  const [grid, setGrid] = useState<GridWithStats | null>(null);
  const [cells, setCells] = useState<GridCell[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchGrid = useCallback(async () => {
    if (!gridId) return;

    setIsLoading(true);
    setError(null);

    try {
      const params = new URLSearchParams();
      params.set("id", gridId);
      if (viewer) params.set("viewer", viewer);

      const response = await fetch(`/api/grids?${params.toString()}`);
      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || "Failed to fetch grid");
      }

      setGrid(data.grid);
      setCells(data.cells || []);
    } catch (err) {
      const message = err instanceof Error ? err.message : "Unknown error";
      setError(message);
      console.error("[useGrid] Fetch error:", err);
    } finally {
      setIsLoading(false);
    }
  }, [gridId, viewer]);

  useEffect(() => {
    fetchGrid();
  }, [fetchGrid]);

  return {
    grid,
    cells,
    isLoading,
    error,
    refresh: fetchGrid,
  };
}

// Hook to fetch public grid feed
export function useGridFeed(sortBy: "upvotes" | "recent" = "upvotes") {
  const [grids, setGrids] = useState<GridWithStats[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const [total, setTotal] = useState(0);

  const fetchPage = useCallback(async (pageNum: number, reset = false) => {
    setIsLoading(true);
    setError(null);

    try {
      const params = new URLSearchParams();
      params.set("sortBy", sortBy);
      params.set("page", pageNum.toString());
      params.set("pageSize", "20");

      const response = await fetch(`/api/grids?${params.toString()}`);
      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || "Failed to fetch grids");
      }

      if (reset) {
        setGrids(data.grids || []);
      } else {
        setGrids((prev) => [...prev, ...(data.grids || [])]);
      }

      setTotal(data.total || 0);
      setHasMore(pageNum < (data.totalPages || 1));
      setPage(pageNum);
    } catch (err) {
      const message = err instanceof Error ? err.message : "Unknown error";
      setError(message);
      console.error("[useGridFeed] Fetch error:", err);
    } finally {
      setIsLoading(false);
    }
  }, [sortBy]);

  // Initial fetch
  useEffect(() => {
    fetchPage(1, true);
  }, [fetchPage]);

  const loadMore = useCallback(() => {
    if (!isLoading && hasMore) {
      fetchPage(page + 1);
    }
  }, [isLoading, hasMore, page, fetchPage]);

  const refresh = useCallback(() => {
    fetchPage(1, true);
  }, [fetchPage]);

  return {
    grids,
    isLoading,
    error,
    hasMore,
    total,
    loadMore,
    refresh,
  };
}
src/hooks/use-leaderboard.ts
"use client";

import { useState, useEffect, useCallback } from "react";
import {
  fetchLeaderboardIndex,
  type LeaderboardIndex,
  type UserStats,
  type BookStats,
  type CategoryStats,
} from "@/lib/net-protocol";

export type ResolvedUser = { username: string; pfpUrl: string; fid?: number };

export function useLeaderboard() {
  const [leaderboard, setLeaderboard] = useState<LeaderboardIndex | null>(null);
  const [resolvedUsers, setResolvedUsers] = useState<Map<string, ResolvedUser>>(new Map());
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Resolve user addresses to usernames/pfps/fids
  const resolveUserAddresses = useCallback(async (addresses: string[]) => {
    const unresolvedAddresses = addresses.filter(addr => !resolvedUsers.has(addr.toLowerCase()));
    if (unresolvedAddresses.length === 0) return;

    try {
      const response = await fetch("/api/resolve-user", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ addresses: unresolvedAddresses }),
      });

      if (response.ok) {
        const data = await response.json();
        setResolvedUsers(prev => {
          const next = new Map(prev);
          for (const [addr, user] of Object.entries(data.users)) {
            const userData = user as { username: string; pfpUrl: string; fid?: number };
            next.set(addr.toLowerCase(), {
              username: userData.username,
              pfpUrl: userData.pfpUrl,
              fid: userData.fid,
            });
          }
          return next;
        });
      }
    } catch (err) {
      console.error("Failed to resolve user addresses:", err);
    }
  }, [resolvedUsers]);

  // Fetch leaderboard data
  const refresh = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    try {
      const data = await fetchLeaderboardIndex();
      setLeaderboard(data);

      // Resolve user addresses from leaderboard
      if (data?.users) {
        const addresses = data.users.map(u => u.address);
        resolveUserAddresses(addresses);
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to load leaderboard");
    } finally {
      setIsLoading(false);
    }
  }, [resolveUserAddresses]);

  // Load on mount
  useEffect(() => {
    refresh();
  }, [refresh]);

  // Get top uploaders (by number of uploads)
  const getTopUploaders = useCallback(
    (limit: number = 10): UserStats[] => {
      if (!leaderboard) return [];
      return leaderboard.users
        .sort((a, b) => b.totalUploads - a.totalUploads)
        .slice(0, limit);
    },
    [leaderboard]
  );

  // Get top contributors by bytes uploaded
  const getTopByBytes = useCallback(
    (limit: number = 10): UserStats[] => {
      if (!leaderboard) return [];
      return leaderboard.users
        .sort((a, b) => b.totalBytesUploaded - a.totalBytesUploaded)
        .slice(0, limit);
    },
    [leaderboard]
  );

  // Get most popular books
  const getPopularBooks = useCallback(
    (limit: number = 10): BookStats[] => {
      if (!leaderboard) return [];
      return leaderboard.topBooks
        .sort((a, b) => b.downloads - a.downloads)
        .slice(0, limit);
    },
    [leaderboard]
  );

  // Get newest books
  const getNewestBooks = useCallback(
    (limit: number = 10): BookStats[] => {
      if (!leaderboard) return [];
      return leaderboard.topBooks
        .sort((a, b) => b.uploadedAt - a.uploadedAt)
        .slice(0, limit);
    },
    [leaderboard]
  );

  // Get category stats sorted by popularity
  const getCategoryStats = useCallback((): CategoryStats[] => {
    if (!leaderboard) return [];
    return leaderboard.categories.sort((a, b) => b.totalBooks - a.totalBooks);
  }, [leaderboard]);

  // Get user rank
  const getUserRank = useCallback(
    (address: string): { rank: number; stats: UserStats | null } => {
      if (!leaderboard) return { rank: 0, stats: null };

      const sortedUsers = [...leaderboard.users].sort(
        (a, b) => b.totalUploads - a.totalUploads
      );
      const index = sortedUsers.findIndex(
        (u) => u.address && u.address.toLowerCase() === address.toLowerCase()
      );

      if (index === -1) {
        return { rank: 0, stats: null };
      }

      return { rank: index + 1, stats: sortedUsers[index] };
    },
    [leaderboard]
  );

  // Get global stats
  const globalStats = leaderboard?.globalStats ?? {
    totalBooks: 0,
    totalBytes: 0,
    totalDownloads: 0,
    totalUsers: 0,
    lastUpdated: Date.now(),
  };

  return {
    leaderboard,
    resolvedUsers,
    isLoading,
    error,
    refresh,
    globalStats,
    getTopUploaders,
    getTopByBytes,
    getPopularBooks,
    getNewestBooks,
    getCategoryStats,
    getUserRank,
  };
}
src/hooks/use-member-upvotes.ts
"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { useWriteContract, useWaitForTransactionReceipt, useAccount } from "wagmi";
import { keccak256, encodePacked, parseEther } from "viem";
import { base } from "viem/chains";

// Contract addresses on Base (same as content upvotes)
const UPVOTE_STORAGE_APP = "0x000000060CEB69D023227DF64CfB75eC37c75B62" as const;
const PURE_ALPHA_STRATEGY = "0x00000001b1bcdeddeafd5296aaf4f3f3e21ae876" as const;
const SCORE_CONTRACT = "0x0000000FA09B022E5616E5a173b4b67FA2FBcF28" as const;

// Cost per upvote in ETH
export const MEMBER_UPVOTE_COST_ETH = 0.000025;
export const MEMBER_UPVOTE_COST_WEI = parseEther(MEMBER_UPVOTE_COST_ETH.toString());

// ABI for UpvoteStorageApp
const UPVOTE_STORAGE_APP_ABI = [
  {
    name: "upvote",
    type: "function",
    stateMutability: "payable",
    inputs: [
      { name: "strategy", type: "address" },
      { name: "storageOperatorAddress", type: "address" },
      { name: "storageKey", type: "bytes32" },
      { name: "scoreDelta", type: "uint256" },
      { name: "scoreUnstoredContext", type: "bytes" },
    ],
    outputs: [],
  },
] as const;

// ABI for Score contract (querying) - reserved for future use
const _SCORE_ABI = [
  {
    name: "getAppStrategyKeyScores",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "app", type: "address" },
      { name: "strategy", type: "address" },
      { name: "scoreKeys", type: "bytes32[]" },
    ],
    outputs: [{ name: "counts", type: "int256[]" }],
  },
] as const;

// Generate a unique storageKey for a member (based on their address)
// This creates a unique identifier for each member that can be upvoted
export function generateMemberStorageKey(memberAddress: string): `0x${string}` {
  // Use a prefix to distinguish member upvotes from content upvotes
  const prefix = "NET_LIBRARY_MEMBER_UPVOTE_V1";
  return keccak256(
    encodePacked(
      ["string", "address"],
      [prefix, memberAddress.toLowerCase() as `0x${string}`]
    )
  );
}

// Generate scoreKey for member upvotes (for querying the Score contract)
// The contract hashes storageKey + storageOperatorAddress together, just like content upvotes.
// At write time, memberAddress is passed as storageOperatorAddress, so the final
// on-chain score key = keccak256(abi.encodePacked(storageKey, memberAddress)).
export function generateMemberScoreKey(memberAddress: string): `0x${string}` {
  const storageKey = generateMemberStorageKey(memberAddress);
  return keccak256(
    encodePacked(
      ["bytes32", "address"],
      [storageKey, memberAddress.toLowerCase() as `0x${string}`]
    )
  );
}

// Pending upvote info for tracking
interface PendingMemberUpvote {
  memberAddress: string;
  memberId: number;
  amount: number;
}

// Hook for upvoting members
export function useMemberUpvote() {
  const { address, isConnected } = useAccount();
  const [isUpvoting, setIsUpvoting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Track pending upvote info
  const pendingUpvoteRef = useRef<PendingMemberUpvote | null>(null);

  const { writeContract, data: txHash, isPending, reset } = useWriteContract();

  const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({
    hash: txHash,
  });

  // When transaction confirms, reset state
  useEffect(() => {
    if (isConfirmed && txHash && pendingUpvoteRef.current) {
      console.log("[useMemberUpvote] Member upvote confirmed:", txHash, pendingUpvoteRef.current);
      pendingUpvoteRef.current = null;
      setIsUpvoting(false);
      reset();
    }
  }, [isConfirmed, txHash, reset]);

  const upvoteMember = useCallback(
    async (memberAddress: string, memberId: number, count: number = 1) => {
      if (!isConnected || !address) {
        setError("Wallet not connected");
        return false;
      }

      if (count < 1) {
        setError("Must upvote at least 1");
        return false;
      }

      // Can't upvote yourself
      if (memberAddress.toLowerCase() === address.toLowerCase()) {
        setError("Can't upvote yourself");
        return false;
      }

      setIsUpvoting(true);
      setError(null);

      try {
        const totalCost = MEMBER_UPVOTE_COST_WEI * BigInt(count);
        const storageKey = generateMemberStorageKey(memberAddress);

        // Store pending upvote info
        pendingUpvoteRef.current = {
          memberAddress,
          memberId,
          amount: count,
        };

        writeContract({
          address: UPVOTE_STORAGE_APP,
          abi: UPVOTE_STORAGE_APP_ABI,
          functionName: "upvote",
          args: [
            PURE_ALPHA_STRATEGY,
            memberAddress as `0x${string}`, // The member's address is the "operator"
            storageKey,
            BigInt(count),
            "0x" as `0x${string}`, // empty scoreUnstoredContext
          ],
          value: totalCost,
          chainId: base.id,
        });

        return true;
      } catch (err) {
        console.error("[useMemberUpvote] Error:", err);
        const errorMsg = err instanceof Error ? err.message : "Failed to upvote member";
        setError(errorMsg);
        setIsUpvoting(false);
        pendingUpvoteRef.current = null;
        return false;
      }
    },
    [isConnected, address, writeContract]
  );

  return {
    upvoteMember,
    isUpvoting: isUpvoting || isPending || isConfirming,
    isConfirmed,
    error,
    txHash,
    reset: () => {
      reset();
      setError(null);
      setIsUpvoting(false);
      pendingUpvoteRef.current = null;
    },
  };
}

// Hook for fetching member upvote counts
export function useMemberUpvoteCounts(
  members: Array<{ memberId: number; address: string }>
) {
  const [counts, setCounts] = useState<Map<string, number>>(new Map());
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Track if we've ever fetched with items
  const hasFetchedWithItemsRef = useRef(false);

  // Serialize members for stable dependency comparison
  const membersKey = JSON.stringify(
    members.map((m) => `${m.memberId}:${m.address}`).sort()
  );

  const fetchCounts = useCallback(async () => {
    if (members.length === 0) {
      if (hasFetchedWithItemsRef.current) {
        setCounts(new Map());
        setIsLoading(false);
      }
      return;
    }

    hasFetchedWithItemsRef.current = true;
    setIsLoading(true);
    setError(null);

    try {
      // Generate scoreKeys for all members
      const scoreKeys = members
        .filter((m) => m.address) // Only members with addresses
        .map((m) => generateMemberScoreKey(m.address));

      if (scoreKeys.length === 0) {
        setCounts(new Map());
        setIsLoading(false);
        return;
      }

      // Call the upvotes API to get counts
      const response = await fetch("/api/upvotes", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          scoreKeys,
          contentKeys: members.filter((m) => m.address).map((m) => m.address),
        }),
      });

      if (!response.ok) {
        throw new Error("Failed to fetch member upvote counts");
      }

      const data = await response.json();
      const newCounts = new Map<string, number>();

      if (data.counts) {
        const membersWithAddresses = members.filter((m) => m.address);
        membersWithAddresses.forEach((member, index) => {
          // Key by address (lowercase for consistency)
          newCounts.set(member.address.toLowerCase(), data.counts[index] || 0);
        });
      }

      setCounts(newCounts);
    } catch (err) {
      console.error("[useMemberUpvoteCounts] Error:", err);
      setError(err instanceof Error ? err.message : "Failed to fetch counts");
    } finally {
      setIsLoading(false);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [membersKey]);

  useEffect(() => {
    fetchCounts();
  }, [fetchCounts]);

  const getCount = useCallback(
    (memberAddress: string) => counts.get(memberAddress.toLowerCase()) || 0,
    [counts]
  );

  return {
    counts,
    getCount,
    isLoading,
    error,
    refresh: fetchCounts,
  };
}

// Export contract addresses for reference
export const MEMBER_UPVOTE_CONTRACTS = {
  UPVOTE_STORAGE_APP,
  PURE_ALPHA_STRATEGY,
  SCORE_CONTRACT,
};
src/hooks/use-membership-status.ts
"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { useAccount } from "wagmi";
import { useFarcasterUser } from "@/neynar-farcaster-sdk/mini";
import { useUserProfile } from "@/hooks/use-user-profile";
import { useAppMode } from "@/lib/app-mode";
import type { SignupPlatform } from "@/lib/net-protocol";

// Full membership info including platform (from API)
export interface MembershipInfo {
  memberId: number;
  ensSubname: string;
  signupPlatform: SignupPlatform | "unknown";
  joinedAt: number;
  fid?: number;
  username?: string;
  address: string;
  matchType: "primary" | "fid" | "linked" | "verified";
  // Web platform fields
  wid?: string;           // Web ID - 6-char alphanumeric (e.g., "A7K2M9")
  customUsername?: string; // User-editable username (web only)
  customPfpUrl?: string;   // User-uploaded PFP URL (web only)
  linkedFid?: number;      // FID linked after signup (for web users who link FC)
  // Agent identity
  isAgent?: boolean;       // True if this member is a registered AI agent
  agentId?: string;        // The agent's registered ID (e.g., "cheryl")
}

interface MemberInfo {
  isMember: boolean;
  memberId: number | null;
  ensSubname: string | null;
  username: string | null;
  fid: number | null;
  // Indicates how the membership was found
  matchType?: "primary" | "fid" | "linked" | "verified" | null;
  registeredAddress?: string;
  linkedAddresses?: string[];
  // All memberships for users with multiple (each one is real - they paid for each)
  allMemberships?: MembershipInfo[] | null;
  // Web platform fields
  wid?: string | null;           // Web ID for web signups
  customUsername?: string | null; // Custom username (web only)
  customPfpUrl?: string | null;   // Custom profile picture URL (web only)
  signupPlatform?: SignupPlatform | null; // Platform user signed up on
  // Stack Pass
  hasStackPass?: boolean;        // True if user has Unlimited Stack Pass
  stackPassPurchasedAt?: number; // Timestamp when pass was purchased
  // Agent identity
  isAgent?: boolean;             // True if this member is a registered AI agent
  agentId?: string | null;       // The agent's registered ID (e.g., "cheryl")
}

export function useMembershipStatus() {
  const { address, isConnected } = useAccount();
  const { data: farcasterUser, isLoading: isFarcasterLoading } = useFarcasterUser();
  const { profile: userProfile, isLoading: isProfileLoading } = useUserProfile();
  const appMode = useAppMode();

  // Get FID from either Farcaster SDK (on Farcaster) or user profile (on Base App via Neynar API)
  const effectiveFid = farcasterUser?.fid || userProfile?.fid;

  const [memberInfo, setMemberInfo] = useState<MemberInfo>({
    isMember: false,
    memberId: null,
    ensSubname: null,
    username: null,
    fid: null,
    allMemberships: null,
    wid: null,
    customUsername: null,
    customPfpUrl: null,
    signupPlatform: null,
    hasStackPass: false,
    stackPassPurchasedAt: undefined,
    isAgent: false,
    agentId: null,
  });
  const [isLoading, setIsLoading] = useState(true);
  const [verifiedAddresses, setVerifiedAddresses] = useState<string[] | null>(null);
  const fetchedFidRef = useRef<number | null>(null);

  // Fetch verified addresses from Neynar when user has a FID
  // This enables cross-platform membership detection on BOTH Farcaster and Base App
  // On Farcaster: FID comes from SDK directly
  // On Base App: FID is resolved via Neynar API in useUserProfile
  useEffect(() => {
    const fid = effectiveFid;
    if (!fid || fetchedFidRef.current === fid) return;
    // Removed the Farcaster-only check - we need verified addresses on both platforms

    fetchedFidRef.current = fid;

    fetch("/api/resolve-user", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ fids: [fid] }),
    })
      .then(res => res.json())
      .then(data => {
        const user = data.users?.[0];
        if (user?.verified_addresses?.eth_addresses) {
          console.log("[useMembershipStatus] Got verified addresses:", user.verified_addresses.eth_addresses.length, "for FID:", fid, "appMode:", appMode);
          setVerifiedAddresses(user.verified_addresses.eth_addresses);
        }
      })
      .catch(err => {
        console.error("[useMembershipStatus] Failed to fetch verified addresses:", err);
      });
  }, [effectiveFid, appMode]);

  const checkMembership = useCallback(async (fid?: number, verifiedAddrs?: string[] | null) => {
    console.log("[useMembershipStatus] checkMembership called:", {
      address: address ? address.slice(0, 10) + "..." + address.slice(-4) : "none",
      isConnected,
      fid: fid || "none"
    });

    if (!address || !isConnected) {
      console.log("[useMembershipStatus] No address or not connected, returning non-member");
      setMemberInfo({
        isMember: false,
        memberId: null,
        ensSubname: null,
        username: null,
        fid: null,
        allMemberships: null,
        wid: null,
        customUsername: null,
        customPfpUrl: null,
        signupPlatform: null,
        hasStackPass: false,
        stackPassPurchasedAt: undefined,
        isAgent: false,
        agentId: null,
      });
      setIsLoading(false);
      return;
    }

    setIsLoading(true);

    try {
      // Check membership - pass both address and FID to check all methods
      // (primary address, linked addresses, FID match, and verified addresses)
      const fidParam = fid ? `&fid=${fid}` : "";
      const verifiedParam = verifiedAddrs && verifiedAddrs.length > 0 ? `&verifiedAddresses=${verifiedAddrs.join(",")}` : "";
      const url = `/api/membership?address=${address}${fidParam}${verifiedParam}`;
      console.log("[useMembershipStatus] Fetching:", url);
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error("Failed to check membership");
      }

      const data = await response.json();
      // matchType is now in allMemberships[0].matchType, not top-level
      const firstMembership = data.allMemberships?.[0];
      console.log("[useMembershipStatus] API response:", {
        isMember: data.isMember,
        memberId: data.member?.memberId,
        matchType: firstMembership?.matchType,
        allMembershipsCount: data.allMemberships?.length || 0,
        totalMembers: data.totalMembers
      });

      if (data.isMember && data.member) {
        setMemberInfo({
          isMember: true,
          memberId: data.member.memberId,
          ensSubname: data.member.ensSubname,
          username: data.member.username,
          fid: data.member.fid || firstMembership?.fid || null,
          matchType: firstMembership?.matchType || null,
          registeredAddress: data.member.address,
          linkedAddresses: data.member.linkedAddresses,
          allMemberships: data.allMemberships || null,
          // Web platform fields
          wid: data.member.wid || null,
          customUsername: data.member.customUsername || null,
          customPfpUrl: data.member.customPfpUrl || null,
          signupPlatform: data.member.signupPlatform || null,
          // Stack Pass
          hasStackPass: data.member.hasStackPass || false,
          stackPassPurchasedAt: data.member.stackPassPurchasedAt,
          // Agent identity
          isAgent: data.member.isAgent || false,
          agentId: data.member.agentId || null,
        });
        return;
      }

      // Not a member by any method
      console.log("[useMembershipStatus] Not a member by any method");
      setMemberInfo({
        isMember: false,
        memberId: null,
        ensSubname: null,
        username: null,
        fid: null,
        allMemberships: null,
        wid: null,
        customUsername: null,
        customPfpUrl: null,
        signupPlatform: null,
        hasStackPass: false,
        stackPassPurchasedAt: undefined,
        isAgent: false,
        agentId: null,
      });
    } catch (err) {
      console.error("[useMembershipStatus] Error checking membership:", err);
      setMemberInfo({
        isMember: false,
        memberId: null,
        ensSubname: null,
        username: null,
        fid: null,
        allMemberships: null,
        wid: null,
        customUsername: null,
        customPfpUrl: null,
        signupPlatform: null,
        hasStackPass: false,
        stackPassPurchasedAt: undefined,
        isAgent: false,
        agentId: null,
      });
    } finally {
      setIsLoading(false);
    }
  }, [address, isConnected]);

  // Wait for user data to load before checking membership
  // This ensures we have the FID for cross-platform account linking
  // On Farcaster: FID comes from SDK, verified addresses come from Neynar
  // On Base App: FID comes from Neynar API via useUserProfile
  useEffect(() => {
    // If either is still loading, wait
    if (isFarcasterLoading || isProfileLoading) {
      setIsLoading(true);
      return;
    }

    // Once done loading, check membership with whatever FID and verified addresses we have
    checkMembership(effectiveFid, verifiedAddresses);
  }, [checkMembership, isFarcasterLoading, isProfileLoading, effectiveFid, verifiedAddresses]);

  return {
    ...memberInfo,
    isLoading: isLoading || isFarcasterLoading || isProfileLoading,
    refresh: () => checkMembership(effectiveFid, verifiedAddresses),
    refreshMembership: () => checkMembership(effectiveFid, verifiedAddresses),
  };
}
src/hooks/use-membership.ts
"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import type { MemberEntry, SignupPlatform } from "@/lib/net-protocol";
import { useAppMode } from "@/lib/app-mode";
import { trackMembership } from "@/lib/diagnostics";

// Full membership info including platform
export interface MembershipInfo {
  memberId: number;
  ensSubname: string;
  signupPlatform: SignupPlatform | "unknown";
  joinedAt: number;
  fid?: number;
  username?: string;
  address: string;
  matchType: "primary" | "fid" | "linked" | "verified";
}

interface MembershipState {
  isLoading: boolean;
  isMember: boolean;
  member: MemberEntry | null;
  allMemberships: MembershipInfo[] | null; // All memberships with full data
  totalMembers: number;
  error: string | null;
  queryAddress: string | null;
  queryFid: number | null;
}

export function useMembership(address?: string, fid?: number) {
  const appMode = useAppMode();
  const [state, setState] = useState<MembershipState>({
    isLoading: true,
    isMember: false,
    member: null,
    allMemberships: null,
    totalMembers: 0,
    error: null,
    queryAddress: null,
    queryFid: null,
  });

  // Track verified addresses from Neynar (for Farcaster cross-platform detection)
  const [verifiedAddresses, setVerifiedAddresses] = useState<string[] | null>(null);
  const fetchedFidRef = useRef<number | null>(null);

  // Fetch verified addresses from Neynar when on Farcaster
  // This enables detecting Base App memberships that used a different wallet
  useEffect(() => {
    if (!fid || fetchedFidRef.current === fid) return;
    if (appMode !== "farcaster") return;

    fetchedFidRef.current = fid;

    fetch("/api/resolve-user", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ fids: [fid] }),
    })
      .then(res => res.json())
      .then(data => {
        const user = data.users?.[0];
        if (user?.verified_addresses?.eth_addresses) {
          console.log("[useMembership] Got verified addresses:", user.verified_addresses.eth_addresses.length);
          setVerifiedAddresses(user.verified_addresses.eth_addresses);
        }
      })
      .catch(err => {
        console.error("[useMembership] Failed to fetch verified addresses:", err);
      });
  }, [fid, appMode]);

  const checkMembership = useCallback(async (verifiedAddrs?: string[] | null) => {
    if (!address) {
      setState({
        isLoading: false,
        isMember: false,
        member: null,
        allMemberships: null,
        totalMembers: 0,
        error: null,
        queryAddress: null,
        queryFid: null,
      });
      return;
    }

    setState(prev => ({ ...prev, isLoading: true, error: null }));

    try {
      // Include FID if available for cross-platform identity lookup
      // This allows finding membership even when using a different (e.g., smart) wallet
      const fidParam = fid ? `&fid=${fid}` : "";
      // Include verified addresses for Farcaster users to find Base App memberships
      const verifiedParam = verifiedAddrs && verifiedAddrs.length > 0
        ? `&verifiedAddresses=${verifiedAddrs.join(",")}`
        : "";
      const response = await fetch(`/api/membership?address=${encodeURIComponent(address)}${fidParam}${verifiedParam}`);
      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to check membership");
      }

      // Track membership check
      trackMembership.checkStatus(address, data.isMember, data.member?.memberId);

      setState({
        isLoading: false,
        isMember: data.isMember,
        member: data.member,
        allMemberships: data.allMemberships || null,
        totalMembers: data.totalMembers,
        error: null,
        queryAddress: address,
        queryFid: fid || null,
      });
    } catch (err) {
      console.error("Membership check error:", err);
      setState(prev => ({
        ...prev,
        isLoading: false,
        error: err instanceof Error ? err.message : "Failed to check membership",
      }));
    }
  }, [address, fid]);

  // Check membership on mount and when address, fid, or verifiedAddresses changes
  useEffect(() => {
    checkMembership(verifiedAddresses);
  }, [checkMembership, verifiedAddresses]);

  return {
    ...state,
    refresh: () => checkMembership(verifiedAddresses),
  };
}
src/hooks/use-netlibrary-feed.ts
"use client";

import { useMemo, useCallback, useState, useEffect } from "react";
import { NetClient } from "@net-protocol/core";
import type { NetClient as NetClientType } from "@net-protocol/core";
import { useWriteContract } from "wagmi";
import { BASE_CHAIN_ID } from "@/lib/net-protocol";

// The main Net Library activity feed topic
export const NETLIBRARY_FEED_TOPIC = "netlibrary";

// Activity types that appear in the main feed
export type ActivityType = "upload" | "review" | "milestone";

// NetMessage type from Net Protocol
export interface NetMessage {
  app: `0x${string}`;
  sender: `0x${string}`;
  timestamp: bigint;
  data: `0x${string}`;
  text: string;
  topic: string;
}

// Metadata structure stored in the data field
interface ActivityMetadata {
  type: ActivityType;
  version: 1;
  // Book info
  contentKey?: string;
  bookTitle?: string;
  bookAuthor?: string;
  // User info
  username?: string;
  pfpUrl?: string;
  // Review specific
  rating?: number;
  // Deep link to the app
  appUrl: string;
}

// Parsed activity for UI
export interface NetLibraryActivity {
  id: string;
  type: ActivityType;
  sender: `0x${string}`;
  text: string;
  timestamp: number;
  // Parsed metadata
  contentKey?: string;
  bookTitle?: string;
  bookAuthor?: string;
  username?: string;
  pfpUrl?: string;
  rating?: number;
  appUrl: string;
}

// Parse hex data to string
function hexToString(hex: string): string {
  const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
  if (!cleanHex) return "";
  const bytes = new Uint8Array(cleanHex.length / 2);
  for (let i = 0; i < cleanHex.length; i += 2) {
    bytes[i / 2] = parseInt(cleanHex.slice(i, i + 2), 16);
  }
  return new TextDecoder().decode(bytes);
}

// Convert string to hex
function stringToHex(str: string): `0x${string}` {
  const bytes = new TextEncoder().encode(str);
  let hex = "0x";
  for (let i = 0; i < bytes.length; i++) {
    hex += bytes[i].toString(16).padStart(2, "0");
  }
  return hex as `0x${string}`;
}

// Parse a NetMessage into activity format
function parseActivity(msg: NetMessage): NetLibraryActivity | null {
  try {
    const dataStr = hexToString(msg.data);
    if (!dataStr) return null;

    const metadata: ActivityMetadata = JSON.parse(dataStr);
    if (metadata.version !== 1) return null;

    return {
      id: `${msg.sender}-${msg.timestamp.toString()}`,
      type: metadata.type,
      sender: msg.sender,
      text: msg.text,
      timestamp: Number(msg.timestamp) * 1000,
      contentKey: metadata.contentKey,
      bookTitle: metadata.bookTitle,
      bookAuthor: metadata.bookAuthor,
      username: metadata.username,
      pfpUrl: metadata.pfpUrl,
      rating: metadata.rating,
      appUrl: metadata.appUrl,
    };
  } catch {
    return null;
  }
}

/**
 * Hook for reading the main Net Library activity feed
 */
export function useNetLibraryFeed() {
  const [posts, setPosts] = useState<NetMessage[]>([]);
  const [totalCount, setTotalCount] = useState(0);
  const [isLoading, setIsLoading] = useState(true);

  const netClient = useMemo(() => {
    return new NetClient({ chainId: BASE_CHAIN_ID });
  }, []);

  // Fetch messages from Net Protocol
  useEffect(() => {
    let isMounted = true;

    async function fetchMessages() {
      setIsLoading(true);
      try {
        // Get total count for the topic
        const count = await netClient.getMessageCount({
          filter: {
            appAddress: "0x0000000000000000000000000000000000000000" as `0x${string}`,
            topic: NETLIBRARY_FEED_TOPIC,
          },
        });

        if (!isMounted) return;
        setTotalCount(count);

        // Fetch last 50 messages
        const maxMessages = 50;
        const startIndex = Math.max(0, count - maxMessages);
        const endIndex = count;

        if (startIndex < endIndex) {
          const messages = await netClient.getMessages({
            filter: {
              appAddress: "0x0000000000000000000000000000000000000000" as `0x${string}`,
              topic: NETLIBRARY_FEED_TOPIC,
            },
            startIndex: startIndex,
            endIndex: endIndex,
          });

          if (!isMounted) return;
          setPosts(messages as NetMessage[]);
        }
      } catch (error) {
        console.error("[useNetLibraryFeed] Fetch error:", error);
      } finally {
        if (isMounted) {
          setIsLoading(false);
        }
      }
    }

    fetchMessages();

    return () => {
      isMounted = false;
    };
  }, [netClient]);

  const activities: NetLibraryActivity[] = useMemo(() => {
    if (!posts || posts.length === 0) return [];

    return posts
      .map(parseActivity)
      .filter((a): a is NetLibraryActivity => a !== null)
      .sort((a, b) => b.timestamp - a.timestamp);
  }, [posts]);

  return {
    activities,
    totalCount,
    isLoading,
  };
}

/**
 * FeedClient for preparing transactions
 */
class FeedClient {
  private netClient: NetClientType;

  constructor(params: { chainId: number }) {
    this.netClient = new NetClient({ chainId: params.chainId });
  }

  preparePostToFeed(params: { topic: string; text: string; data: string }) {
    const dataHex = stringToHex(params.data);
    return this.netClient.prepareSendMessage({
      topic: params.topic,
      text: params.text,
      data: dataHex,
    });
  }
}

/**
 * Hook for posting activity to the main Net Library feed
 */
export function usePostToNetLibraryFeed() {
  const { writeContractAsync } = useWriteContract();

  const feedClient = useMemo(() => {
    return new FeedClient({ chainId: BASE_CHAIN_ID });
  }, []);

  // Post a book upload announcement
  const postUpload = useCallback(async (params: {
    contentKey: string;
    bookTitle: string;
    bookAuthor: string;
    username?: string;
    pfpUrl?: string;
    appBaseUrl: string;
  }): Promise<boolean> => {
    try {
      const metadata: ActivityMetadata = {
        type: "upload",
        version: 1,
        contentKey: params.contentKey,
        bookTitle: params.bookTitle,
        bookAuthor: params.bookAuthor,
        username: params.username,
        pfpUrl: params.pfpUrl,
        appUrl: `${params.appBaseUrl}/book/${params.contentKey}`,
      };

      const displayName = params.username ? `@${params.username}` : "Someone";
      const text = `${displayName} uploaded "${params.bookTitle}" by ${params.bookAuthor}`;

      const txConfig = feedClient.preparePostToFeed({
        topic: NETLIBRARY_FEED_TOPIC,
        text,
        data: JSON.stringify(metadata),
      });

      await writeContractAsync({
        address: txConfig.to,
        abi: txConfig.abi,
        functionName: txConfig.functionName,
        args: txConfig.args,
        value: txConfig.value,
      });

      return true;
    } catch (err) {
      console.error("[usePostToNetLibraryFeed] Upload post error:", err);
      return false;
    }
  }, [feedClient, writeContractAsync]);

  // Post a book review announcement
  const postReview = useCallback(async (params: {
    contentKey: string;
    bookTitle: string;
    rating: number;
    username?: string;
    pfpUrl?: string;
    appBaseUrl: string;
  }): Promise<boolean> => {
    try {
      const metadata: ActivityMetadata = {
        type: "review",
        version: 1,
        contentKey: params.contentKey,
        bookTitle: params.bookTitle,
        rating: params.rating,
        username: params.username,
        pfpUrl: params.pfpUrl,
        appUrl: `${params.appBaseUrl}/book/${params.contentKey}`,
      };

      const displayName = params.username ? `@${params.username}` : "Someone";
      const stars = "★".repeat(params.rating) + "☆".repeat(5 - params.rating);
      const text = `${displayName} rated "${params.bookTitle}" ${stars}`;

      const txConfig = feedClient.preparePostToFeed({
        topic: NETLIBRARY_FEED_TOPIC,
        text,
        data: JSON.stringify(metadata),
      });

      await writeContractAsync({
        address: txConfig.to,
        abi: txConfig.abi,
        functionName: txConfig.functionName,
        args: txConfig.args,
        value: txConfig.value,
      });

      return true;
    } catch (err) {
      console.error("[usePostToNetLibraryFeed] Review post error:", err);
      return false;
    }
  }, [feedClient, writeContractAsync]);

  // Post a milestone announcement
  const postMilestone = useCallback(async (params: {
    text: string;
    appBaseUrl: string;
  }): Promise<boolean> => {
    try {
      const metadata: ActivityMetadata = {
        type: "milestone",
        version: 1,
        appUrl: params.appBaseUrl,
      };

      const txConfig = feedClient.preparePostToFeed({
        topic: NETLIBRARY_FEED_TOPIC,
        text: params.text,
        data: JSON.stringify(metadata),
      });

      await writeContractAsync({
        address: txConfig.to,
        abi: txConfig.abi,
        functionName: txConfig.functionName,
        args: txConfig.args,
        value: txConfig.value,
      });

      return true;
    } catch (err) {
      console.error("[usePostToNetLibraryFeed] Milestone post error:", err);
      return false;
    }
  }, [feedClient, writeContractAsync]);

  return {
    postUpload,
    postReview,
    postMilestone,
  };
}
src/hooks/use-onchain-comments.ts
"use client";
// Re-export from use-comments.ts (canonical location)
// This file exists for semantic clarity - "onchain comments" is more descriptive
export { useOnchainComments, useComments, type OnchainComment } from "@/hooks/use-comments";
src/hooks/use-pdf-cover.ts
"use client";

import { useState, useCallback } from "react";

interface ExtractedCover {
  dataUrl: string;
  width: number;
  height: number;
}

/**
 * Hook for extracting cover images from PDFs
 * Uses PDF.js to render the first page as an image
 */
export function usePdfCover() {
  const [isExtracting, setIsExtracting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  /**
   * Extract first page of PDF as a cover image
   * @param source - File object or CDN URL
   * @param maxWidth - Maximum width for the cover (default: 400)
   * @returns Promise with data URL of the cover image
   */
  const extractCover = useCallback(async (
    source: File | string,
    maxWidth: number = 400
  ): Promise<ExtractedCover | null> => {
    setIsExtracting(true);
    setError(null);

    try {
      // Dynamically import PDF.js
      const pdfjsLib = await import("pdfjs-dist");

      // Try multiple CDN sources for the worker in case one is down/blocked
      const workerUrls = [
        `https://unpkg.com/pdfjs-dist@${pdfjsLib.version}/build/pdf.worker.min.mjs`,
        `https://cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjsLib.version}/build/pdf.worker.min.mjs`,
        `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.mjs`,
      ];

      let workerLoaded = false;
      for (const workerUrl of workerUrls) {
        try {
          const testResponse = await fetch(workerUrl, { method: "HEAD" });
          if (testResponse.ok) {
            pdfjsLib.GlobalWorkerOptions.workerSrc = workerUrl;
            workerLoaded = true;
            break;
          }
        } catch {
          // Try next URL
        }
      }

      if (!workerLoaded) {
        // Fallback: disable worker (slower but works)
        pdfjsLib.GlobalWorkerOptions.workerSrc = "";
      }

      // Load PDF from source
      let pdfData: ArrayBuffer;

      if (source instanceof File) {
        pdfData = await source.arrayBuffer();
      } else {
        // Fetch from URL
        const response = await fetch(source);
        if (!response.ok) {
          throw new Error(`Failed to fetch PDF: ${response.status}`);
        }
        pdfData = await response.arrayBuffer();
      }

      // Load PDF document
      const pdf = await pdfjsLib.getDocument({ data: pdfData }).promise;

      // Get first page
      const page = await pdf.getPage(1);

      // Calculate scale to fit maxWidth
      const viewport = page.getViewport({ scale: 1 });
      const scale = maxWidth / viewport.width;
      const scaledViewport = page.getViewport({ scale });

      // Create canvas
      const canvas = document.createElement("canvas");
      canvas.width = scaledViewport.width;
      canvas.height = scaledViewport.height;

      const context = canvas.getContext("2d");
      if (!context) {
        throw new Error("Failed to get canvas context");
      }

      // Render page
      await page.render({
        canvasContext: context,
        viewport: scaledViewport,
      }).promise;

      // Convert to data URL
      const dataUrl = canvas.toDataURL("image/jpeg", 0.85);

      setIsExtracting(false);
      return {
        dataUrl,
        width: scaledViewport.width,
        height: scaledViewport.height,
      };
    } catch (err) {
      console.error("[usePdfCover] Extraction error:", err);
      setError(err instanceof Error ? err.message : "Failed to extract cover");
      setIsExtracting(false);
      return null;
    }
  }, []);

  /**
   * Extract cover and upload to discovery entry
   * @param contentKey - Content key of the uploaded book
   * @param operator - Operator/uploader address
   * @param cdnUrl - URL to fetch PDF from
   */
  const extractAndUpdateCover = useCallback(async (
    contentKey: string,
    operator: string,
    cdnUrl: string
  ): Promise<string | null> => {
    try {
      const cover = await extractCover(cdnUrl);
      if (!cover) return null;

      // Upload cover to KV storage to get a hosted URL
      // Data URLs are too large to store in discovery entries
      let finalCoverUrl = cover.dataUrl;
      try {
        const uploadResponse = await fetch("/api/upload-cover", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ dataUrl: cover.dataUrl, contentKey }),
        });
        if (uploadResponse.ok) {
          const uploadResult = await uploadResponse.json();
          if (uploadResult.url) {
            finalCoverUrl = uploadResult.url;
            console.log("[usePdfCover] Cover uploaded to KV:", finalCoverUrl);
          }
        }
      } catch (uploadErr) {
        console.warn("[usePdfCover] Cover upload failed, using data URL:", uploadErr);
      }

      // Update discovery entry with cover
      const response = await fetch("/api/discovery", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          contentKey,
          operator,
          coverUrl: finalCoverUrl,
        }),
      });

      if (!response.ok) {
        throw new Error("Failed to update discovery entry");
      }

      return finalCoverUrl;
    } catch (err) {
      console.error("[usePdfCover] Update error:", err);
      setError(err instanceof Error ? err.message : "Failed to update cover");
      return null;
    }
  }, [extractCover]);

  return {
    extractCover,
    extractAndUpdateCover,
    isExtracting,
    error,
  };
}
src/hooks/use-platform-status.ts
"use client";

/**
 * Platform Status Hook
 *
 * Tracks cross-platform identity and linking status for Net Library members.
 * Handles:
 * - Current platform detection (Farcaster, Base App, or Web)
 * - Verification status on each platform
 * - Linked account detection
 * - Dismissed prompt tracking
 */

import { useState, useEffect, useCallback, useRef } from "react";
import { useAccount } from "wagmi";
import { useFarcasterUser } from "@/neynar-farcaster-sdk/mini";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { useUserProfile } from "@/hooks/use-user-profile";
import { useAppMode } from "@/lib/app-mode";

// ─── Server-side preference helpers ─────────────────────────────────────────
// Persist popup-dismiss state to KV so it survives across sessions/webviews
// where localStorage is ephemeral or blocked (Farcaster mini-apps, Base App).

async function fetchServerDismissed(fid?: number, address?: string): Promise<boolean> {
  if (!fid && !address) return false;
  try {
    const param = fid ? `fid=${fid}` : `address=${address}`;
    const res = await fetch(`/api/prefs?${param}&key=dismissed_membership`);
    if (!res.ok) return false;
    const data = await res.json();
    return data.value === "true";
  } catch {
    return false;
  }
}

async function persistServerDismiss(fid?: number, address?: string): Promise<void> {
  if (!fid && !address) return;
  try {
    await fetch("/api/prefs", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ fid, address, key: "dismissed_membership", value: "true" }),
    });
  } catch {
    // Fire-and-forget — localStorage fallback still runs
  }
}

// Local storage keys
const STORAGE_KEYS = {
  DISMISSED_WELCOME: "nl_dismissed_welcome",
  DISMISSED_LINK_PROMPT: "nl_dismissed_link_prompt",
  DISMISSED_MEMBERSHIP_PROMPT: "nl_dismissed_membership_prompt",
  SEEN_PLATFORMS: "nl_seen_platforms", // Track which platforms user has visited
} as const;

// Platform types - now includes "web" for direct browser access
export type Platform = "farcaster" | "base-app" | "web";

// Platform colors for UI
export const PLATFORM_COLORS = {
  farcaster: {
    primary: "#8A63D2",      // Purple
    bg: "bg-purple-500",
    text: "text-purple-400",
    border: "border-purple-500",
    ring: "ring-purple-500",
  },
  "base-app": {
    primary: "#0052FF",      // Blue
    bg: "bg-blue-500",
    text: "text-blue-400",
    border: "border-blue-500",
    ring: "ring-blue-500",
  },
  web: {
    primary: "#EAB308",      // Yellow
    bg: "bg-yellow-500",
    text: "text-yellow-400",
    border: "border-yellow-500",
    ring: "ring-yellow-500",
  },
} as const;

export interface PlatformStatus {
  // Current platform
  currentPlatform: Platform | null;

  // Verification status (is member and verified on this platform)
  isFarcasterVerified: boolean;
  isBaseAppVerified: boolean;
  isWebVerified: boolean;

  // Whether user has linked their accounts
  hasLinkedAccounts: boolean;

  // User preferences (what they've dismissed)
  hasSeenWelcome: boolean;
  hasDismissedLinkPrompt: boolean;
  hasDismissedMembershipPrompt: boolean;

  // First visit detection
  isFirstVisitOnPlatform: boolean;

  // Loading state
  isLoading: boolean;

  // Actions
  dismissWelcome: () => void;
  dismissLinkPrompt: () => void;
  dismissMembershipPrompt: () => void;
  markPlatformSeen: (platform: Platform) => void;
}

/**
 * Get stored value from localStorage with fallback
 */
function getStoredValue<T>(key: string, fallback: T): T {
  if (typeof window === "undefined") return fallback;
  try {
    const stored = localStorage.getItem(key);
    if (stored === null) return fallback;
    return JSON.parse(stored) as T;
  } catch {
    return fallback;
  }
}

/**
 * Store value in localStorage
 */
function setStoredValue<T>(key: string, value: T): void {
  if (typeof window === "undefined") return;
  try {
    localStorage.setItem(key, JSON.stringify(value));
  } catch {
    // Storage full or unavailable
  }
}

export function usePlatformStatus(): PlatformStatus {
  const appMode = useAppMode();
  const { address, isConnected } = useAccount();
  const { data: farcasterUser, isLoading: isFarcasterLoading } = useFarcasterUser();
  const { isMember, memberId, linkedAddresses, matchType, registeredAddress, fid: memberFid, isLoading: isMembershipLoading } = useMembershipStatus();

  // Get FID from Neynar lookup (for Base App users) - used to auto-verify Farcaster identity
  const { profile: userProfile } = useUserProfile();

  // Current platform detection
  const currentPlatform: Platform | null =
    appMode === "farcaster" ? "farcaster" :
    appMode === "base-app" ? "base-app" :
    appMode === "web" ? "web" :
    null;

  // State for preferences (loaded from localStorage)
  const [hasSeenWelcome, setHasSeenWelcome] = useState(() =>
    getStoredValue(STORAGE_KEYS.DISMISSED_WELCOME, false)
  );
  const [hasDismissedLinkPrompt, setHasDismissedLinkPrompt] = useState(() =>
    getStoredValue(STORAGE_KEYS.DISMISSED_LINK_PROMPT, false)
  );
  const [hasDismissedMembershipPrompt, setHasDismissedMembershipPrompt] = useState(() =>
    getStoredValue(STORAGE_KEYS.DISMISSED_MEMBERSHIP_PROMPT, false)
  );
  const [seenPlatforms, setSeenPlatforms] = useState<Platform[]>(() =>
    getStoredValue(STORAGE_KEYS.SEEN_PLATFORMS, [] as Platform[])
  );

  // Track previous verification state to avoid flashing X marks during refresh
  // Use refs to persist across re-renders without triggering new renders
  // Initialize from localStorage to prevent flashing on initial load
  // Also check for membership ID cached separately for more reliable detection
  // NOTE: localStorage may not be available in Base App webview - wrap in try/catch
  const hasCachedMemberId = (() => {
    if (typeof window === "undefined") return false;
    try {
      return !!localStorage.getItem("nl_member_id");
    } catch {
      return false;
    }
  })();
  const prevFcVerifiedRef = useRef<boolean>((() => {
    if (typeof window === "undefined") return false;
    try {
      return localStorage.getItem("nl_fc_verified") === "true" || hasCachedMemberId;
    } catch {
      return false;
    }
  })());
  const prevBaseVerifiedRef = useRef<boolean>((() => {
    if (typeof window === "undefined") return false;
    try {
      return localStorage.getItem("nl_base_verified") === "true" || hasCachedMemberId;
    } catch {
      return false;
    }
  })());
  const prevWebVerifiedRef = useRef<boolean>((() => {
    if (typeof window === "undefined") return false;
    try {
      return localStorage.getItem("nl_web_verified") === "true" || hasCachedMemberId;
    } catch {
      return false;
    }
  })());
  const hasEverLoadedRef = useRef<boolean>(false);

  // Derive verification status
  // Farcaster verified = is a member AND we can identify their Farcaster account
  // We trust Neynar's wallet→FID lookup (already cryptographically verified when user verified address on FC)
  const computedFcVerified = isMember && (
    !!memberFid ||           // Membership has FID linked in database
    matchType === "fid" ||   // Found membership via FID lookup
    !!farcasterUser?.fid ||  // Currently using Farcaster with valid user
    !!userProfile?.fid       // FID detected via Neynar lookup (Base App) - trusted, no SIWF needed
  );

  // Base App verified = is a member AND on Base App with a connected wallet
  // If we found their membership (by address, FID, linked address, or verified address), they're verified
  // The wallet↔membership link is established by:
  // - Direct address match (matchType = "primary")
  // - Linked address (matchType = "linked")
  // - FID lookup via Neynar (matchType = "fid") - wallet→FID link is already cryptographically verified
  // - Verified address (matchType = "verified") - address verified on Farcaster, used on different platform
  const computedBaseVerified = !!(isMember && isConnected && address && (
    matchType === "primary" ||
    matchType === "linked" ||
    matchType === "fid" ||
    matchType === "verified" ||
    // Fallback: check addresses directly
    (registeredAddress && address.toLowerCase() === registeredAddress.toLowerCase()) ||
    (linkedAddresses && linkedAddresses.some(
      (linked) => linked && linked.toLowerCase() === address.toLowerCase()
    ))
  ));

  // Web verified = is a member AND on Web with a connected wallet
  // Same logic as Base App verification - wallet connection proves identity
  const computedWebVerified = !!(isMember && isConnected && address && (
    matchType === "primary" ||
    matchType === "linked" ||
    matchType === "fid" ||
    matchType === "verified" ||
    // Fallback: check addresses directly
    (registeredAddress && address.toLowerCase() === registeredAddress.toLowerCase()) ||
    (linkedAddresses && linkedAddresses.some(
      (linked) => linked && linked.toLowerCase() === address.toLowerCase()
    ))
  ));

  // Debug logging for verification status
  useEffect(() => {
    console.log("[usePlatformStatus] Verification Debug:", {
      appMode,
      isMember,
      isLoading: isMembershipLoading,
      matchType,
      memberFid,
      farcasterUserFid: farcasterUser?.fid,
      userProfileFid: userProfile?.fid,
      isConnected,
      address: address?.slice(0, 10),
      registeredAddress: registeredAddress?.slice(0, 10),
      linkedAddressesCount: linkedAddresses?.length || 0,
      computedFcVerified,
      computedBaseVerified,
      computedWebVerified,
      cachedFcVerified: prevFcVerifiedRef.current,
      cachedBaseVerified: prevBaseVerifiedRef.current,
      cachedWebVerified: prevWebVerifiedRef.current,
    });
  }, [appMode, isMember, isMembershipLoading, matchType, memberFid, farcasterUser?.fid, userProfile?.fid, isConnected, address, registeredAddress, linkedAddresses, computedFcVerified, computedBaseVerified, computedWebVerified]);

  // Update refs when we get verified status (after loading completes)
  // Once verified, we keep showing verified during subsequent loads
  // Also persist to localStorage so it survives page refresh
  // IMPORTANT: Only clear cache when we're confident user is NOT verified
  // (i.e., membership fully loaded AND user is confirmed not a member)
  useEffect(() => {
    if (!isMembershipLoading) {
      hasEverLoadedRef.current = true;

      // Cache member ID for faster detection on subsequent loads
      if (isMember && memberId !== null) {
        try {
          localStorage.setItem("nl_member_id", String(memberId));
        } catch {
          // Ignore storage errors
        }
      } else if (!isMember) {
        try {
          localStorage.removeItem("nl_member_id");
        } catch {
          // Ignore storage errors
        }
      }

      // For FC verification: only clear if user is definitely not a member
      // Keep cached "true" if isMember is true (even if computedFcVerified is temporarily false due to timing)
      if (computedFcVerified) {
        prevFcVerifiedRef.current = true;
        try {
          localStorage.setItem("nl_fc_verified", "true");
        } catch {
          // Ignore storage errors
        }
      } else if (!isMember) {
        // Only clear if user is confirmed NOT a member
        prevFcVerifiedRef.current = false;
        try {
          localStorage.removeItem("nl_fc_verified");
        } catch {
          // Ignore storage errors
        }
      }
      // If isMember but !computedFcVerified, keep the cached value (timing issue)

      // For Base verification: same logic
      if (computedBaseVerified) {
        prevBaseVerifiedRef.current = true;
        try {
          localStorage.setItem("nl_base_verified", "true");
        } catch {
          // Ignore storage errors
        }
      } else if (!isMember) {
        // Only clear if user is confirmed NOT a member
        prevBaseVerifiedRef.current = false;
        try {
          localStorage.removeItem("nl_base_verified");
        } catch {
          // Ignore storage errors
        }
      }
      // If isMember but !computedBaseVerified, keep the cached value (timing issue)

      // For Web verification: same logic
      if (computedWebVerified) {
        prevWebVerifiedRef.current = true;
        try {
          localStorage.setItem("nl_web_verified", "true");
        } catch {
          // Ignore storage errors
        }
      } else if (!isMember) {
        // Only clear if user is confirmed NOT a member
        prevWebVerifiedRef.current = false;
        try {
          localStorage.removeItem("nl_web_verified");
        } catch {
          // Ignore storage errors
        }
      }
      // If isMember but !computedWebVerified, keep the cached value (timing issue)
    }
  }, [isMembershipLoading, isMember, memberId, computedFcVerified, computedBaseVerified, computedWebVerified]);

  // During loading OR when computed drops to false temporarily, preserve cached state
  // This prevents flashing X marks during pull-to-refresh, initial load, AND data refresh timing issues
  // Only show X if: not loading AND computed is false AND we've never been verified (cache is false)
  const isFarcasterVerified = isMembershipLoading
    ? prevFcVerifiedRef.current
    : (computedFcVerified || (prevFcVerifiedRef.current && isMember));
  const isBaseAppVerified = isMembershipLoading
    ? prevBaseVerifiedRef.current
    : (computedBaseVerified || (prevBaseVerifiedRef.current && isMember));
  const isWebVerified = isMembershipLoading
    ? prevWebVerifiedRef.current
    : (computedWebVerified || (prevWebVerifiedRef.current && isMember));

  // Check if accounts are linked
  // Linked = has both FID associated AND wallet addresses
  const hasLinkedAccounts = isMember && (
    (linkedAddresses && linkedAddresses.length > 0) || // Has linked addresses
    (matchType === "linked") // Found via linked address
  );

  // First visit detection for current platform
  const isFirstVisitOnPlatform = currentPlatform ? !seenPlatforms.includes(currentPlatform) : false;

  // Actions
  const dismissWelcome = useCallback(() => {
    setHasSeenWelcome(true);
    setStoredValue(STORAGE_KEYS.DISMISSED_WELCOME, true);
  }, []);

  const dismissLinkPrompt = useCallback(() => {
    setHasDismissedLinkPrompt(true);
    setStoredValue(STORAGE_KEYS.DISMISSED_LINK_PROMPT, true);
  }, []);

  const dismissMembershipPrompt = useCallback(() => {
    setHasDismissedMembershipPrompt(true);
    // Write to localStorage (may be ephemeral in mini-app webviews — that's OK)
    setStoredValue(STORAGE_KEYS.DISMISSED_MEMBERSHIP_PROMPT, true);
    // Also persist server-side so the dismissed state survives across sessions
    // and webview contexts where localStorage is blocked or cleared.
    persistServerDismiss(memberFid ?? undefined, address ?? undefined);
  }, [memberFid, address]);

  const markPlatformSeen = useCallback((platform: Platform) => {
    if (!seenPlatforms.includes(platform)) {
      const updated = [...seenPlatforms, platform];
      setSeenPlatforms(updated);
      setStoredValue(STORAGE_KEYS.SEEN_PLATFORMS, updated);
    }
  }, [seenPlatforms]);

  // Hydrate dismissed_membership from server once identity is resolved.
  // This is the fallback for webview contexts where localStorage is ephemeral:
  // if localStorage says "not dismissed" but the server says "dismissed", trust the server.
  const hasFetchedServerDismiss = useRef(false);
  // Track the identity string we last fetched for, so we re-fetch if the user
  // disconnects and reconnects with a different wallet or Farcaster account.
  const lastFetchedIdentity = useRef<string | null>(null);
  useEffect(() => {
    const currentIdentity = memberFid ? `fid:${memberFid}` : address ? `addr:${address}` : null;

    // Reset the fetch guard if identity changed (e.g. user switched wallets).
    if (currentIdentity !== lastFetchedIdentity.current) {
      hasFetchedServerDismiss.current = false;
      lastFetchedIdentity.current = currentIdentity;
    }

    if (hasFetchedServerDismiss.current) return;
    if (isMembershipLoading) return; // Wait until we have FID / address
    // Only relevant for non-members who might see the popup
    if (isMember) {
      // Member can't see the become-member popup anyway — no need to fetch
      hasFetchedServerDismiss.current = true;
      return;
    }
    if (!currentIdentity) return; // No identity yet

    hasFetchedServerDismiss.current = true;
    fetchServerDismissed(memberFid ?? undefined, address ?? undefined).then((serverDismissed) => {
      if (serverDismissed && !getStoredValue(STORAGE_KEYS.DISMISSED_MEMBERSHIP_PROMPT, false)) {
        // Server says dismissed but localStorage doesn't know — sync it
        setHasDismissedMembershipPrompt(true);
        setStoredValue(STORAGE_KEYS.DISMISSED_MEMBERSHIP_PROMPT, true);
      }
    });
  }, [isMembershipLoading, isMember, memberFid, address]);

  // Auto-mark current platform as seen after a short delay
  useEffect(() => {
    if (currentPlatform && isFirstVisitOnPlatform) {
      // Mark as seen after popup is shown (3 second delay)
      const timeout = setTimeout(() => {
        markPlatformSeen(currentPlatform);
      }, 3000);
      return () => clearTimeout(timeout);
    }
  }, [currentPlatform, isFirstVisitOnPlatform, markPlatformSeen]);

  return {
    currentPlatform,
    isFarcasterVerified,
    isBaseAppVerified,
    isWebVerified,
    hasLinkedAccounts,
    hasSeenWelcome,
    hasDismissedLinkPrompt,
    hasDismissedMembershipPrompt,
    isFirstVisitOnPlatform,
    isLoading: appMode === "detecting" || isFarcasterLoading || isMembershipLoading,
    dismissWelcome,
    dismissLinkPrompt,
    dismissMembershipPrompt,
    markPlatformSeen,
  };
}
src/hooks/use-reading-queue.ts
"use client";

import { useState, useEffect, useCallback } from "react";
import type { QueuedBook } from "@/features/app/types";

interface QueuedBookEntry {
  id: string;
  contentKey: string;
  title: string;
  author: string;
  categories: string[];
  addedAt: number;
  estimatedReadTime: string;
  progress: number;
}

interface _UserReadingQueue {
  address: string;
  items: QueuedBookEntry[];
  lastUpdated: number;
}

// Convert API entry to QueuedBook
function entryToQueuedBook(entry: QueuedBookEntry): QueuedBook {
  return {
    id: entry.id,
    title: entry.title,
    author: entry.author,
    categories: entry.categories,
    addedDate: new Date(entry.addedAt).toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    }),
    estimatedReadTime: entry.estimatedReadTime,
    progress: entry.progress,
  };
}

export function useReadingQueue(address?: string) {
  const [queue, setQueue] = useState<QueuedBook[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Fetch queue on mount and when address changes
  const fetchQueue = useCallback(async () => {
    if (!address) {
      setQueue([]);
      setIsLoading(false);
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(`/api/reading-queue?address=${encodeURIComponent(address)}`);
      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to fetch queue");
      }

      const items = (data.queue?.items || []).map(entryToQueuedBook);
      setQueue(items);
    } catch (err) {
      console.error("Fetch queue error:", err);
      setError(err instanceof Error ? err.message : "Failed to fetch queue");
    } finally {
      setIsLoading(false);
    }
  }, [address]);

  useEffect(() => {
    fetchQueue();
  }, [fetchQueue]);

  // Add item to queue
  const addToQueue = useCallback(
    async (item: {
      contentKey: string;
      title: string;
      author: string;
      categories: string[];
      estimatedReadTime?: string;
    }) => {
      if (!address) return false;

      try {
        const response = await fetch("/api/reading-queue", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            address,
            action: "add",
            item,
          }),
        });

        const data = await response.json();

        if (response.ok && data.queue) {
          setQueue((data.queue.items || []).map(entryToQueuedBook));
          return true;
        }
        return false;
      } catch (err) {
        console.error("Add to queue error:", err);
        return false;
      }
    },
    [address]
  );

  // Remove item from queue
  const removeFromQueue = useCallback(
    async (itemId: string) => {
      if (!address) return false;

      try {
        const response = await fetch("/api/reading-queue", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            address,
            action: "remove",
            itemId,
          }),
        });

        const data = await response.json();

        if (response.ok && data.queue) {
          setQueue((data.queue.items || []).map(entryToQueuedBook));
          return true;
        }
        return false;
      } catch (err) {
        console.error("Remove from queue error:", err);
        return false;
      }
    },
    [address]
  );

  // Update progress for an item
  const updateProgress = useCallback(
    async (itemId: string, progress: number) => {
      if (!address) return false;

      try {
        const response = await fetch("/api/reading-queue", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            address,
            action: "update-progress",
            itemId,
            progress,
          }),
        });

        const data = await response.json();

        if (response.ok && data.queue) {
          setQueue((data.queue.items || []).map(entryToQueuedBook));
          return true;
        }
        return false;
      } catch (err) {
        console.error("Update progress error:", err);
        return false;
      }
    },
    [address]
  );

  // Reorder items in queue
  const reorderQueue = useCallback(
    async (newOrder: string[]) => {
      if (!address) return false;

      try {
        const response = await fetch("/api/reading-queue", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            address,
            action: "reorder",
            newOrder,
          }),
        });

        const data = await response.json();

        if (response.ok && data.queue) {
          setQueue((data.queue.items || []).map(entryToQueuedBook));
          return true;
        }
        return false;
      } catch (err) {
        console.error("Reorder queue error:", err);
        return false;
      }
    },
    [address]
  );

  // Check if an item is in the queue
  const isInQueue = useCallback(
    (contentKeyOrTitle: string) => {
      return queue.some(
        (item) =>
          item.title === contentKeyOrTitle || item.id.includes(contentKeyOrTitle)
      );
    },
    [queue]
  );

  return {
    queue,
    isLoading,
    error,
    refresh: fetchQueue,
    addToQueue,
    removeFromQueue,
    updateProgress,
    reorderQueue,
    isInQueue,
  };
}
src/hooks/use-relay-batch-upload-v2.ts
"use client";

/**
 * Batch File Relay Upload Hook v2 - Proper x402 SDK Integration
 *
 * Uses @net-protocol/relay SDK with proper x402 payment protocol.
 * Key improvements over v1:
 * - x402 handles payment automatically (EIP-3009 authorization, not transfer)
 * - User doesn't pay gas for USDC transfer
 * - SDK's batchTransactions() for optimal batching
 * - Single session for all files in a batch
 *
 * Works on:
 * - Farcaster Mini Apps (Smart Wallets via EIP-5792)
 * - Base App (Coinbase Smart Wallet)
 * - WalletConnect (EOA wallets like MetaMask)
 */

import { useState, useCallback, useMemo, useRef, useEffect } from "react";
import { useAccount, usePublicClient, useWalletClient, useConfig, useSendCalls, useWriteContract } from "wagmi";
import { getCallsStatus } from "@wagmi/core";
import { createPublicClient, http, type Address, type Hash, encodeFunctionData, getAddress } from "viem";
import { base } from "viem/chains";

// Shared utilities for Smart Wallet detection and error handling
import {
  isSmartWalletDeployed,
  isSimulationFailure,
  analyzeUploadError,
  ERC20_ABI,
  USDC_ADDRESS,
  USDC_DECIMALS,
} from "@/lib/relay-upload-utils";
import { NET_LIBRARY_DATA_SUFFIX } from "@/lib/constants";
import { useWalletCapabilities } from "@/hooks/use-wallet-capabilities";

// SDK imports
import { RelayClient, batchTransactions, waitForConfirmations } from "@net-protocol/relay";
import { generateXmlMetadata } from "@net-protocol/storage";
import type { WriteTransactionConfig } from "@net-protocol/core";
import { stringToHex } from "viem";

// Local imports
import { createWagmiLocalAccount } from "@/lib/wagmi-x402-adapter";
import {
  CHUNKED_STORAGE_ADDRESS,
  STORAGE_CONTRACT_ADDRESS,
  CHUNKED_STORAGE_ABI,
  STORAGE_ABI,
  BASE_CHAIN_ID,
  prepareFileForUploadLegacy,
  getCdnUrl,
  createBookMetadata,
  generateStorageKey,
  createDiscoveryEntry,
  detectMediaTypeFromMime,
  detectMediaTypeFromExtension,
} from "@/lib/net-protocol";
import { detectFarcasterFrame } from "@/lib/app-mode";

// =============================================================================
// CONFIGURATION
// =============================================================================

const RELAY_CONFIG = {
  apiUrl: "https://www.netprotocol.app",
  chainId: BASE_CHAIN_ID,
  secretKey: "[REDACTED]",
  usdcAddress: USDC_ADDRESS,
  // x402 facilitator address (receives USDC payments, converts to ETH for relay wallet)
  x402FacilitatorAddress: "0x6462F8f301Bd08c206ee611aA00015bA41acc1D0" as Address,
} as const;

// Dedicated Base public client for USDC balance checks
const basePublicClient = createPublicClient({
  chain: base,
  transport: http("https://mainnet.base.org"),
});

// ERC20_ABI and USDC_DECIMALS imported from relay-upload-utils

// =============================================================================
// TYPES
// =============================================================================

export type BatchRelayStatus =
  | "idle"
  | "estimating"
  | "checking-balance"
  | "needs-funding"
  | "funding"
  | "creating-session"
  | "preparing"
  | "uploading"
  | "updating-index"
  | "complete"
  | "partial-success"
  | "error";

export interface FileUploadResult {
  fileName: string;
  fileSize: number;
  success: boolean;
  cdnUrl?: string;
  contentKey?: string;
  error?: string;
  transactionCount: number;
  costUsdc: number;
}

export interface BatchRelayProgress {
  status: BatchRelayStatus;
  // Cost tracking (USDC equivalent for display)
  estimatedTotalCostUsdc: number;
  actualTotalCostUsdc: number;
  // Balance info
  backendWalletBalance: number;
  backendWalletBalanceEth: number;
  userUsdcBalance: number;
  sufficientBalance: boolean;
  // File-level progress
  totalFiles: number;
  completedFiles: number;
  currentFileName: string;
  fileResults: FileUploadResult[];
  // Transaction-level progress
  totalTransactions: number;
  completedTransactions: number;
  // Batch progress
  currentBatch: number;
  totalBatches: number;
  // Status
  currentStep: string;
  error?: string;
  txHashes: Hash[];
}

export interface BatchFileItem {
  file: File;
  metadata: {
    title: string;
    author: string;
    categories: string[];
    coverUrl?: string;
    publicationYear?: number;
    publisher?: string;
    isbn?: string;
    uploaderFid?: number;
    uploaderUsername?: string;
    contentHash?: string;
  };
}

export interface BatchUploadResult {
  success: boolean;
  results: FileUploadResult[];
  totalCostUsdc: number;
  usedRelay: boolean;
  error?: string;
}

// =============================================================================
// HOOK
// =============================================================================

export function useRelayBatchUploadV2() {
  const { address, isConnected } = useAccount();
  const publicClient = usePublicClient();
  const { data: walletClient } = useWalletClient();

  const [progress, setProgress] = useState<BatchRelayProgress>({
    status: "idle",
    estimatedTotalCostUsdc: 0,
    actualTotalCostUsdc: 0,
    backendWalletBalance: 0,
    backendWalletBalanceEth: 0,
    userUsdcBalance: 0,
    sufficientBalance: false,
    totalFiles: 0,
    completedFiles: 0,
    currentFileName: "",
    fileResults: [],
    totalTransactions: 0,
    completedTransactions: 0,
    currentBatch: 0,
    totalBatches: 0,
    currentStep: "",
    txHashes: [],
  });

  // Wagmi hooks for Smart Wallet transactions
  const config = useConfig();
  const { sendCallsAsync } = useSendCalls();
  const { writeContractAsync } = useWriteContract();

  // Upfront capabilities detection — used to choose transaction strategy without trial-and-error.
  const { hasAtomicBatch, isLoading: capabilitiesLoading } = useWalletCapabilities();

  // Session token reference (reused across files in batch)
  const sessionTokenRef = useRef<string | null>(null);
  const sessionExpiresAtRef = useRef<number>(0);

  // Track the address the session was created for (prevents using wrong session after wallet switch)
  const sessionAddressRef = useRef<string | null>(null);

  // Upload-in-progress guard to prevent concurrent batch uploads
  const uploadInProgressRef = useRef<boolean>(false);

  // AbortController for cancellable operations
  const abortControllerRef = useRef<AbortController | null>(null);

  // Clear session when wallet address changes (prevents using wrong session after wallet switch)
  useEffect(() => {
    if (address !== sessionAddressRef.current) {
      if (sessionTokenRef.current) {
        console.log(`[RELAY-BATCH-V2] Wallet changed (${sessionAddressRef.current?.slice(0, 8)} → ${address?.slice(0, 8)}), clearing session`);
      }
      sessionTokenRef.current = null;
      sessionExpiresAtRef.current = 0;
      sessionAddressRef.current = address || null;

      // Abort any in-progress operations when wallet changes
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
        abortControllerRef.current = null;
      }
      uploadInProgressRef.current = false;
    }
  }, [address]);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, []);

  // Detect Farcaster mode
  const isFarcasterMode = useMemo(() => {
    if (typeof window === "undefined") return true;
    return detectFarcasterFrame();
  }, []);

  // Get or create RelayClient
  const getRelayClient = useCallback(() => {
    return new RelayClient({
      apiUrl: RELAY_CONFIG.apiUrl,
      chainId: RELAY_CONFIG.chainId,
    });
  }, []);

  /**
   * Check user's USDC balance on Base chain
   */
  const checkUserUsdcBalance = useCallback(async (): Promise<number> => {
    if (!address) return 0;

    try {
      const balance = await basePublicClient.readContract({
        address: RELAY_CONFIG.usdcAddress,
        abi: ERC20_ABI,
        functionName: "balanceOf",
        args: [address],
      });
      const balanceUsdc = Number(balance) / 10 ** USDC_DECIMALS;
      console.log(`[RELAY-BATCH-V2] USDC balance: ${balanceUsdc} for ${address}`);
      return balanceUsdc;
    } catch (error) {
      console.error("[RELAY-BATCH-V2] Failed to check USDC balance:", error);
      return 0;
    }
  }, [address]);

  /**
   * Check backend wallet balance via SDK
   */
  const checkBalance = useCallback(async () => {
    if (!address) return null;

    try {
      const relayClient = getRelayClient();
      const result = await relayClient.checkBalance({
        operatorAddress: address,
        secretKey: RELAY_CONFIG.secretKey,
      });

      console.log("[RELAY-BATCH-V2] Backend wallet balance:", result);
      return result;
    } catch (error) {
      console.error("[RELAY-BATCH-V2] checkBalance error:", error);
      return null;
    }
  }, [address, getRelayClient]);

  /**
   * Fund backend wallet with proper Smart Wallet handling
   *
   * CRITICAL: This uses the same robust funding flow as single upload:
   * 1. Get x402 payment info (payTo address, amount)
   * 2. Check if Smart Wallet is deployed
   * 3. Try sendCallsAsync (EIP-5792) for Smart Wallets
   * 4. Fall back to writeContractAsync for EOA wallets
   * 5. Handle simulation failures gracefully
   */
  const fundBackendWallet = useCallback(async (requestedAmountUsdc?: number): Promise<boolean> => {
    if (!address || !walletClient) {
      throw new Error("Wallet not connected");
    }

    const requestedAmount = requestedAmountUsdc || 1.0; // Default to $1.00

    console.log(`[RELAY-BATCH-V2] Starting funding flow for $${requestedAmount.toFixed(2)} USDC...`);

    try {
      setProgress((prev) => ({
        ...prev,
        status: "funding",
        currentStep: "Getting payment info...",
      }));

      // Step 1: Get backend wallet address and x402 payment info
      const balanceInfo = await checkBalance();
      if (!balanceInfo) {
        throw new Error("Could not get backend wallet info");
      }
      const originalBalanceEth = parseFloat(balanceInfo.balanceEth);

      // Get x402 payment info from local API
      const fundResponse = await fetch("/api/relay/fund", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          operatorAddress: address,
          chainId: RELAY_CONFIG.chainId,
          amountUsdc: requestedAmount,
        }),
      });

      if (fundResponse.status !== 402) {
        const errorData = await fundResponse.json().catch(() => ({ error: "Unknown error" }));
        throw new Error(errorData.error || "Unexpected response from funding API");
      }

      // Parse x402 response
      const paymentInfo = await fundResponse.json();
      const accepts = paymentInfo.accepts?.[0];
      const payTo = accepts?.payTo || accepts?.payToAddress || accepts?.recipient;
      const maxAmount = accepts?.maxAmountRequired || accepts?.maxAmount || accepts?.amount;

      // Parse amount (may be in wei or USDC units)
      let amountUsdc = requestedAmount;
      if (maxAmount) {
        const maxAmountNum = Number(maxAmount);
        if (maxAmountNum > 1_000_000) {
          amountUsdc = maxAmountNum / 1_000_000;
        } else {
          amountUsdc = maxAmountNum;
        }
      }

      if (!payTo) {
        throw new Error("Payment info missing payTo address");
      }

      const amountWei = BigInt(Math.ceil(amountUsdc * 1_000_000));
      console.log(`[RELAY-BATCH-V2] Payment: $${amountUsdc.toFixed(2)} USDC to ${payTo}`);

      // Step 2: Check if Smart Wallet is deployed
      const walletDeployed = await isSmartWalletDeployed(address);
      console.log(`[RELAY-BATCH-V2] Smart Wallet deployed: ${walletDeployed}`);

      // Step 3: Prepare USDC transfer calldata
      const transferCalldata = encodeFunctionData({
        abi: ERC20_ABI,
        functionName: "transfer",
        args: [getAddress(payTo), amountWei],
      });

      setProgress((prev) => ({
        ...prev,
        currentStep: "Sending USDC payment...",
      }));

      let actualTxHash: `0x${string}` | undefined;

      console.log(`[RELAY-BATCH-V2] Capabilities — hasAtomicBatch: ${hasAtomicBatch}, loading: ${capabilitiesLoading}`);

      // Skip sendCallsAsync if:
      //   - capabilities are still loading (default safe: assume no EIP-5792 until confirmed), OR
      //   - capabilities resolved and the wallet does NOT support atomic batch.
      // This prevents firing sendCallsAsync on an EOA wallet if the user clicks
      // before wallet_getCapabilities returns.
      const skipSendCalls = capabilitiesLoading || !hasAtomicBatch;
      if (skipSendCalls) {
        console.log(`[RELAY-BATCH-V2] Wallet does not support EIP-5792 — skipping sendCallsAsync, using writeContractAsync directly.`);
      }

      // Step 4: Try sendCallsAsync first (for Smart Wallets)
      try {
        if (skipSendCalls) throw new Error("Wallet does not support EIP-5792 — skipping to EOA path");
        const result = await sendCallsAsync({
          calls: [{
            to: RELAY_CONFIG.usdcAddress,
            data: transferCalldata,
            value: 0n,
          }],
          chainId: RELAY_CONFIG.chainId,
          capabilities: {
            // ERC-8021 onchain attribution for Net Library (bc_d7041lf9).
            // optional: true — wallets that don't support dataSuffix will still
            // process the transaction normally.
            dataSuffix: {
              value: NET_LIBRARY_DATA_SUFFIX,
              optional: true,
            },
          },
        });

        const batchId = typeof result === "string" ? result : result.id;
        console.log(`[RELAY-BATCH-V2] sendCallsAsync submitted, batch ID: ${batchId}`);

        // Poll for tx hash
        setProgress((prev) => ({
          ...prev,
          currentStep: "Waiting for confirmation...",
        }));

        let pollAttempts = 0;
        while (!actualTxHash && pollAttempts < 60) {
          await new Promise((resolve) => setTimeout(resolve, 1000));
          pollAttempts++;

          try {
            const status = await getCallsStatus(config, { id: batchId });
            if (status.status === "success" && status.receipts?.[0]) {
              actualTxHash = status.receipts[0].transactionHash;
              console.log(`[RELAY-BATCH-V2] Got tx hash: ${actualTxHash}`);
            } else if (status.status === "failure") {
              throw new Error("USDC transfer failed on-chain");
            }
          } catch (pollError) {
            if (pollAttempts > 10) {
              const msg = pollError instanceof Error ? pollError.message : String(pollError);
              console.log(`[RELAY-BATCH-V2] Poll ${pollAttempts}: ${msg.slice(0, 50)}`);
            }
          }
        }

        // Fallback: verify via balance check
        if (!actualTxHash) {
          console.warn(`[RELAY-BATCH-V2] Could not get tx hash, verifying via balance...`);
          setProgress((prev) => ({
            ...prev,
            currentStep: "Verifying payment...",
          }));

          let balanceAttempts = 0;
          while (balanceAttempts < 30) {
            await new Promise((resolve) => setTimeout(resolve, 1000));
            balanceAttempts++;

            const newBalanceInfo = await checkBalance();
            const newBalanceEth = parseFloat(newBalanceInfo?.balanceEth || "0");

            if (newBalanceEth > originalBalanceEth + 0.00001) {
              console.log(`[RELAY-BATCH-V2] ✅ Balance increased!`);
              setProgress((prev) => ({
                ...prev,
                status: "checking-balance",
                backendWalletBalance: newBalanceEth * 3500,
                backendWalletBalanceEth: newBalanceEth,
                sufficientBalance: true,
              }));
              return true;
            }
          }
          throw new Error("Funding verification timed out");
        }
      } catch (smartWalletError) {
        const errMsg = smartWalletError instanceof Error ? smartWalletError.message : String(smartWalletError);
        console.error(`[RELAY-BATCH-V2] sendCallsAsync error:`, errMsg.slice(0, 100));

        // Check for user rejection
        if (errMsg.toLowerCase().includes("user rejected") || errMsg.toLowerCase().includes("user denied")) {
          throw new Error("User cancelled transaction");
        }

        // Check for simulation failure
        if (isSimulationFailure(errMsg)) {
          console.error(`[RELAY-BATCH-V2] Simulation failure detected. Wallet deployed: ${walletDeployed}`);

          const userBalance = await checkUserUsdcBalance();
          if (userBalance < amountUsdc) {
            throw new Error(`Insufficient USDC. Have $${userBalance.toFixed(2)}, need $${amountUsdc.toFixed(2)}`);
          }

          if (!walletDeployed) {
            throw new Error(
              "Your Smart Wallet needs activation. " +
              "Try a smaller amount ($0.10) or receive some ETH first."
            );
          }

          throw new Error("Transaction simulation failed. Please try again.");
        }

        // Fallback to writeContractAsync for EOA wallets
        console.log(`[RELAY-BATCH-V2] Trying writeContractAsync (EOA)...`);

        try {
          setProgress((prev) => ({
            ...prev,
            currentStep: "Sending USDC payment (EOA)...",
          }));

          actualTxHash = await writeContractAsync({
            address: RELAY_CONFIG.usdcAddress,
            abi: ERC20_ABI,
            functionName: "transfer",
            args: [payTo as `0x${string}`, amountWei],
            chainId: RELAY_CONFIG.chainId,
          });
          console.log(`[RELAY-BATCH-V2] writeContractAsync submitted: ${actualTxHash}`);
        } catch (eoaError) {
          const eoaErrMsg = eoaError instanceof Error ? eoaError.message : String(eoaError);
          console.error(`[RELAY-BATCH-V2] Both methods failed:`, eoaErrMsg.slice(0, 100));

          if (isSimulationFailure(eoaErrMsg)) {
            const userBalance = await checkUserUsdcBalance();
            if (userBalance < amountUsdc) {
              throw new Error(`Insufficient USDC. Have $${userBalance.toFixed(2)}, need $${amountUsdc.toFixed(2)}`);
            }
            throw new Error("Transaction failed. Please check your wallet and try again.");
          }

          throw eoaError;
        }
      }

      // Step 5: Wait for balance to increase
      if (actualTxHash) {
        setProgress((prev) => ({
          ...prev,
          currentStep: "Verifying payment...",
        }));

        await new Promise((resolve) => setTimeout(resolve, 3000));

        let verifyAttempts = 0;
        while (verifyAttempts < 30) {
          await new Promise((resolve) => setTimeout(resolve, 2000));
          verifyAttempts++;

          const newBalanceInfo = await checkBalance();
          const newBalanceEth = parseFloat(newBalanceInfo?.balanceEth || "0");

          if (newBalanceEth > originalBalanceEth + 0.00001) {
            console.log(`[RELAY-BATCH-V2] ✅ Funding verified!`);
            setProgress((prev) => ({
              ...prev,
              status: "checking-balance",
              backendWalletBalance: newBalanceEth * 3500,
              backendWalletBalanceEth: newBalanceEth,
              sufficientBalance: true,
              currentStep: `Funded $${amountUsdc.toFixed(2)}!`,
            }));
            return true;
          }
        }

        throw new Error("Payment sent but verification timed out");
      }

      throw new Error("No transaction hash obtained");
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : String(error);
      console.error(`[RELAY-BATCH-V2] Funding error:`, errMsg);

      setProgress((prev) => ({
        ...prev,
        status: "error",
        currentStep: errMsg,
      }));

      throw new Error(errMsg);
    }
  }, [address, walletClient, config, sendCallsAsync, writeContractAsync, checkBalance, checkUserUsdcBalance]);

  /**
   * Ensure we have a valid session
   */
  const ensureSession = useCallback(async (): Promise<string> => {
    if (!address || !walletClient) {
      throw new Error("Wallet not connected");
    }

    // Check if existing session is still valid (with 5 min buffer)
    const now = Date.now();
    if (sessionTokenRef.current && sessionExpiresAtRef.current > now + 5 * 60 * 1000) {
      console.log("[RELAY-BATCH-V2] Reusing existing session");
      return sessionTokenRef.current;
    }

    console.log("[RELAY-BATCH-V2] Creating new session...");

    const account = createWagmiLocalAccount(walletClient);
    const relayClient = getRelayClient();

    const sessionResult = await relayClient.createSession({
      operatorAddress: address,
      secretKey: RELAY_CONFIG.secretKey,
      account,
      expiresIn: 3600, // 1 hour
    });

    sessionTokenRef.current = sessionResult.sessionToken;
    sessionExpiresAtRef.current = now + 55 * 60 * 1000; // 55 minutes from now

    console.log("[RELAY-BATCH-V2] Session created, expires at:", new Date(sessionExpiresAtRef.current));

    return sessionResult.sessionToken;
  }, [address, walletClient, getRelayClient]);

  /**
   * Estimate cost for a batch of files
   */
  const estimateBatchCost = useCallback(
    async (
      items: BatchFileItem[]
    ): Promise<{
      totalCostUsdc: number;
      totalTransactions: number;
      perFileCosts: Array<{ fileName: string; costUsdc: number; transactions: number }>;
      balanceInfo: {
        balanceUsdc: number;
        sufficient: boolean;
        shortfallUsdc: number;
      } | null;
      userUsdcBalance: number;
      canProceed: boolean;
      needsFunding: boolean;
      lowBalance: boolean;
    }> => {
      if (!address) {
        return {
          totalCostUsdc: 0,
          totalTransactions: 0,
          perFileCosts: [],
          balanceInfo: null,
          userUsdcBalance: 0,
          canProceed: false,
          needsFunding: false,
          lowBalance: false,
        };
      }

      // Estimate per-file costs
      const perFileCosts = items.map((item) => {
        let transactions = 2; // content + metadata
        if (item.file.size >= 80000) {
          const numChunks = Math.ceil(item.file.size / 20000);
          transactions = numChunks + 2;
        }
        return {
          fileName: item.file.name,
          costUsdc: transactions * 0.015,
          transactions,
        };
      });

      const totalTransactions = perFileCosts.reduce((sum, f) => sum + f.transactions, 0);
      const totalCostUsdc = perFileCosts.reduce((sum, f) => sum + f.costUsdc, 0);

      // Check balances
      const [balanceResult, userUsdcBalance] = await Promise.all([
        checkBalance(),
        checkUserUsdcBalance(),
      ]);

      if (!balanceResult) {
        return {
          totalCostUsdc,
          totalTransactions,
          perFileCosts,
          balanceInfo: null,
          userUsdcBalance,
          canProceed: false,
          needsFunding: userUsdcBalance >= 1,
          lowBalance: false,
        };
      }

      const balanceEth = parseFloat(balanceResult.balanceEth);
      const balanceUsdc = balanceEth * 3500;
      const sufficient = balanceResult.sufficientBalance && balanceUsdc >= totalCostUsdc;
      const shortfallUsdc = sufficient ? 0 : Math.max(0, totalCostUsdc - balanceUsdc);

      const lowBalance = balanceUsdc < 0.10; // $0.10 minimum

      return {
        totalCostUsdc,
        totalTransactions,
        perFileCosts,
        balanceInfo: {
          balanceUsdc,
          sufficient,
          shortfallUsdc,
        },
        userUsdcBalance,
        canProceed: sufficient,
        needsFunding: !sufficient && userUsdcBalance >= shortfallUsdc,
        lowBalance,
      };
    },
    [address, checkBalance, checkUserUsdcBalance]
  );

  /**
   * Upload a batch of files
   *
   * CRITICAL: This function now includes all protections from single upload:
   * - Upload-in-progress guard (prevents concurrent batch uploads)
   * - AbortController for cancellable operations
   * - Proper error analysis with Smart Wallet detection
   */
  const uploadBatch = useCallback(
    async (items: BatchFileItem[]): Promise<BatchUploadResult> => {
      if (!address || !walletClient || !publicClient) {
        return {
          success: false,
          results: [],
          totalCostUsdc: 0,
          usedRelay: true,
          error: "Wallet not connected",
        };
      }

      // Prevent concurrent batch uploads
      if (uploadInProgressRef.current) {
        console.warn(`[RELAY-BATCH-V2] Batch upload already in progress, ignoring new request`);
        return {
          success: false,
          results: [],
          totalCostUsdc: 0,
          usedRelay: true,
          error: "Batch upload already in progress",
        };
      }

      // Create new AbortController for this batch upload
      abortControllerRef.current = new AbortController();
      const signal = abortControllerRef.current.signal;

      // Mark batch upload as in progress
      uploadInProgressRef.current = true;

      console.log(`[RELAY-BATCH-V2] Starting batch upload: ${items.length} files`);

      const fileResults: FileUploadResult[] = [];
      const allTxHashes: Hash[] = [];

      try {
        // Initialize progress
        setProgress({
          status: "checking-balance",
          estimatedTotalCostUsdc: 0,
          actualTotalCostUsdc: 0,
          backendWalletBalance: 0,
          backendWalletBalanceEth: 0,
          userUsdcBalance: 0,
          sufficientBalance: false,
          totalFiles: items.length,
          completedFiles: 0,
          currentFileName: "",
          fileResults: [],
          totalTransactions: 0,
          completedTransactions: 0,
          currentBatch: 0,
          totalBatches: 0,
          currentStep: "Checking balance...",
          txHashes: [],
        });

        // Step 1: Check balance and estimate costs
        const estimate = await estimateBatchCost(items);

        setProgress((prev) => ({
          ...prev,
          estimatedTotalCostUsdc: estimate.totalCostUsdc,
          totalTransactions: estimate.totalTransactions,
          backendWalletBalance: estimate.balanceInfo?.balanceUsdc || 0,
          userUsdcBalance: estimate.userUsdcBalance,
          sufficientBalance: estimate.canProceed,
        }));

        // Step 2: Fund if needed
        if (!estimate.canProceed) {
          if (estimate.needsFunding) {
            setProgress((prev) => ({
              ...prev,
              status: "needs-funding",
              currentStep: "Funding required...",
            }));
            return {
              success: false,
              results: [],
              totalCostUsdc: 0,
              usedRelay: true,
              error: "NEEDS_FUNDING",
            };
          } else {
            return {
              success: false,
              results: [],
              totalCostUsdc: 0,
              usedRelay: true,
              error: "Insufficient USDC balance",
            };
          }
        }

        // Step 3: Create session
        setProgress((prev) => ({
          ...prev,
          status: "creating-session",
          currentStep: "Creating relay session...",
        }));

        const sessionToken = await ensureSession();

        // Step 4: Process each file
        const relayClient = getRelayClient();
        let completedTransactions = 0;

        // Get the actual operator (backend wallet) that writes to chain
        // This is needed for correct CDN URL generation and discovery indexing
        const balanceResult = await checkBalance();
        const actualOperator = balanceResult?.backendWalletAddress || address;
        console.log(`[RELAY-BATCH-V2] Using backend wallet as operator: ${actualOperator}`);

        for (let i = 0; i < items.length; i++) {
          // Check if upload was cancelled
          if (signal.aborted) {
            console.log(`[RELAY-BATCH-V2] Upload cancelled at file ${i + 1}/${items.length}`);
            throw new Error("Batch upload cancelled");
          }

          const item = items[i];
          const { file, metadata } = item;

          setProgress((prev) => ({
            ...prev,
            status: "preparing",
            currentFileName: file.name,
            currentStep: `Preparing ${file.name}...`,
          }));

          try {
            // Prepare file for storage
            const prepared = await prepareFileForUploadLegacy(file);
            console.log(`[RELAY-BATCH-V2] File prepared:`, {
              fileName: file.name,
              storageType: prepared.storageType,
              key: prepared.key,
              xmlChunks: prepared.xmlChunks?.length,
            });

            // Build transactions for this file using WriteTransactionConfig format
            const transactions: WriteTransactionConfig[] = [];

            // Add content transactions
            if (prepared.storageType === "xml" && prepared.xmlChunks) {
              // XML storage - multiple chunk transactions
              for (let chunkIdx = 0; chunkIdx < prepared.xmlChunks.length; chunkIdx++) {
                const xmlChunk = prepared.xmlChunks[chunkIdx];
                transactions.push({
                  to: CHUNKED_STORAGE_ADDRESS,
                  abi: CHUNKED_STORAGE_ABI,
                  functionName: "put",
                  args: [xmlChunk.key, "", xmlChunk.compressedChunks],
                });
              }

              // XML metadata transaction
              const xmlChunkKeys = prepared.xmlChunks.map((c) => c.key);
              const xmlMetadata = generateXmlMetadata(xmlChunkKeys, 0, address);
              transactions.push({
                to: STORAGE_CONTRACT_ADDRESS,
                abi: STORAGE_ABI,
                functionName: "put",
                args: [prepared.key, prepared.text, stringToHex(xmlMetadata)],
              });
            } else if (prepared.storageType === "chunked" && prepared.chunks) {
              // Chunked storage
              transactions.push({
                to: CHUNKED_STORAGE_ADDRESS,
                abi: CHUNKED_STORAGE_ABI,
                functionName: "put",
                args: [prepared.key, prepared.text, prepared.chunks],
              });
            } else {
              // Regular storage - use hex-encoded base64 data
              transactions.push({
                to: STORAGE_CONTRACT_ADDRESS,
                abi: STORAGE_ABI,
                functionName: "put",
                args: [prepared.key, prepared.text, prepared.dataHex || stringToHex(String.fromCharCode(...prepared.data))],
              });
            }

            // Add book metadata transaction
            const bookMetadata = createBookMetadata(
              metadata.title,
              metadata.author,
              metadata.categories,
              file.name,
              file.size,
              prepared.key,
              address,
              prepared.storageType
            );
            const bookMetadataKey = generateStorageKey(`netlib-meta-${prepared.key}`);
            transactions.push({
              to: STORAGE_CONTRACT_ADDRESS,
              abi: STORAGE_ABI,
              functionName: "put",
              args: [bookMetadataKey, `${metadata.title} by ${metadata.author}`, stringToHex(JSON.stringify(bookMetadata))],
            });

            // Add discovery entry
            const mediaType =
              file.type && file.type !== "application/octet-stream"
                ? detectMediaTypeFromMime(file.type)
                : detectMediaTypeFromExtension(file.name);

            // IMPORTANT: Two different addresses needed:
            // - actualOperator (backend wallet) = who wrote to blockchain, used for CDN URL generation
            // - address (user's wallet) = who gets credit/attribution for the upload
            const newEntry = createDiscoveryEntry(
              prepared.key,
              bookMetadataKey,
              actualOperator, // Backend wallet for CDN URL generation
              metadata.title,
              metadata.author,
              metadata.categories,
              file.size,
              prepared.storageType,
              metadata.coverUrl,
              {
                publicationYear: metadata.publicationYear,
                publisher: metadata.publisher,
                isbn: metadata.isbn,
                uploaderFid: metadata.uploaderFid,
                uploaderUsername: metadata.uploaderUsername,
                uploaderAddress: address, // User's wallet for attribution (NOT the relay backend)
                contentHash: metadata.contentHash,
                mediaType,
                fileName: file.name, // Original filename for correct CDN URL generation
                // IMPORTANT: Pre-compute and store the CDN URL so it's available for display
                cdnUrl: getCdnUrl(BASE_CHAIN_ID, actualOperator, prepared.key, prepared.storageType, file.name),
              }
            );
            const discoveryKey = generateStorageKey(`netlib-discovery-${prepared.key}`);
            transactions.push({
              to: STORAGE_CONTRACT_ADDRESS,
              abi: STORAGE_ABI,
              functionName: "put",
              args: [discoveryKey, `Discovery: ${metadata.title}`, stringToHex(JSON.stringify(newEntry))],
            });

            // Batch and submit transactions
            setProgress((prev) => ({
              ...prev,
              status: "uploading",
              currentStep: `Uploading ${file.name}...`,
            }));

            const batches = batchTransactions(transactions);
            const fileTxHashes: Hash[] = [];

            for (let batchIdx = 0; batchIdx < batches.length; batchIdx++) {
              const batch = batches[batchIdx];

              setProgress((prev) => ({
                ...prev,
                currentBatch: batchIdx + 1,
                totalBatches: batches.length,
                currentStep: `Uploading ${file.name} (batch ${batchIdx + 1}/${batches.length})...`,
              }));

              const submitResult = await relayClient.submitTransactions({
                operatorAddress: address,
                secretKey: RELAY_CONFIG.secretKey,
                transactions: batch,
                sessionToken,
              });

              fileTxHashes.push(...submitResult.transactionHashes);
              allTxHashes.push(...submitResult.transactionHashes);
              completedTransactions += batch.length - submitResult.failedIndexes.length;

              setProgress((prev) => ({
                ...prev,
                completedTransactions,
                txHashes: [...prev.txHashes, ...submitResult.transactionHashes],
              }));

              // Retry failed transactions
              if (submitResult.failedIndexes.length > 0) {
                console.log(`[RELAY-BATCH-V2] Retrying ${submitResult.failedIndexes.length} failed transactions...`);
                const retryResult = await relayClient.retryFailedTransactions({
                  operatorAddress: address,
                  secretKey: RELAY_CONFIG.secretKey,
                  originalTransactions: batch,
                  failedIndexes: submitResult.failedIndexes,
                  backendWalletAddress: (await checkBalance())?.backendWalletAddress || address,
                  sessionToken,
                });

                fileTxHashes.push(...retryResult.transactionHashes);
                allTxHashes.push(...retryResult.transactionHashes);
                completedTransactions += retryResult.transactionHashes.length;
              }
            }

            // Wait for confirmations
            setProgress((prev) => ({
              ...prev,
              status: "updating-index",
              currentStep: `Confirming ${file.name}...`,
            }));

            await waitForConfirmations({
              // eslint-disable-next-line @typescript-eslint/no-explicit-any
              publicClient: publicClient as any,
              transactionHashes: fileTxHashes,
              confirmations: 1,
            });

            // Update discovery index in KV store for immediate visibility
            // FIX: Previously batch uploads only stored discovery on-chain,
            // which meant items wouldn't appear in browse tab until blockchain re-indexed.
            // Now we update the KV store (same as single uploads) for instant visibility.
            try {
              await fetch("/api/discovery", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(newEntry),
              });
              console.log(`[RELAY-BATCH-V2] Updated discovery index for: ${metadata.title}`);
            } catch (discoveryError) {
              // Log but don't fail the upload - on-chain data is the source of truth
              console.error(`[RELAY-BATCH-V2] Failed to update discovery index:`, discoveryError);
            }

            // Success for this file
            // Pass filename to generate correct /storage/load/ URL format
            // IMPORTANT: Use actualOperator (backend wallet) not user address - that's who wrote to chain
            const cdnUrl = getCdnUrl(BASE_CHAIN_ID, actualOperator, prepared.key, prepared.storageType, file.name);
            fileResults.push({
              fileName: file.name,
              fileSize: file.size,
              success: true,
              cdnUrl,
              contentKey: prepared.key,
              transactionCount: transactions.length,
              costUsdc: transactions.length * 0.015,
            });

            setProgress((prev) => ({
              ...prev,
              completedFiles: i + 1,
              fileResults: [...fileResults],
            }));

            console.log(`[RELAY-BATCH-V2] File complete: ${file.name} -> ${cdnUrl}`);
          } catch (fileError) {
            console.error(`[RELAY-BATCH-V2] Error uploading ${file.name}:`, fileError);
            fileResults.push({
              fileName: file.name,
              fileSize: file.size,
              success: false,
              error: fileError instanceof Error ? fileError.message : "Upload failed",
              transactionCount: 0,
              costUsdc: 0,
            });

            setProgress((prev) => ({
              ...prev,
              completedFiles: i + 1,
              fileResults: [...fileResults],
            }));
          }
        }

        // Calculate final results
        const successCount = fileResults.filter((r) => r.success).length;
        const totalCostUsdc = fileResults.reduce((sum, r) => sum + r.costUsdc, 0);
        const allSucceeded = successCount === items.length;

        setProgress((prev) => ({
          ...prev,
          status: allSucceeded ? "complete" : successCount > 0 ? "partial-success" : "error",
          actualTotalCostUsdc: totalCostUsdc,
          currentStep: allSucceeded
            ? `All ${items.length} files uploaded!`
            : `${successCount}/${items.length} files uploaded`,
        }));

        return {
          success: allSucceeded,
          results: fileResults,
          totalCostUsdc,
          usedRelay: true,
        };
      } catch (error) {
        console.error("[RELAY-BATCH-V2] Batch upload error:", error);

        // Analyze the error for better user feedback
        const errorAnalysis = analyzeUploadError(error);

        setProgress((prev) => ({
          ...prev,
          status: "error",
          error: errorAnalysis.message,
          currentStep: errorAnalysis.isUserRejection ? "Cancelled" : "Upload failed",
        }));

        return {
          success: false,
          results: fileResults,
          totalCostUsdc: 0,
          usedRelay: true,
          error: errorAnalysis.message,
        };
      } finally {
        // Always clear in-progress flag when batch upload completes (success or failure)
        uploadInProgressRef.current = false;
        abortControllerRef.current = null;
      }
    },
    [
      address,
      walletClient,
      publicClient,
      checkBalance,
      estimateBatchCost,
      ensureSession,
      getRelayClient,
    ]
  );

  /**
   * Reset progress state
   */
  const reset = useCallback(() => {
    setProgress({
      status: "idle",
      estimatedTotalCostUsdc: 0,
      actualTotalCostUsdc: 0,
      backendWalletBalance: 0,
      backendWalletBalanceEth: 0,
      userUsdcBalance: 0,
      sufficientBalance: false,
      totalFiles: 0,
      completedFiles: 0,
      currentFileName: "",
      fileResults: [],
      totalTransactions: 0,
      completedTransactions: 0,
      currentBatch: 0,
      totalBatches: 0,
      currentStep: "",
      txHashes: [],
    });
  }, []);

  /**
   * Fund wallet (interface for add-funds-modal)
   */
  const fundWallet = useCallback(
    async (amountUsdc: number): Promise<boolean> => {
      console.log(`[RELAY-BATCH-V2] fundWallet called with $${amountUsdc}`);

      if (!address || !walletClient) {
        throw new Error("Wallet not connected");
      }

      try {
        await fundBackendWallet();
        return true;
      } catch (error) {
        console.error("[RELAY-BATCH-V2] fundWallet error:", error);
        throw error;
      }
    },
    [address, walletClient, fundBackendWallet]
  );

  /**
   * Get relay balance (interface for components)
   */
  const getRelayBalance = useCallback(async () => {
    if (!address) return null;

    const balanceResult = await checkBalance();
    if (!balanceResult) return null;

    const balanceEth = parseFloat(balanceResult.balanceEth);
    const balanceUsdc = balanceEth * 3500;
    // $0.10 minimum balance required
    const sufficient = balanceUsdc >= 0.10;

    return {
      balanceUsdc,
      backendWalletAddress: balanceResult.backendWalletAddress,
      sufficient,
      shortfallUsdc: 0,
      recommendedFundingUsdc: 5,
      lowBalance: balanceUsdc < 0.10,
    };
  }, [address, checkBalance]);

  /**
   * Cancel an in-progress batch upload
   */
  const cancelBatchUpload = useCallback(() => {
    if (abortControllerRef.current) {
      console.log(`[RELAY-BATCH-V2] Cancelling batch upload...`);
      abortControllerRef.current.abort();
      abortControllerRef.current = null;
    }
    uploadInProgressRef.current = false;
  }, []);

  return {
    // State
    progress,
    isFarcasterMode,
    isRelayAvailable: true,
    isUploading: uploadInProgressRef.current,

    // Actions
    uploadBatch,
    fundWallet,
    fundBackendWallet,
    reset,
    cancelBatchUpload,

    // Utilities
    estimateBatchCost,
    getRelayBalance,
    checkBalance,
    checkUserUsdcBalance,

    // Account info
    isConnected,
    address,
  };
}
src/hooks/use-relay-upload-v2.ts
"use client";

/**
 * Relay Upload Hook v3 - Proper x402 Integration with Robust Verify Flow
 *
 * This hook uses @net-protocol/relay SDK properly with x402 payment protocol.
 *
 * Key features:
 * 1. Uses RelayClient class from SDK instead of manual API calls
 * 2. Uses createRelayX402Client() for proper x402 payment handling
 * 3. Uses SDK's batchTransactions() for automatic batching
 * 4. Uses SDK's waitForConfirmations() for confirmation tracking
 * 5. Proper EIP-712 signed sessions via createRelaySession()
 * 6. x402 handles payment automatically (no manual USDC transfers!)
 *
 * v3 improvements:
 * 7. ROBUST VERIFY FLOW - Ensures verify is always called after payment with retries
 * 8. PAYMENT RECOVERY - Can scan for unverified payments and recover them
 * 9. Fixed funding presets: $0.10, $0.25, $5.00 (matching Net Protocol production)
 *
 * The x402 protocol uses EIP-3009 transferWithAuthorization, which means:
 * - User signs an authorization (not a transfer)
 * - Facilitator executes the transfer on user's behalf
 * - User doesn't pay gas for the USDC transfer!
 */

import { useState, useCallback, useMemo, useRef, useEffect } from "react";
import { useAccount, usePublicClient, useWalletClient, useConfig, useSendCalls, useWriteContract } from "wagmi";
import { getCallsStatus } from "@wagmi/core";
import { useSimplePrice } from "@/neynar-web-sdk/src/coingecko/api-hooks/hooks/simple";
import { NET_LIBRARY_DATA_SUFFIX } from "@/lib/constants";
import { useWalletCapabilities } from "@/hooks/use-wallet-capabilities";
import { stringToHex, encodeFunctionData } from "viem";
import type { Address, Hash } from "viem";

// Shared utilities for Smart Wallet detection and error handling
import {
  isSmartWalletDeployed,
  isSimulationFailure,
  ERC20_ABI,
  basePublicClient as sharedBasePublicClient,
} from "@/lib/relay-upload-utils";

// Net Protocol SDK imports
import {
  RelayClient,
  batchTransactions,
  type CheckBalanceResult,
} from "@net-protocol/relay";
import { generateXmlMetadata } from "@net-protocol/storage";
import type { WriteTransactionConfig } from "@net-protocol/core";

// Local imports
import { createWagmiLocalAccount } from "@/lib/wagmi-x402-adapter";
import {
  CHUNKED_STORAGE_ADDRESS,
  STORAGE_CONTRACT_ADDRESS,
  CHUNKED_STORAGE_ABI,
  STORAGE_ABI,
  BASE_CHAIN_ID,
  prepareFileForUploadLegacy,
  getCdnUrl,
  createBookMetadata,
  generateStorageKey,
  createDiscoveryEntry,
  detectMediaTypeFromMime,
  detectMediaTypeFromExtension,
} from "@/lib/net-protocol";
import { detectFarcasterFrame } from "@/lib/app-mode";

// =============================================================================
// CONFIGURATION
// =============================================================================

// In Farcaster Mini Apps, we use a local API proxy to avoid CORS issues
// The local routes forward requests to the real Net Protocol API
const getApiBaseUrl = () => {
  if (typeof window === "undefined") return "https://www.netprotocol.app";
  // Use relative URL for local API proxy
  return window.location.origin;
};

const RELAY_CONFIG = {
  // Direct external URL - used for SDK calls that work cross-origin
  apiUrl: "https://www.netprotocol.app",
  // Local proxy URL - used for funding (avoids CORS issues in Mini App)
  localApiUrl: getApiBaseUrl(),
  chainId: BASE_CHAIN_ID,
  secretKey: "[REDACTED]",
  usdcAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" as Address,
  // x402 facilitator address (receives USDC payments, converts to ETH for relay wallet)
  x402FacilitatorAddress: "0x6462F8f301Bd08c206ee611aA00015bA41acc1D0" as Address,
  // Verify retry settings
  verifyMaxRetries: 5,
  verifyRetryDelayMs: 2000,
} as const;

// Use shared Base public client for balance checks
// isSmartWalletDeployed, isSimulationFailure, ERC20_ABI imported from relay-upload-utils
const basePublicClient = sharedBasePublicClient;

// =============================================================================
// TYPES
// =============================================================================

export type RelayUploadStatus =
  | "idle"
  | "estimating"
  | "checking-balance"
  | "needs-funding"
  | "funding"
  | "creating-session"
  | "preparing"
  | "submitting"
  | "confirming"
  | "updating-index"
  | "complete"
  | "error"
  | "fallback-prompt"
  | "fallback-direct";

export interface RelayUploadProgress {
  status: RelayUploadStatus;
  // Cost tracking (in USDC equivalent for display)
  estimatedCostUsdc: number;
  estimatedCostEth: number;
  // Actual cost spent (calculated after upload)
  actualCostEth?: number;
  actualCostUsdc?: number;
  // Balance info (ETH stored as gas credits, shown as USDC equivalent)
  backendWalletBalance: number;
  backendWalletBalanceEth: number;
  userUsdcBalance: number;
  sufficientBalance: boolean;
  // Progress
  currentStep: string;
  totalTransactions: number;
  completedTransactions: number;
  // Batch progress
  currentBatch: number;
  totalBatches: number;
  // Results
  cdnUrl?: string;
  contentKey?: string;
  txHashes: Hash[];
  error?: string;
  // Fallback info (for compatibility with v1)
  fallbackReason?: string;
  canFallback: boolean;
}

export interface RelayUploadMetadata {
  title: string;
  author: string;
  categories: string[];
  coverUrl?: string;
  publicationYear?: number;
  publisher?: string;
  isbn?: string;
  uploaderFid?: number;
  uploaderUsername?: string;
  // Membership info - for unified identity across all platforms
  uploaderMemberId?: number;
  uploaderEnsSubname?: string;
  // Unified social identity: Farcaster username stored at signup
  // If @geaux.eth signed up via Farcaster, this shows "geaux.eth" everywhere
  uploaderStoredUsername?: string;
  contentHash?: string;
  /** When true, the file was AES-256-GCM encrypted client-side before upload */
  encrypted?: boolean;
  // Social receipt metadata (for archived social posts)
  isSocialReceipt?: boolean;
  socialPlatform?: string;
  originalUrl?: string;
  socialText?: string;
  socialAuthor?: string;
  socialTimestamp?: Date | string;
}

export interface RelayUploadResult {
  success: boolean;
  cdnUrl?: string;
  contentKey?: string;
  operator?: string;  // Backend wallet that wrote to chain (for CDN URL generation)
  error?: string;
  usedRelay: boolean;
  totalCostUsdc?: number;
  // Added for improved error handling
  warning?: string;  // Non-fatal warning (e.g., discovery index failed)
  partialUpload?: boolean;  // True if some but not all transactions completed
  completedTransactions?: number;  // Number of successful transactions
  failedTransactions?: number;  // Number of failed transactions
}

// =============================================================================
// HOOK
// =============================================================================

export function useRelayUploadV2() {
  const { address, isConnected, connector } = useAccount();
  const publicClient = usePublicClient();
  const { data: walletClient } = useWalletClient();
  const config = useConfig(); // For getCallsStatus polling
  const { sendCallsAsync } = useSendCalls(); // Smart Wallets (Farcaster, Base App)
  const { writeContractAsync } = useWriteContract(); // EOA wallets (browser, WalletConnect)

  // Upfront capabilities detection — used to choose transaction strategy without trial-and-error.
  // isLoading=true means we haven't heard back yet; fall back to try/catch in that case.
  const { hasAtomicBatch, isLoading: capabilitiesLoading } = useWalletCapabilities();

  // Live ETH price from CoinGecko (refreshes every 30 seconds)
  const { data: ethPriceData } = useSimplePrice(
    ['ethereum'],
    ['usd'],
    {},
    {
      refetchInterval: 30000,
      staleTime: 15000,
    }
  );
  const liveEthPriceUsd = ethPriceData?.ethereum?.usd || 3500; // Fallback to $3500 if API fails

  const [progress, setProgress] = useState<RelayUploadProgress>({
    status: "idle",
    estimatedCostUsdc: 0,
    estimatedCostEth: 0,
    backendWalletBalance: 0,
    backendWalletBalanceEth: 0,
    userUsdcBalance: 0,
    sufficientBalance: false,
    currentStep: "",
    totalTransactions: 0,
    completedTransactions: 0,
    currentBatch: 0,
    totalBatches: 0,
    txHashes: [],
    canFallback: true,
  });

  // Session token reference (persists during upload)
  const sessionTokenRef = useRef<string | null>(null);
  const sessionExpiresAtRef = useRef<number>(0);

  // Track the address the session was created for
  const sessionAddressRef = useRef<string | null>(null);

  // Upload-in-progress guard to prevent concurrent uploads
  const uploadInProgressRef = useRef<boolean>(false);

  // AbortController for cancellable operations
  const abortControllerRef = useRef<AbortController | null>(null);

  // Clear session when wallet address changes (prevents using wrong session after wallet switch)
  useEffect(() => {
    if (address !== sessionAddressRef.current) {
      if (sessionTokenRef.current) {
        console.log(`[RELAY-V3] Wallet changed (${sessionAddressRef.current?.slice(0, 8)} → ${address?.slice(0, 8)}), clearing session`);
      }
      sessionTokenRef.current = null;
      sessionExpiresAtRef.current = 0;
      sessionAddressRef.current = address || null;

      // Abort any in-progress operations when wallet changes
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
        abortControllerRef.current = null;
      }
      uploadInProgressRef.current = false;
    }
  }, [address]);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      if (abortControllerRef.current) {
        abortControllerRef.current.abort();
      }
    };
  }, []);

  const isFarcasterMode = useMemo(() => {
    if (typeof window === "undefined") return true;
    return detectFarcasterFrame();
  }, []);

  /**
   * Check user's USDC balance on Base chain
   */
  const checkUserUsdcBalance = useCallback(async (): Promise<number> => {
    if (!address) return 0;

    try {
      const balance = await basePublicClient.readContract({
        address: RELAY_CONFIG.usdcAddress,
        abi: ERC20_ABI,
        functionName: "balanceOf",
        args: [address],
      });
      const balanceUsdc = Number(balance) / 10 ** 6; // USDC has 6 decimals
      console.log(`[RELAY-V2] User USDC balance: $${balanceUsdc.toFixed(2)}`);
      return balanceUsdc;
    } catch (error) {
      console.error("[RELAY-V2] Failed to check USDC balance:", error);
      return 0;
    }
  }, [address]);

  /**
   * Check backend wallet balance using API route (same as UploadWalletBalance component)
   * This is more reliable than the SDK's checkBalance which can fail silently
   */
  const checkBalance = useCallback(async (): Promise<CheckBalanceResult | null> => {
    if (!address) return null;

    try {
      const response = await fetch("/api/relay/balance", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          operatorAddress: address,
          chainId: RELAY_CONFIG.chainId,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({ error: "Unknown error" }));
        console.error("[RELAY-V2] Balance API error:", errorData);
        return null;
      }

      const result = await response.json();

      if (!result.success && result.error) {
        console.error("[RELAY-V2] Balance check failed:", result.error);
        return null;
      }

      console.log(`[RELAY-V2] Backend wallet balance:`, {
        address: result.backendWalletAddress,
        balanceEth: result.balanceEth,
        sufficientBalance: result.sufficientBalance,
      });

      return {
        backendWalletAddress: result.backendWalletAddress,
        balanceEth: result.balanceEth || "0",
        balanceWei: result.balanceWei || "0",
        sufficientBalance: result.sufficientBalance || false,
        minRequiredWei: result.minRequiredWei || "0",
        minRequiredEth: result.minRequiredEth || "0",
      };
    } catch (error) {
      console.error("[RELAY-V2] Balance check failed:", error);
      return null;
    }
  }, [address]);

  /**
   * Verify a payment transaction with retries
   * This is the critical step that converts USDC payment to ETH in the backend wallet
   */
  const verifyPaymentWithRetries = useCallback(async (
    paymentTxHash: string,
    maxRetries: number = RELAY_CONFIG.verifyMaxRetries,
    retryDelayMs: number = RELAY_CONFIG.verifyRetryDelayMs
  ): Promise<{ success: boolean; backendWalletAddress?: string; error?: string }> => {
    const verifyUrl = `${RELAY_CONFIG.localApiUrl}/api/relay/fund/verify`;

    for (let attempt = 1; attempt <= maxRetries; attempt++) {
      console.log(`[RELAY-V3] Verify attempt ${attempt}/${maxRetries} for tx: ${paymentTxHash.slice(0, 20)}...`);

      try {
        const verifyResponse = await fetch(verifyUrl, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            operatorAddress: address,
            chainId: RELAY_CONFIG.chainId,
            paymentTxHash,
          }),
        });

        const verifyData = await verifyResponse.json();
        console.log(`[RELAY-V3] Verify response (attempt ${attempt}):`, verifyData);

        // Success!
        if (verifyData.success) {
          console.log(`[RELAY-V3] ✅ Payment verified successfully!`);
          return {
            success: true,
            backendWalletAddress: verifyData.backendWalletAddress,
          };
        }

        // Already processed is also success (idempotent)
        if (verifyData.alreadyProcessed) {
          console.log(`[RELAY-V3] ✅ Payment was already processed`);
          return {
            success: true,
            backendWalletAddress: verifyData.backendWalletAddress,
          };
        }

        // If we get a specific error, don't retry
        if (verifyData.error?.includes("Invalid payment") || verifyData.error?.includes("not found")) {
          console.error(`[RELAY-V3] ❌ Permanent error, not retrying:`, verifyData.error);
          return { success: false, error: verifyData.error };
        }

        // Transient error - retry after delay
        console.log(`[RELAY-V3] Verify failed (attempt ${attempt}), retrying in ${retryDelayMs}ms...`);

      } catch (error) {
        console.error(`[RELAY-V3] Verify request failed (attempt ${attempt}):`, error);
      }

      // Wait before retry (except on last attempt)
      if (attempt < maxRetries) {
        await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
      }
    }

    return { success: false, error: `Verification failed after ${maxRetries} attempts` };
  }, [address]);

  /**
   * Fund backend wallet using MANUAL USDC transfer (proven v1 approach)
   *
   * This matches the v1 hook's approach which works reliably for both Farcaster and Base App:
   * 1. Get x402 payment info (payTo address, amount)
   * 2. Send USDC directly via sendCallsAsync (Smart Wallet) or writeContractAsync (EOA)
   * 3. Poll getCallsStatus for tx hash (Smart Wallets don't return it immediately)
   * 4. Fallback to balance-based verification if tx hash unavailable
   * 5. Verify payment with relay service
   */
  const fundBackendWallet = useCallback(async (amountUsdc?: number): Promise<boolean> => {
    if (!address || !walletClient) {
      throw new Error("Wallet not connected");
    }

    setProgress((prev) => ({
      ...prev,
      status: "funding",
      currentStep: "Initiating funding...",
    }));

    try {
      const requestedAmount = amountUsdc || 0.10;
      console.log(`[RELAY-V3] fundBackendWallet called with amountUsdc: ${requestedAmount}`);
      console.log(`[RELAY-V3] Using MANUAL USDC transfer (v1 approach - proven for Base App)`);

      // Step 1: Get x402 payment info from relay API
      const fundInfoResponse = await fetch("/api/relay/fund", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          operatorAddress: address,
          chainId: RELAY_CONFIG.chainId,
          amountUsdc: requestedAmount,
        }),
      });

      const fundInfo = await fundInfoResponse.json();
      console.log(`[RELAY-V3] Fund API response:`, fundInfo);

      // If funding succeeded without payment (unlikely but possible)
      if (fundInfo.success) {
        console.log(`[RELAY-V3] Funding succeeded directly`);
        await checkBalance();
        return true;
      }

      // Check if x402 payment is required
      if (fundInfoResponse.status !== 402 && !fundInfo.accepts) {
        throw new Error(fundInfo.error || "Failed to get payment info from relay");
      }

      // Parse x402 response - get payTo address
      const accepts = fundInfo.accepts?.[0];
      const payTo = accepts?.payTo || accepts?.extra?.facilitator;

      if (!payTo || !/^0x[a-fA-F0-9]{40}$/.test(payTo)) {
        console.error(`[RELAY-V3] Invalid payTo address:`, payTo, fundInfo);
        throw new Error("Invalid payment address from relay service");
      }

      console.log(`[RELAY-V3] x402 payment required. PayTo: ${payTo}, Amount: $${requestedAmount}`);

      // Step 2: Check user's USDC balance
      const userBalance = await checkUserUsdcBalance();
      if (userBalance !== null && userBalance < requestedAmount) {
        throw new Error(`Insufficient USDC. Have $${userBalance.toFixed(2)}, need $${requestedAmount.toFixed(2)}`);
      }

      // Step 3: Get original relay balance for comparison (balance is in ETH, not USDC)
      const originalBalanceInfo = await checkBalance();
      const originalBalanceEth = parseFloat(originalBalanceInfo?.balanceEth || "0");

      // Step 4: Send USDC directly via wagmi
      setProgress((prev) => ({
        ...prev,
        currentStep: `Sending $${requestedAmount.toFixed(2)} USDC...`,
      }));

      const amountWei = BigInt(Math.round(requestedAmount * 1_000_000)); // USDC has 6 decimals

      const transferCalldata = encodeFunctionData({
        abi: ERC20_ABI,
        functionName: "transfer",
        args: [payTo as `0x${string}`, amountWei],
      });

      console.log(`[RELAY-V3] Sending ${amountWei} USDC smallest units to ${payTo}`);
      console.log(`[RELAY-V3] Connector: ${connector?.name || 'unknown'}`);

      let actualTxHash: string | undefined;

      // Check if this is a Smart Wallet and if it's deployed
      // Undeployed Smart Wallets may fail simulation on their first transaction
      const walletDeployed = await isSmartWalletDeployed(address);
      console.log(`[RELAY-V3] Smart Wallet deployed: ${walletDeployed}`);
      console.log(`[RELAY-V3] Capabilities — hasAtomicBatch: ${hasAtomicBatch}, loading: ${capabilitiesLoading}`);

      // Skip sendCallsAsync if:
      //   - capabilities are still loading (default safe: assume no EIP-5792 until confirmed), OR
      //   - capabilities resolved and the wallet does NOT support atomic batch.
      // This prevents firing sendCallsAsync on an EOA wallet if the user clicks
      // before wallet_getCapabilities returns.
      const skipSendCalls = capabilitiesLoading || !hasAtomicBatch;
      if (skipSendCalls) {
        console.log(`[RELAY-V3] Wallet does not support EIP-5792 — skipping sendCallsAsync, using writeContractAsync directly.`);
      }

      try {
        // Try Smart Wallet via sendCallsAsync (EIP-5792) - works for Farcaster and Base App
        // Bypassed when capabilities confirm the wallet doesn't support it.
        if (skipSendCalls) throw new Error("Wallet does not support EIP-5792 — skipping to EOA path");
        console.log(`[RELAY-V3] Attempting sendCallsAsync (Smart Wallet)...`);
        console.log(`[RELAY-V3] USDC address: ${RELAY_CONFIG.usdcAddress}`);
        console.log(`[RELAY-V3] Transfer calldata: ${transferCalldata.slice(0, 50)}...`);
        console.log(`[RELAY-V3] Wallet deployed status: ${walletDeployed}`);
        const result = await sendCallsAsync({
          calls: [{
            to: RELAY_CONFIG.usdcAddress,
            data: transferCalldata,
            value: 0n, // Explicit zero ETH value for ERC20 transfer
          }],
          chainId: RELAY_CONFIG.chainId,
          capabilities: {
            // ERC-8021 onchain attribution for Net Library (bc_d7041lf9).
            // optional: true — wallets that don't support dataSuffix will still
            // process the transaction normally.
            dataSuffix: {
              value: NET_LIBRARY_DATA_SUFFIX,
              optional: true,
            },
          },
        });

        // sendCallsAsync returns { id: string, capabilities?: ... } - extract the ID
        const batchId = typeof result === "string" ? result : result.id;
        console.log(`[RELAY-V3] sendCallsAsync submitted, batch ID: ${batchId}`);

        // Poll getCallsStatus for actual tx hash (Smart Wallets don't return it immediately)
        setProgress((prev) => ({
          ...prev,
          currentStep: "Waiting for confirmation...",
        }));

        let pollAttempts = 0;
        const maxPollAttempts = 60;

        while (!actualTxHash && pollAttempts < maxPollAttempts) {
          await new Promise((resolve) => setTimeout(resolve, 1000));
          pollAttempts++;

          try {
            const status = await getCallsStatus(config, { id: batchId });
            console.log(`[RELAY-V3] Poll ${pollAttempts}: status=${status.status}`);

            if (status.status === "success" && status.receipts?.[0]) {
              actualTxHash = status.receipts[0].transactionHash;
              console.log(`[RELAY-V3] Got tx hash from Smart Wallet: ${actualTxHash}`);
            } else if (status.status === "failure") {
              throw new Error("USDC transfer failed on-chain");
            }
          } catch (pollError) {
            if (pollAttempts > 10) {
              const msg = pollError instanceof Error ? pollError.message : String(pollError);
              console.log(`[RELAY-V3] Poll error (${pollAttempts}): ${msg.slice(0, 50)}`);
            }
          }
        }

        // FALLBACK: If we couldn't get tx hash after polling, check balance directly
        if (!actualTxHash) {
          console.warn(`[RELAY-V3] Could not get tx hash after ${maxPollAttempts}s, falling back to balance verification...`);
          setProgress((prev) => ({
            ...prev,
            currentStep: "Verifying via balance check...",
          }));

          let balanceAttempts = 0;
          while (balanceAttempts < 30) {
            await new Promise((resolve) => setTimeout(resolve, 1000));
            balanceAttempts++;

            const newBalanceInfo = await checkBalance();
            const newBalanceEth = parseFloat(newBalanceInfo?.balanceEth || "0");

            if (newBalanceEth > originalBalanceEth + 0.00001) {
              console.log(`[RELAY-V3] ✅ Balance increased! ${originalBalanceEth.toFixed(6)} → ${newBalanceEth.toFixed(6)} ETH`);
              setProgress((prev) => ({
                ...prev,
                status: "idle",
                currentStep: `Funded! Balance: ${newBalanceEth.toFixed(6)} ETH`,
              }));
              return true;
            }
          }

          throw new Error("Funding verification timed out. If USDC was sent, try 'Recover Funds'.");
        }
      } catch (smartWalletError) {
        const errMsg = smartWalletError instanceof Error ? smartWalletError.message : String(smartWalletError);
        console.error(`[RELAY-V3] sendCallsAsync error:`, errMsg);

        // Check for user rejection
        if (errMsg.toLowerCase().includes("user rejected") || errMsg.toLowerCase().includes("user denied")) {
          throw new Error("User cancelled transaction");
        }

        // Check for Farcaster wallet-specific errors
        if (errMsg.toLowerCase().includes("failed to load") || errMsg.toLowerCase().includes("confirmation transaction")) {
          console.error(`[RELAY-V3] Farcaster wallet transaction loading error - may be insufficient USDC balance or network issue`);
          // Try to provide more helpful error message
          const userBalance = await checkUserUsdcBalance();
          if (userBalance < requestedAmount) {
            throw new Error(`Insufficient USDC balance. Have $${userBalance.toFixed(2)}, need $${requestedAmount.toFixed(2)}`);
          }
          // If balance is sufficient, it's likely a wallet/network issue
          throw new Error("Wallet failed to load transaction. Please try again or check your wallet connection.");
        }

        // Check for Smart Wallet simulation failure (common in Base App)
        // This catches the false "insufficient funds" error that's actually a simulation failure
        if (isSimulationFailure(errMsg)) {
          console.error(`[RELAY-V3] Smart Wallet simulation failure detected. Wallet deployed: ${walletDeployed}`);

          // First, verify the user actually has sufficient USDC
          const userBalance = await checkUserUsdcBalance();
          if (userBalance < requestedAmount) {
            throw new Error(`Insufficient USDC balance. Have $${userBalance.toFixed(2)}, need $${requestedAmount.toFixed(2)}`);
          }

          // If balance is sufficient, this is a simulation problem, not a funds problem
          if (!walletDeployed) {
            // Smart Wallet needs to be deployed first
            // The first transaction includes deployment cost which confuses simulation
            console.error(`[RELAY-V3] Undeployed Smart Wallet detected - first tx includes deployment overhead`);
            throw new Error(
              "Your Smart Wallet needs to be activated. " +
              "Please try a smaller amount ($0.10) or activate your wallet by receiving ETH first."
            );
          }

          // Wallet is deployed but simulation still failed
          throw new Error(
            "Transaction simulation failed. This may be a temporary network issue. " +
            "Please wait a moment and try again."
          );
        }

        // Fallback to writeContractAsync for EOA wallets (browser extensions, WalletConnect)
        // This is the common path for browser users with MetaMask, Rainbow, etc.
        console.log(`[RELAY-V3] sendCallsAsync failed (${errMsg.slice(0, 50)}...), trying writeContractAsync (EOA)...`);

        try {
          setProgress((prev) => ({
            ...prev,
            currentStep: "Sending USDC payment...",
          }));

          // writeContractAsync returns the actual tx hash directly (no polling needed!)
          actualTxHash = await writeContractAsync({
            address: RELAY_CONFIG.usdcAddress,
            abi: ERC20_ABI,
            functionName: "transfer",
            args: [payTo as `0x${string}`, amountWei],
            chainId: RELAY_CONFIG.chainId,
          });
          console.log(`[RELAY-V3] writeContractAsync submitted, TX hash: ${actualTxHash}`);
        } catch (eoaError) {
          const eoaErrMsg = eoaError instanceof Error ? eoaError.message : String(eoaError);
          console.error(`[RELAY-V3] Both Smart Wallet and EOA methods failed:`, eoaErrMsg.slice(0, 150));

          // Check if EOA failure is also a simulation failure
          if (isSimulationFailure(eoaErrMsg)) {
            const userBalance = await checkUserUsdcBalance();
            if (userBalance < requestedAmount) {
              throw new Error(`Insufficient USDC balance. Have $${userBalance.toFixed(2)}, need $${requestedAmount.toFixed(2)}`);
            }
            throw new Error(
              "Transaction failed to simulate. Please check your wallet connection and try again."
            );
          }

          throw eoaError;
        }
      }

      // Step 5: Save tx hash to localStorage for recovery
      const pendingPaymentsKey = `net-relay-pending-${address}`;
      try {
        const existing = JSON.parse(localStorage.getItem(pendingPaymentsKey) || "[]");
        existing.push({ txHash: actualTxHash, timestamp: Date.now(), amount: requestedAmount });
        localStorage.setItem(pendingPaymentsKey, JSON.stringify(existing.slice(-10)));
        console.log(`[RELAY-V3] Saved pending payment to localStorage`);
      } catch {
        // Ignore storage errors
      }

      // Step 6: Verify payment with relay
      setProgress((prev) => ({
        ...prev,
        currentStep: "Verifying payment...",
      }));

      // Wait for tx to propagate
      await new Promise((resolve) => setTimeout(resolve, 3000));

      const verifyResult = await verifyPaymentWithRetries(actualTxHash!);

      if (verifyResult.success) {
        // Clear from localStorage
        try {
          const existing = JSON.parse(localStorage.getItem(pendingPaymentsKey) || "[]");
          const filtered = existing.filter((p: { txHash: string }) => p.txHash !== actualTxHash);
          localStorage.setItem(pendingPaymentsKey, JSON.stringify(filtered));
        } catch {
          // Ignore
        }

        await checkBalance();
        setProgress((prev) => ({
          ...prev,
          status: "idle",
          currentStep: `Funded $${requestedAmount.toFixed(2)} USDC!`,
        }));
        return true;
      }

      // Verify failed but tx exists - check balance as final fallback
      console.warn(`[RELAY-V3] Verify failed, checking balance...`);
      let finalAttempts = 0;
      while (finalAttempts < 15) {
        await new Promise((resolve) => setTimeout(resolve, 2000));
        finalAttempts++;

        const finalBalanceInfo = await checkBalance();
        const finalBalanceEth = parseFloat(finalBalanceInfo?.balanceEth || "0");

        if (finalBalanceEth > originalBalanceEth + 0.00001) {
          console.log(`[RELAY-V3] ✅ Balance confirmed increased!`);
          return true;
        }
      }

      throw new Error("Payment sent but verification failed. Use 'Recover Funds' to retry.");
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : String(error);
      console.error(`[RELAY-V3] Funding error:`, errMsg);

      setProgress((prev) => ({
        ...prev,
        status: "error",
        currentStep: errMsg,
      }));

      throw new Error(`Funding failed: ${errMsg}`);
    }
  }, [address, walletClient, config, connector, sendCallsAsync, writeContractAsync, checkBalance, checkUserUsdcBalance, verifyPaymentWithRetries, capabilitiesLoading, hasAtomicBatch]);

  // Note: The old SDK-based code is replaced with the manual approach above
  // These are kept to avoid breaking other parts of the codebase that may use them
  void RelayClient;
  void createWagmiLocalAccount;

  /**
   * Create or refresh relay session
   *
   * IMPORTANT: Uses local API proxy to avoid CORS issues in Farcaster Mini Apps.
   * The flow is:
   * 1. Generate session parameters (expiresAt, nonce)
   * 2. Sign EIP-712 typed data locally using the wallet
   * 3. Submit signature to local proxy -> Net Protocol API
   */
  const ensureSession = useCallback(async (): Promise<string> => {
    if (!address) {
      throw new Error("Wallet not connected");
    }

    // Check if existing session is still valid (with 5 min buffer)
    const now = Math.floor(Date.now() / 1000);
    if (sessionTokenRef.current && sessionExpiresAtRef.current > now + 300) {
      console.log(`[RELAY-V3] Using existing session (expires in ${sessionExpiresAtRef.current - now}s)`);
      return sessionTokenRef.current;
    }

    console.log(`[RELAY-V4] Creating new session via SDK with local proxy...`);

    // Use SDK's createSession but point it to our local proxy URL
    // This keeps the SDK's internal EIP-712 signing logic which is proven to work
    // but routes API calls through our proxy to avoid CORS
    const proxyClient = new RelayClient({
      apiUrl: RELAY_CONFIG.localApiUrl, // Use local proxy instead of direct URL
      chainId: RELAY_CONFIG.chainId,
    });

    // Create wagmi adapter for signing
    const account = createWagmiLocalAccount(walletClient!);

    console.log(`[RELAY-V4] Calling SDK createSession with proxy URL: ${RELAY_CONFIG.localApiUrl}`);
    console.log(`[RELAY-V4] Operator: ${address}, ChainId: ${RELAY_CONFIG.chainId}`);

    try {
      console.log(`[RELAY-V4] About to sign EIP-712 typed data...`);

      // Add timeout for wallet signature - Warpcast wallet can hang indefinitely
      // if their evm-scan-action API is having issues
      const SIGNATURE_TIMEOUT_MS = 60000; // 60 seconds - enough time for user to approve

      const sessionPromise = proxyClient.createSession({
        operatorAddress: address,
        secretKey: RELAY_CONFIG.secretKey,
        account,
        expiresIn: 3600, // 1 hour
      });

      const timeoutPromise = new Promise<never>((_, reject) => {
        setTimeout(() => {
          reject(new Error("WALLET_TIMEOUT"));
        }, SIGNATURE_TIMEOUT_MS);
      });

      const { sessionToken, expiresAt } = await Promise.race([sessionPromise, timeoutPromise]);

      sessionTokenRef.current = sessionToken;
      sessionExpiresAtRef.current = expiresAt;

      console.log(`[RELAY-V4] Session created successfully!`);
      console.log(`[RELAY-V4] Token length: ${sessionToken?.length || 0}, expires: ${new Date(expiresAt * 1000).toISOString()}`);
    } catch (sessionError) {
      const errMsg = sessionError instanceof Error ? sessionError.message : String(sessionError);
      const errStack = sessionError instanceof Error ? sessionError.stack : undefined;
      console.error(`[RELAY-V4] Session creation failed:`, errMsg);
      console.error(`[RELAY-V4] Stack:`, errStack);

      // Check for user rejection
      if (
        errMsg.toLowerCase().includes("user rejected") ||
        errMsg.toLowerCase().includes("user denied") ||
        errMsg.toLowerCase().includes("cancelled")
      ) {
        throw new Error("User cancelled session signature");
      }

      // Check for wallet timeout (Warpcast API issues)
      if (errMsg === "WALLET_TIMEOUT") {
        throw new Error("Wallet signature timed out. The Farcaster wallet may be experiencing issues. Please try again.");
      }

      // Include more context in the error
      throw new Error(`Session failed: ${errMsg}`);
    }

    return sessionTokenRef.current!;
  }, [address, walletClient]);

  /**
   * Main upload function
   */
  const uploadFile = useCallback(
    async (file: File, metadata: RelayUploadMetadata): Promise<RelayUploadResult> => {
      if (!isConnected || !address || !walletClient) {
        return { success: false, error: "Wallet not connected", usedRelay: false };
      }

      // Prevent concurrent uploads - only one upload at a time
      if (uploadInProgressRef.current) {
        console.warn(`[RELAY-V2] Upload already in progress, ignoring new request`);
        return { success: false, error: "Upload already in progress", usedRelay: false };
      }

      // Create new AbortController for this upload
      abortControllerRef.current = new AbortController();
      const signal = abortControllerRef.current.signal;

      // Mark upload as in progress
      uploadInProgressRef.current = true;

      console.log(`[RELAY-V2] Starting upload: ${file.name} (${file.size} bytes)`);

      try {
        // Check if aborted before starting
        if (signal.aborted) {
          throw new Error("Upload cancelled");
        }

        // Step 1: Check balance
        setProgress({
          status: "checking-balance",
          estimatedCostUsdc: 0,
          estimatedCostEth: 0,
          backendWalletBalance: 0,
          backendWalletBalanceEth: 0,
          userUsdcBalance: 0,
          sufficientBalance: false,
          currentStep: "Checking relay balance...",
          totalTransactions: 0,
          completedTransactions: 0,
          currentBatch: 0,
          totalBatches: 0,
          txHashes: [],
          canFallback: true,
        });

        const [balanceInfo, userUsdcBalance] = await Promise.all([
          checkBalance(),
          checkUserUsdcBalance(),
        ]);

        if (!balanceInfo) {
          throw new Error("Failed to check relay balance");
        }

        const balanceEth = parseFloat(balanceInfo.balanceEth);
        const balanceUsdc = balanceEth * liveEthPriceUsd; // Live CoinGecko price

        // Calculate actual cost for THIS file (not SDK's generic threshold)
        // Small files: 2 txs, Chunked: 2 txs, XML (>80KB): N chunks + 2 txs
        let estimatedTransactions = 2;
        if (file.size >= 80000) {
          // Base64 encoding expands size by ~1.37×; each XML chunk holds ~80KB of encoded data
          const base64Size = Math.ceil(file.size * 1.37);
          const numChunks = Math.ceil(base64Size / 80000);
          estimatedTransactions = numChunks + 2; // +2 for xml-metadata + book-metadata txs
        }

        // Calldata-aware cost estimate per transaction on Base L2:
        //   21 000 base gas + ~80KB non-zero calldata × 16 gas/byte ≈ 1 300 000 gas
        //   At ~0.127 gwei basefee → ~0.000165 ETH per data-heavy tx
        // This is ~33× more accurate than the old flat 0.000005 ETH figure.
        const estimatedGasPerTx = 21000 + (80000 * 16); // ~1.3M gas
        const baseFeeGwei = 0.127;
        const estimatedCostEthPerTx = (estimatedGasPerTx * baseFeeGwei) / 1e9;
        const estimatedCostEth = estimatedTransactions * estimatedCostEthPerTx;
        const estimatedCostUsdc = estimatedCostEth * liveEthPriceUsd; // Live price for display

        // Check if ETH balance is sufficient for THIS specific upload
        const actualSufficientBalance = balanceEth >= estimatedCostEth;

        console.log(`[RELAY-V2] Balance check for file:`, {
          fileSize: file.size,
          estimatedTransactions,
          estimatedCostEth: estimatedCostEth.toFixed(8),
          estimatedCostUsdc: estimatedCostUsdc.toFixed(4),
          balanceEth: balanceEth.toFixed(8),
          balanceUsdc: balanceUsdc.toFixed(4),
          sdkSufficientBalance: balanceInfo.sufficientBalance,
          actualSufficientBalance,
        });

        setProgress((prev) => ({
          ...prev,
          backendWalletBalance: balanceUsdc,
          backendWalletBalanceEth: balanceEth,
          userUsdcBalance,
          estimatedCostUsdc,
          estimatedCostEth,
          totalTransactions: estimatedTransactions,
          sufficientBalance: actualSufficientBalance,
        }));

        // Step 2: Fund if needed - use OUR calculation, not SDK's
        if (!actualSufficientBalance) {
          console.log(`[RELAY-V2] Insufficient balance, needs funding`);

          setProgress((prev) => ({
            ...prev,
            status: "needs-funding",
            currentStep: `Insufficient balance (${balanceEth.toFixed(6)} ETH). Please fund your Upload Wallet.`,
          }));

          // Return with needs-funding status - UI will show funding modal
          return {
            success: false,
            error: "NEEDS_FUNDING",
            usedRelay: false,
          };
        }

        // Step 3: Create session
        setProgress((prev) => ({
          ...prev,
          status: "creating-session",
          currentStep: "Awaiting wallet signature...",
        }));

        let sessionToken: string;
        try {
          sessionToken = await ensureSession();
        } catch (sessionErr) {
          const sessionErrMsg = sessionErr instanceof Error ? sessionErr.message : String(sessionErr);
          console.error(`[RELAY-V3] Session creation error:`, sessionErrMsg);
          setProgress((prev) => ({
            ...prev,
            status: "error",
            error: `Session failed: ${sessionErrMsg}`,
            currentStep: "Session creation failed",
          }));
          throw sessionErr;
        }

        // Validate session token
        if (!sessionToken || sessionToken.length < 10) {
          console.error(`[RELAY-V3] Invalid session token:`, sessionToken?.slice(0, 20));
          const invalidTokenErr = "Failed to create upload session. Please try again.";
          setProgress((prev) => ({
            ...prev,
            status: "error",
            error: invalidTokenErr,
            currentStep: "Invalid session token",
          }));
          throw new Error(invalidTokenErr);
        }

        console.log(`[RELAY-V3] Session token obtained (${sessionToken.length} chars)`);

        // Step 3b: Session created - show transition message
        setProgress((prev) => ({
          ...prev,
          currentStep: "Session created! Preparing file...",
        }));

        // Step 4: Prepare file
        setProgress((prev) => ({
          ...prev,
          status: "preparing",
          currentStep: "Preparing file for upload...",
        }));

        const prepared = await prepareFileForUploadLegacy(file, address);

        console.log(`[RELAY-V2] File prepared:`, {
          storageType: prepared.storageType,
          key: prepared.key.slice(0, 20) + "...",
          xmlChunks: prepared.xmlChunks?.length,
          chunksCount: prepared.chunks?.length,
          chunksType: prepared.chunks ? typeof prepared.chunks[0] : 'none',
          fileSize: file.size,
        });

        // Step 5: Build transactions
        const transactions: WriteTransactionConfig[] = [];

        if (prepared.storageType === "xml" && prepared.xmlChunks) {
          // XML storage - multiple chunk transactions
          for (let i = 0; i < prepared.xmlChunks.length; i++) {
            const xmlChunk = prepared.xmlChunks[i];
            transactions.push({
              to: CHUNKED_STORAGE_ADDRESS,
              abi: CHUNKED_STORAGE_ABI,
              functionName: "put",
              args: [xmlChunk.key, "", xmlChunk.compressedChunks],
            });
          }

          // XML metadata transaction
          const xmlChunkKeys = prepared.xmlChunks.map((c) => c.key);
          const xmlMetadata = generateXmlMetadata(xmlChunkKeys, 0, address);
          transactions.push({
            to: STORAGE_CONTRACT_ADDRESS,
            abi: STORAGE_ABI,
            functionName: "put",
            args: [prepared.key, prepared.text, stringToHex(xmlMetadata)],
          });
        } else if (prepared.storageType === "chunked" && prepared.chunks) {
          console.log(`[RELAY-V2] Building chunked storage transaction:`, {
            to: CHUNKED_STORAGE_ADDRESS,
            key: prepared.key,
            text: prepared.text,
            chunksLength: prepared.chunks.length,
            firstChunkPreview: prepared.chunks[0]?.slice?.(0, 50) || 'not a string',
          });
          transactions.push({
            to: CHUNKED_STORAGE_ADDRESS,
            abi: CHUNKED_STORAGE_ABI,
            functionName: "put",
            args: [prepared.key, prepared.text, prepared.chunks],
          });
        } else {
          // Regular storage - use hex-encoded base64 data
          transactions.push({
            to: STORAGE_CONTRACT_ADDRESS,
            abi: STORAGE_ABI,
            functionName: "put",
            args: [prepared.key, prepared.text, prepared.dataHex || stringToHex(String.fromCharCode(...prepared.data))],
          });
        }

        // Book metadata transaction
        const bookMetadata = createBookMetadata(
          metadata.title,
          metadata.author,
          metadata.categories,
          file.name,
          file.size,
          prepared.key,
          address,
          prepared.storageType
        );
        const bookMetadataKey = generateStorageKey(`netlib-meta-${prepared.key}`);
        transactions.push({
          to: STORAGE_CONTRACT_ADDRESS,
          abi: STORAGE_ABI,
          functionName: "put",
          args: [bookMetadataKey, `${metadata.title} by ${metadata.author}`, stringToHex(JSON.stringify(bookMetadata))],
        });

        console.log(`[RELAY-V2] Prepared ${transactions.length} transactions`);

        // Step 6: Batch transactions using SDK
        const batches = batchTransactions(transactions);

        console.log(`[RELAY-V2] Split into ${batches.length} batches`);

        setProgress((prev) => ({
          ...prev,
          status: "submitting",
          totalTransactions: transactions.length,
          totalBatches: batches.length,
          currentStep: `Submitting ${transactions.length} transactions in ${batches.length} batch(es)...`,
        }));

        // Step 7: Submit batches via local proxy (avoids CORS)
        const allHashes: Hash[] = [];
        let completedTxCount = 0;
        let actualOperator: string = address; // Track the actual operator (backend wallet) that writes to chain

        for (let batchIndex = 0; batchIndex < batches.length; batchIndex++) {
          const batch = batches[batchIndex];

          // ── Circuit breaker: verify relay wallet balance before each batch ──
          // Without this, a wallet that runs out mid-upload will keep spending gas
          // on transactions that form an incomplete, unrecoverable file.
          const cbBalance = await checkBalance();
          if (cbBalance) {
            const cbEth = parseFloat(cbBalance.balanceEth || "0");
            const remainingBatches = batches.length - batchIndex;
            // Conservative: each transaction in a remaining batch costs ~0.000165 ETH
            // (21000 base + ~80KB calldata at 16 gas/non-zero byte ≈ 1.3M gas × 0.127 gwei)
            const avgTxsPerBatch = Math.ceil(transactions.length / batches.length);
            const estimatedRemaining = remainingBatches * avgTxsPerBatch * 0.000165;
            const threshold = Math.max(estimatedRemaining, 0.0005);
            if (cbEth < threshold) {
              throw new Error(
                `Upload paused: relay wallet balance too low to complete remaining ${remainingBatches} batch${remainingBatches !== 1 ? "es" : ""}. ` +
                `${batchIndex} of ${batches.length} batches completed. ` +
                `Balance: ${cbEth.toFixed(6)} ETH, needed: ~${threshold.toFixed(6)} ETH. ` +
                `Please add funds and retry.`
              );
            }
          }

          setProgress((prev) => ({
            ...prev,
            currentBatch: batchIndex + 1,
            currentStep: `Submitting batch ${batchIndex + 1}/${batches.length} (${batch.length} txs)...`,
          }));

          console.log(`[RELAY-V3] Submitting batch ${batchIndex + 1}/${batches.length} with ${batch.length} transactions`);

          // Log transaction details for debugging
          batch.forEach((tx, i) => {
            console.log(`[RELAY-V3] Tx ${i}: to=${tx.to}, fn=${tx.functionName}, args[0]=${typeof tx.args?.[0] === 'string' ? tx.args[0].slice(0, 30) + '...' : tx.args?.[0]}`);
          });

          // Use local proxy instead of SDK to avoid CORS
          const submitUrl = `${RELAY_CONFIG.localApiUrl}/api/relay/submit`;
          const submitResponse = await fetch(submitUrl, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              operatorAddress: address,
              chainId: RELAY_CONFIG.chainId,
              secretKey: RELAY_CONFIG.secretKey,
              transactions: batch,
              sessionToken,
            }),
          });

          if (!submitResponse.ok) {
            const errorData = await submitResponse.json().catch(() => ({ error: "Unknown error" }));
            console.error(`[RELAY-V3] Submit error:`, errorData);
            throw new Error(errorData.error || "Failed to submit transactions");
          }

          const result = await submitResponse.json();
          console.log(`[RELAY-V3] Submit response:`, JSON.stringify(result, null, 2));

          // Check for relay error (session expired, invalid, etc.)
          if (result.error) {
            console.error(`[RELAY-V3] Relay error in response:`, result.error);
            throw new Error(result.error);
          }

          // Log detailed transaction results
          console.log(`[RELAY-V3] Transaction results:`, {
            transactionHashes: result.transactionHashes?.length || 0,
            successfulIndexes: result.successfulIndexes?.length || 0,
            failedIndexes: result.failedIndexes?.length || 0,
            backendWallet: result.backendWalletAddress,
          });

          // Capture the actual operator address (backend wallet that writes to chain)
          // This is needed for CDN URL generation and verification
          if (result.backendWalletAddress) {
            actualOperator = result.backendWalletAddress;
            console.log(`[RELAY-V3] Using backend wallet as operator: ${actualOperator}`);
          }

          if (result.transactionHashes) {
            allHashes.push(...result.transactionHashes);
          }
          if (result.successfulIndexes) {
            completedTxCount += result.successfulIndexes.length;
          }

          // Check if ALL transactions failed
          if (result.failedIndexes?.length === batch.length && (!result.successfulIndexes || result.successfulIndexes.length === 0)) {
            console.error(`[RELAY-V3] ALL transactions in batch failed! Backend wallet may be out of funds.`);
            throw new Error("All transactions failed - the relay wallet may be out of funds. Please check your balance and try again.");
          }

          // Handle failures with retry via local proxy
          if (result.failedIndexes && result.failedIndexes.length > 0) {
            console.log(`[RELAY-V3] ${result.failedIndexes.length} failed, retrying...`);

            // Check balance before retrying — low balance is the most common failure
            // cause; retrying into an empty wallet wastes gas without recovering anything.
            const retryBalanceInfo = await checkBalance();
            if (retryBalanceInfo) {
              const retryEth = parseFloat(retryBalanceInfo.balanceEth || "0");
              if (retryEth < 0.0005) {
                throw new Error(
                  `Relay wallet balance too low to retry failed transactions (${retryEth.toFixed(6)} ETH remaining). ` +
                  `Please add funds and retry the upload.`
                );
              }
            }

            // Simple retry - resubmit failed transactions
            const failedTxs = result.failedIndexes.map((i: number) => batch[i]).filter(Boolean);
            if (failedTxs.length > 0) {
              const retryResponse = await fetch(submitUrl, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                  operatorAddress: address,
                  chainId: RELAY_CONFIG.chainId,
                  secretKey: RELAY_CONFIG.secretKey,
                  transactions: failedTxs,
                  sessionToken,
                }),
              });

              if (retryResponse.ok) {
                const retryResult = await retryResponse.json();
                if (retryResult.transactionHashes) {
                  allHashes.push(...retryResult.transactionHashes);
                }
                if (retryResult.successfulIndexes) {
                  completedTxCount += retryResult.successfulIndexes.length;
                }
              }
            }
          }

          setProgress((prev) => ({
            ...prev,
            completedTransactions: completedTxCount,
            txHashes: allHashes,
          }));
        }

        console.log(`[RELAY-V3] All batches submitted, ${allHashes.length} transactions`);

        // Check if ANY transactions were submitted
        if (allHashes.length === 0) {
          console.error(`[RELAY-V3] No transactions were submitted successfully!`);
          setProgress((prev) => ({
            ...prev,
            status: "error",
            error: "No transactions were submitted. The relay may be unavailable.",
            currentStep: "Submit failed - no transactions",
          }));
          return {
            success: false,
            error: "All transactions failed to submit - relay may be unavailable. Please try again.",
            usedRelay: true,
          };
        }

        // Step 8: Wait for confirmations using SDK
        // CRITICAL: This must complete before adding to discovery index
        setProgress((prev) => ({
          ...prev,
          status: "confirming",
          currentStep: `Confirming ${allHashes.length} transactions...`,
        }));

        if (!publicClient) {
          console.error(`[RELAY-V3] No public client available for confirmations!`);
          throw new Error("Failed to verify transactions - wallet client unavailable. Please try again.");
        }

        console.log(`[RELAY-V3] Waiting for ${allHashes.length} transaction confirmations...`);

        // Check each transaction receipt to verify it succeeded (not just mined)
        let confirmedCount = 0;
        let failedCount = 0;
        const failedHashes: string[] = [];

        for (const hash of allHashes) {
          // Check if upload was cancelled
          if (signal.aborted) {
            throw new Error("Upload cancelled");
          }

          try {
            const receipt = await publicClient.waitForTransactionReceipt({
              hash: hash as `0x${string}`,
              confirmations: 1,
              timeout: 60_000, // 60 second timeout per tx
            });

            if (receipt.status === "success") {
              confirmedCount++;
              console.log(`[RELAY-V3] Tx ${hash.slice(0, 10)}... SUCCESS`);
            } else {
              failedCount++;
              failedHashes.push(hash);
              console.error(`[RELAY-V3] Tx ${hash.slice(0, 10)}... REVERTED!`);
            }

            setProgress((prev) => ({
              ...prev,
              completedTransactions: confirmedCount,
              currentStep: `Confirmed ${confirmedCount}/${allHashes.length} transactions...`,
            }));
          } catch (receiptError) {
            failedCount++;
            failedHashes.push(hash);
            console.error(`[RELAY-V3] Tx ${hash.slice(0, 10)}... FAILED to get receipt:`, receiptError);
          }
        }

        console.log(`[RELAY-V3] Transaction results: ${confirmedCount} succeeded, ${failedCount} failed`);

        if (failedCount > 0) {
          console.error(`[RELAY-V3] ${failedCount} transactions REVERTED:`, failedHashes);

          // Calculate how much of the upload completed for better user feedback
          const completionPercent = Math.round((confirmedCount / allHashes.length) * 100);
          const isPartialUpload = confirmedCount > 0 && failedCount > 0;

          // Build a helpful error message based on what happened
          let errorDetail: string;
          let suggestion: string;

          if (confirmedCount === 0) {
            // Nothing uploaded - safe to just retry
            errorDetail = "No content was uploaded.";
            suggestion = "Please check your relay wallet balance and try again.";
          } else if (completionPercent < 50) {
            // Less than half uploaded - recommend fresh retry
            errorDetail = `Only ${completionPercent}% of the upload completed.`;
            suggestion = "We recommend retrying the upload - partial content cannot be recovered.";
          } else {
            // More than half uploaded - partial recovery might be possible
            errorDetail = `${completionPercent}% of the upload completed (${confirmedCount}/${allHashes.length} transactions).`;
            suggestion = "Some content may exist on-chain but is incomplete. Try uploading again - if it detects existing content, it will skip redundant chunks.";
          }

          setProgress((prev) => ({
            ...prev,
            status: "error",
            error: `${errorDetail} ${suggestion}`,
            currentStep: isPartialUpload ? `Partial failure (${completionPercent}% complete)` : "Upload failed",
          }));

          return {
            success: false,
            error: `${failedCount} of ${allHashes.length} transactions reverted. ${errorDetail} ${suggestion}`,
            usedRelay: true,
            partialUpload: isPartialUpload,
            completedTransactions: confirmedCount,
            failedTransactions: failedCount,
          };
        }

        console.log(`[RELAY-V3] All ${allHashes.length} transactions confirmed successfully!`);

        // Step 8b: Verify content is actually on-chain before adding to index
        setProgress((prev) => ({
          ...prev,
          currentStep: "Verifying content on-chain...",
        }));

        // Wait for indexers to catch up - storedon.net needs time to index new content
        // Initial wait of 5 seconds gives the indexer time to process the transaction
        await new Promise((resolve) => setTimeout(resolve, 5000));

        // Verify the main content key exists on-chain via our API proxy (avoids CSP issues in Mini App)
        // IMPORTANT: Use actualOperator (backend wallet) not user address - that's who wrote to chain
        const verifyUrl = `/api/verify-content?key=${encodeURIComponent(prepared.key)}&operator=${encodeURIComponent(actualOperator)}`;
        console.log(`[RELAY-V3] Verifying content via proxy: ${verifyUrl}`);

        // Verify content with retries using exponential backoff
        // Total max wait: 5s initial + 3s + 5s + 8s + 12s + 18s + 25s = ~76 seconds
        // This gives storedon.net's indexer plenty of time to catch up
        let contentVerified = false;
        const verifyDelays = [3000, 5000, 8000, 12000, 18000, 25000]; // Exponential backoff delays
        const maxVerifyAttempts = verifyDelays.length;

        for (let verifyAttempt = 0; verifyAttempt < maxVerifyAttempts; verifyAttempt++) {
          // Check if upload was cancelled
          if (signal.aborted) {
            throw new Error("Upload cancelled");
          }

          try {
            const verifyResponse = await fetch(verifyUrl, { signal });

            if (verifyResponse.ok) {
              const verifyData = await verifyResponse.json().catch(() => null);
              if (verifyData && verifyData.exists) {
                console.log(`[RELAY-V3] Content verified on-chain! (attempt ${verifyAttempt + 1})`);
                contentVerified = true;
                break;
              }
            }

            console.log(`[RELAY-V3] Verification attempt ${verifyAttempt + 1}/${maxVerifyAttempts} failed, waiting ${verifyDelays[verifyAttempt]}ms...`);
            await new Promise((resolve) => setTimeout(resolve, verifyDelays[verifyAttempt]));
          } catch (verifyErr) {
            // If aborted, re-throw to stop the loop
            if (signal.aborted) {
              throw new Error("Upload cancelled");
            }
            console.warn(`[RELAY-V3] Verification fetch failed (attempt ${verifyAttempt + 1}):`, verifyErr);
            await new Promise((resolve) => setTimeout(resolve, verifyDelays[verifyAttempt]));
          }
        }

        if (!contentVerified) {
          // Even if verification fails, the transaction succeeded on-chain
          // Log a warning but don't fail the upload - the content IS there, indexer is just slow
          console.warn(`[RELAY-V3] Content verification timed out after ${maxVerifyAttempts} attempts`);
          console.warn(`[RELAY-V3] Transactions succeeded on-chain - proceeding with index update despite verification timeout`);
          console.warn(`[RELAY-V3] Content key: ${prepared.key}, Operator: ${actualOperator}`);
          // Continue to index update - don't return error
        }

        // Step 9: Update discovery index
        setProgress((prev) => ({
          ...prev,
          status: "updating-index",
          currentStep: "Updating discovery index...",
        }));

        const detectedMediaType =
          detectMediaTypeFromMime(file.type) !== "unknown"
            ? detectMediaTypeFromMime(file.type)
            : detectMediaTypeFromExtension(file.name);

        // IMPORTANT: Two different addresses needed:
        // - actualOperator (backend wallet) = who wrote to blockchain, used for CDN URL generation
        // - address (user's wallet) = who gets credit/attribution for the upload
        const newEntry = createDiscoveryEntry(
          prepared.key,
          bookMetadataKey,
          actualOperator, // Backend wallet for CDN URL generation
          metadata.title,
          metadata.author,
          metadata.categories,
          file.size,
          prepared.storageType,
          metadata.coverUrl,
          {
            publicationYear: metadata.publicationYear,
            publisher: metadata.publisher,
            isbn: metadata.isbn,
            uploaderFid: metadata.uploaderFid,
            uploaderUsername: metadata.uploaderUsername,
            uploaderMemberId: metadata.uploaderMemberId,
            uploaderEnsSubname: metadata.uploaderEnsSubname,
            uploaderStoredUsername: metadata.uploaderStoredUsername, // Social identity
            uploaderAddress: address, // User's wallet for attribution (NOT the relay backend)
            contentHash: metadata.contentHash,
            mediaType: detectedMediaType !== "unknown" ? detectedMediaType : undefined,
            fileName: file.name, // Original filename for correct CDN URL generation
            // IMPORTANT: Pre-compute and store the CDN URL so it's available for display
            // This uses the correct /storage/load/ format that Net Protocol expects
            cdnUrl: getCdnUrl(BASE_CHAIN_ID, actualOperator, prepared.key, prepared.storageType, file.name),
            // Social receipt metadata (for archived social posts)
            isSocialReceipt: metadata.isSocialReceipt,
            socialPlatform: metadata.socialPlatform as "farcaster" | "twitter" | "youtube" | "instagram" | "tiktok" | "reddit" | "bluesky" | "threads" | "linkedin" | undefined,
            originalUrl: metadata.originalUrl,
            socialText: metadata.socialText,
            socialAuthor: metadata.socialAuthor,
            socialTimestamp: metadata.socialTimestamp instanceof Date
              ? metadata.socialTimestamp.toISOString()
              : metadata.socialTimestamp,
            encrypted: metadata.encrypted,
          }
        );

        // ARCHITECTURE NOTE — encrypted flag:
        // The relay path writes content directly to the blockchain via x402 payment transactions
        // and then registers the entry in the discovery index via POST /api/discovery.
        // It does NOT call the /api/v1/library/upload route at all — that route is only used
        // for the legacy HTTP-based upload path.
        // The `encrypted` flag in `newEntry` (set above from metadata.encrypted) is therefore
        // the canonical source of truth: it flows into the discovery index and is read back by
        // the library API (/api/v1/library) and the viewer (MultimediaViewer).
        // No separate KV write to the upload route is needed; the discovery index IS the record.

        // ── Register in discovery index ────────────────────────────────────────
        // IMPORTANT: This happens BEFORE setting status:"complete" so the user
        // sees "Registering in library..." and stays on the screen until it's done.
        // keepalive:true ensures the fetch survives even if the user backgrounds
        // the app immediately after this step starts.
        setProgress((prev) => ({ ...prev, currentStep: "Registering in library..." }));

        let discoveryUpdated = false;
        const maxRetries = 3;
        for (let attempt = 1; attempt <= maxRetries; attempt++) {
          try {
            // Include fid and address at top level so authenticateCaller can identify
            // the uploader without requiring a Bearer token
            const entryWithAuth = {
              ...newEntry,
              fid: metadata.uploaderFid,
              address: address, // user's wallet address
            };
            const entryJson = JSON.stringify(entryWithAuth);
            const resp = await fetch("/api/discovery", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: entryJson,
              // keepalive keeps the request alive even if the tab is backgrounded
              // or the component unmounts — critical for mobile where the OS may
              // suspend the browser before this fetch completes
              keepalive: true,
            });
            if (resp.ok) {
              discoveryUpdated = true;
              console.log(`[RELAY-V2] Discovery index updated successfully`);
              break;
            }
            console.warn(`[RELAY-V2] Discovery update attempt ${attempt}/${maxRetries} failed: ${resp.status}`);
          } catch (err) {
            console.warn(`[RELAY-V2] Discovery update attempt ${attempt}/${maxRetries} error:`, err);
          }
          if (attempt < maxRetries) {
            await new Promise(r => setTimeout(r, 500 * attempt));
          }
        }

        if (!discoveryUpdated) {
          console.error("[RELAY-V2] Failed to update discovery index after all retries - content uploaded but not discoverable");
        }

        // Update leaderboard (non-critical, single attempt, keepalive for mobile)
        try {
          await fetch("/api/leaderboard", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ entry: newEntry }),
            keepalive: true,
          });
        } catch {
          console.error("[RELAY-V2] Failed to update leaderboard");
        }

        // Resolve the definitive operator (= relay backend wallet that wrote to chain).
        // Priority: relay response > balance-check response > env fallback.
        // We must NEVER fall back to the user's address: the CDN URL would point to the
        // wrong address and return nothing, making the uploaded content unreachable.
        if (actualOperator === address) {
          // No backendWalletAddress was returned by the relay — try balance endpoint as fallback
          const fallbackBalance = await checkBalance();
          if (fallbackBalance?.backendWalletAddress) {
            actualOperator = fallbackBalance.backendWalletAddress;
            console.log(`[RELAY-V3] Resolved operator from balance check: ${actualOperator}`);
          } else {
            // Hard failure: without the correct operator address the CDN URL will be wrong.
            // Spending gas on a file that can't be accessed is worse than surfacing the error.
            throw new Error(
              "Cannot determine relay backend wallet address for CDN URL. " +
              "The upload transactions were submitted but the file may not be accessible. " +
              "Please contact support with your transaction hashes."
            );
          }
        }

        // Success! Calculate actual cost based on transactions submitted
        // Pass filename to generate correct /storage/load/ URL format
        // IMPORTANT: Use actualOperator (backend wallet) not user address - that's who wrote to chain
        const cdnUrl = getCdnUrl(BASE_CHAIN_ID, actualOperator, prepared.key, prepared.storageType, file.name);
        const actualTxCount = allHashes.length;
        // Calldata-aware post-upload cost: ~1.3M gas × 0.127 gwei basefee per data tx
        const actualCostEth = actualTxCount * ((21000 + 80000 * 16) * 0.127 / 1e9);
        const actualCostUsdc = actualCostEth * liveEthPriceUsd;

        // Build status message - include warning if discovery failed
        const statusMessage = discoveryUpdated
          ? `Upload complete! Cost: $${actualCostUsdc.toFixed(4)}`
          : `Upload complete but not indexed. Use "Refresh Index" to make it visible.`;

        setProgress((prev) => ({
          ...prev,
          status: "complete",
          cdnUrl,
          contentKey: prepared.key,
          actualCostEth,
          actualCostUsdc,
          currentStep: statusMessage,
        }));

        console.log(`[RELAY-V2] Upload complete! CDN URL: ${cdnUrl}, Cost: ${actualCostEth.toFixed(6)} ETH ($${actualCostUsdc.toFixed(4)}), Discoverable: ${discoveryUpdated}`);

        return {
          success: true,
          cdnUrl,
          contentKey: prepared.key,
          operator: actualOperator, // Backend wallet that wrote to chain (for CDN URL generation)
          usedRelay: true,
          warning: discoveryUpdated ? undefined : "Content uploaded but may not appear in browse tab. Try refreshing.",
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : "Upload failed";
        console.error("[RELAY-V2] Upload error:", errorMessage);

        // Check if aborted
        if (signal.aborted || errorMessage.includes("Upload cancelled")) {
          setProgress((prev) => ({
            ...prev,
            status: "idle",
            error: "Upload cancelled",
            currentStep: "",
          }));

          return {
            success: false,
            error: "Upload cancelled",
            usedRelay: false,
          };
        }

        // Check if user cancelled
        if (
          errorMessage.toLowerCase().includes("user rejected") ||
          errorMessage.toLowerCase().includes("user denied") ||
          errorMessage.toLowerCase().includes("cancelled")
        ) {
          setProgress((prev) => ({
            ...prev,
            status: "idle",
            error: "Cancelled by user",
            currentStep: "",
          }));

          return {
            success: false,
            error: "USER_CANCELLED",
            usedRelay: false,
          };
        }

        setProgress((prev) => ({
          ...prev,
          status: "error",
          error: errorMessage,
          currentStep: "Error occurred",
        }));

        return {
          success: false,
          error: errorMessage,
          usedRelay: true,
        };
      } finally {
        // Always clear in-progress flag when upload completes (success or failure)
        uploadInProgressRef.current = false;
        abortControllerRef.current = null;
      }
    },
    [
      address,
      isConnected,
      walletClient,
      publicClient,
      checkBalance,
      checkUserUsdcBalance,
      ensureSession,
      liveEthPriceUsd,
    ]
  );

  /**
   * Reset progress state
   */
  const reset = useCallback(() => {
    setProgress({
      status: "idle",
      estimatedCostUsdc: 0,
      estimatedCostEth: 0,
      backendWalletBalance: 0,
      backendWalletBalanceEth: 0,
      userUsdcBalance: 0,
      sufficientBalance: false,
      currentStep: "",
      totalTransactions: 0,
      completedTransactions: 0,
      currentBatch: 0,
      totalBatches: 0,
      txHashes: [],
      canFallback: true,
    });
  }, []);

  /**
   * Cancel an in-progress upload
   * Note: This will NOT roll back any transactions that have already been submitted
   */
  const cancelUpload = useCallback(() => {
    if (abortControllerRef.current) {
      console.log(`[RELAY-V2] Cancelling upload...`);
      abortControllerRef.current.abort();
      abortControllerRef.current = null;
    }
    uploadInProgressRef.current = false;
  }, []);

  /**
   * Estimate upload cost (matches v1 interface for upload-tab.tsx)
   */
  const estimateUploadCost = useCallback(
    async (
      file: File
    ): Promise<{
      estimatedCostUsdc: number;
      estimatedCostEth: number;
      totalTransactions: number;
      balanceInfo: {
        balanceUsdc: number;
        balanceEth: number;
        backendWalletAddress: Address;
        sufficient: boolean;
        shortfallUsdc: number;
        recommendedFundingUsdc: number;
        lowBalance: boolean;
      } | null;
      userUsdcBalance: number;
      canProceed: boolean;
      lowBalance: boolean;
      needsFunding: boolean;
    }> => {
      if (!address) {
        return {
          estimatedCostUsdc: 0,
          estimatedCostEth: 0,
          totalTransactions: 0,
          balanceInfo: null,
          userUsdcBalance: 0,
          canProceed: false,
          lowBalance: false,
          needsFunding: false,
        };
      }

      // Estimate transactions based on file size
      // Small files: 2 txs (content + metadata)
      // Chunked: 2 txs (chunked content + metadata)
      // XML: N+2 txs (N chunks + xml metadata + book metadata)
      let totalTransactions = 2;
      if (file.size >= 80000) {
        // Base64 encoding expands size by ~1.37×; each XML chunk holds ~80KB of encoded data
        const base64Size = Math.ceil(file.size * 1.37);
        const numChunks = Math.ceil(base64Size / 80000);
        totalTransactions = numChunks + 2; // +2 for xml-metadata + book-metadata txs
      }

      // Calldata-aware cost estimate per transaction on Base L2:
      //   21 000 base gas + ~80KB non-zero calldata × 16 gas/byte ≈ 1 300 000 gas
      //   At ~0.127 gwei basefee → ~0.000165 ETH per data-heavy tx
      const estimatedGasPerTx = 21000 + (80000 * 16); // ~1.3M gas
      const baseFeeGwei = 0.127;
      const estimatedCostEthPerTx = (estimatedGasPerTx * baseFeeGwei) / 1e9;
      const estimatedCostEth = totalTransactions * estimatedCostEthPerTx;
      const estimatedCostUsdc = estimatedCostEth * liveEthPriceUsd; // Live price for display

      // Check backend wallet balance (returns ETH balance)
      const balanceResult = await checkBalance();
      const userUsdcBalance = await checkUserUsdcBalance();

      if (!balanceResult) {
        return {
          estimatedCostUsdc,
          estimatedCostEth,
          totalTransactions,
          balanceInfo: null,
          userUsdcBalance,
          canProceed: false,
          lowBalance: false,
          needsFunding: userUsdcBalance >= 1,
        };
      }

      const balanceEth = parseFloat(balanceResult.balanceEth) || 0;
      const balanceUsdc = balanceEth * liveEthPriceUsd; // Live CoinGecko price

      console.log(`[RELAY-V2] estimateUploadCost balance check:`, {
        rawBalanceEth: balanceResult.balanceEth,
        parsedBalanceEth: balanceEth,
        balanceUsdc,
        estimatedCostEth,
        liveEthPriceUsd,
      });

      // Compare ETH balance against ETH cost (relay wallet holds ETH, not USDC)
      const sufficient = balanceEth >= estimatedCostEth;
      const shortfallUsdc = sufficient ? 0 : Math.max(0, estimatedCostUsdc - balanceUsdc);
      const lowBalance = balanceEth < 0.00003; // ~$0.10 worth of ETH minimum

      return {
        estimatedCostUsdc,
        estimatedCostEth,
        totalTransactions,
        balanceInfo: {
          balanceUsdc,
          balanceEth,
          backendWalletAddress: balanceResult.backendWalletAddress,
          sufficient,
          shortfallUsdc,
          recommendedFundingUsdc: 5, // Recommend $5 for multiple uploads
          lowBalance,
        },
        userUsdcBalance,
        canProceed: sufficient,
        lowBalance,
        needsFunding: !sufficient && userUsdcBalance >= shortfallUsdc,
      };
    },
    [address, checkBalance, checkUserUsdcBalance, liveEthPriceUsd]
  );

  /**
   * Get relay balance (matches v1 interface for upload-tab.tsx)
   * Uses $0.10 as minimum balance threshold per Aspyn
   */
  const getRelayBalance = useCallback(async () => {
    if (!address) return null;

    const balanceResult = await checkBalance();
    if (!balanceResult) return null;

    const balanceEth = parseFloat(balanceResult.balanceEth);
    // Live ETH price from CoinGecko
    const balanceUsdc = balanceEth * liveEthPriceUsd;
    // Minimum balance is ~$0.10 worth of ETH
    const sufficient = balanceEth >= 0.00003;

    return {
      balanceUsdc,
      backendWalletAddress: balanceResult.backendWalletAddress,
      sufficient,
      shortfallUsdc: 0,
      recommendedFundingUsdc: 5,
      lowBalance: balanceEth < 0.00003, // ~$0.10 worth of ETH
    };
  }, [address, checkBalance, liveEthPriceUsd]);

  /**
   * Fund wallet (matches v1 interface for add-funds-modal.tsx)
   * @param amountUsdc - Amount in USDC to fund
   */
  const fundWallet = useCallback(
    async (amountUsdc: number): Promise<boolean> => {
      console.log(`[RELAY-V3] fundWallet called with $${amountUsdc}`);

      if (!address || !walletClient) {
        throw new Error("Wallet not connected");
      }

      if (amountUsdc < 0.1) {
        throw new Error("Minimum funding amount is $0.10");
      }

      try {
        // Pass the actual amount to fundBackendWallet
        await fundBackendWallet(amountUsdc);
        return true;
      } catch (error) {
        console.error("[RELAY-V3] fundWallet error:", error);
        throw error;
      }
    },
    [address, walletClient, fundBackendWallet]
  );

  /**
   * Fast recovery: Try to verify pending payments stored in localStorage
   * This is faster than blockchain scanning and catches most recovery cases
   */
  const recoverPendingPayments = useCallback(async (): Promise<{
    recovered: number;
    total: number;
  }> => {
    if (!address) {
      return { recovered: 0, total: 0 };
    }

    const pendingPaymentsKey = `net-relay-pending-${address}`;
    let pending: Array<{ txHash: string; timestamp: number; amount: number }>;

    try {
      pending = JSON.parse(localStorage.getItem(pendingPaymentsKey) || "[]");
    } catch {
      return { recovered: 0, total: 0 };
    }

    if (pending.length === 0) {
      return { recovered: 0, total: 0 };
    }

    console.log(`[RELAY-V3] Found ${pending.length} pending payments in localStorage`);

    let recovered = 0;
    const stillPending: typeof pending = [];

    for (const payment of pending) {
      // Skip payments older than 1 hour (likely already processed or invalid)
      if (Date.now() - payment.timestamp > 60 * 60 * 1000) {
        console.log(`[RELAY-V3] Skipping old payment: ${payment.txHash.slice(0, 20)}...`);
        continue;
      }

      console.log(`[RELAY-V3] Attempting to verify: ${payment.txHash.slice(0, 20)}...`);

      const result = await verifyPaymentWithRetries(payment.txHash, 3, 1500);

      if (result.success) {
        console.log(`[RELAY-V3] ✅ Recovered pending payment!`);
        recovered++;
      } else {
        // Keep it for future recovery attempts
        stillPending.push(payment);
      }
    }

    // Update localStorage with remaining pending payments
    localStorage.setItem(pendingPaymentsKey, JSON.stringify(stillPending));

    if (recovered > 0) {
      await checkBalance();
    }

    return { recovered, total: pending.length };
  }, [address, verifyPaymentWithRetries, checkBalance]);

  /**
   * Recover unverified payments by scanning blockchain for USDC transfers to facilitator
   * and attempting to verify each one.
   *
   * This helps users recover funds that were paid but never verified due to:
   * - Network errors during verify
   * - User closing browser/modal before verify completed
   * - App crashes
   *
   * First tries fast recovery from localStorage, then falls back to blockchain scan.
   *
   * @returns Object with recovered count and total found, or null if error
   */
  const recoverUnverifiedPayments = useCallback(async (): Promise<{
    recovered: number;
    total: number;
  } | null> => {
    if (!address) {
      console.log("[RELAY-V3] Cannot recover: no wallet connected");
      return null;
    }

    console.log(`[RELAY-V3] Starting payment recovery for ${address}`);

    // First, try fast recovery from localStorage
    const localResult = await recoverPendingPayments();
    if (localResult.recovered > 0) {
      console.log(`[RELAY-V3] Fast recovery found ${localResult.recovered} payments!`);
      return localResult;
    }

    try {
      // Call our API endpoint that scans for unverified payments
      const response = await fetch("/api/relay/recover", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          operatorAddress: address,
          chainId: RELAY_CONFIG.chainId,
        }),
      });

      if (!response.ok) {
        const errorText = await response.text();
        console.error("[RELAY-V3] Recovery API error:", errorText);
        return null;
      }

      const result = await response.json();
      console.log("[RELAY-V3] Recovery result:", result);

      // Refresh balance if any payments were recovered
      if (result.recovered > 0) {
        await checkBalance();
      }

      return {
        recovered: result.recovered || 0,
        total: result.total || 0,
      };
    } catch (error) {
      console.error("[RELAY-V3] Recovery error:", error);
      return null;
    }
  }, [address, checkBalance, recoverPendingPayments]);

  return {
    // State
    progress,
    isFarcasterMode,
    isRelayAvailable: true, // SDK is always available

    // Actions (matching v1 interface)
    uploadFile,
    fundWallet,
    reset,
    estimateUploadCost,
    getRelayBalance,

    // v3 additions
    recoverUnverifiedPayments,
    recoverPendingPayments, // Fast recovery from localStorage

    // Internal (not exposed in v1 but useful)
    fundBackendWallet,
    checkBalance,

    // Utilities
    checkUserUsdcBalance,

    // Live ETH price from CoinGecko
    liveEthPriceUsd,

    // Account info
    isConnected,
    address,

    // Upload control (new)
    cancelUpload,
    isUploading: uploadInProgressRef.current,
  };
}
src/hooks/use-reviews.ts
"use client";

import { useState, useEffect, useCallback } from "react";

export interface BookReview {
  id: string;
  contentKey: string;
  reviewerAddress: string;
  reviewerFid?: number;
  reviewerUsername?: string;
  reviewerPfpUrl?: string;
  rating: number;
  reviewText?: string;
  createdAt: number;
  helpful: number;
}

export interface BookRatingSummary {
  contentKey: string;
  averageRating: number;
  totalReviews: number;
  ratingDistribution: { [key: number]: number };
}

export function useReviews(contentKey?: string) {
  const [reviews, setReviews] = useState<BookReview[]>([]);
  const [summary, setSummary] = useState<BookRatingSummary | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Fetch reviews for a specific book
  const fetchReviews = useCallback(async () => {
    if (!contentKey) {
      setReviews([]);
      setSummary(null);
      setIsLoading(false);
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(`/api/reviews?contentKey=${encodeURIComponent(contentKey)}`);
      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to fetch reviews");
      }

      setReviews(data.reviews || []);
      setSummary(data.summary || null);
    } catch (err) {
      console.error("Fetch reviews error:", err);
      setError(err instanceof Error ? err.message : "Failed to fetch reviews");
    } finally {
      setIsLoading(false);
    }
  }, [contentKey]);

  useEffect(() => {
    fetchReviews();
  }, [fetchReviews]);

  // Submit a review
  const submitReview = useCallback(
    async (params: {
      reviewerAddress: string;
      reviewerFid?: number;
      reviewerUsername?: string;
      rating: number;
      reviewText?: string;
    }) => {
      if (!contentKey) return { success: false, error: "No content key" };

      try {
        const response = await fetch("/api/reviews", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            action: "submit",
            contentKey,
            ...params,
          }),
        });

        const data = await response.json();

        if (!response.ok) {
          throw new Error(data.error || "Failed to submit review");
        }

        // Refresh reviews to get the updated list
        await fetchReviews();

        return { success: true, summary: data.summary };
      } catch (err) {
        console.error("Submit review error:", err);
        return {
          success: false,
          error: err instanceof Error ? err.message : "Failed to submit review",
        };
      }
    },
    [contentKey, fetchReviews]
  );

  // Mark a review as helpful
  const markHelpful = useCallback(async (reviewId: string) => {
    try {
      const response = await fetch("/api/reviews", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          action: "helpful",
          reviewId,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to mark helpful");
      }

      // Update local state
      setReviews((prev) =>
        prev.map((r) => (r.id === reviewId ? { ...r, helpful: data.helpful } : r))
      );

      return { success: true, helpful: data.helpful };
    } catch (err) {
      console.error("Mark helpful error:", err);
      return {
        success: false,
        error: err instanceof Error ? err.message : "Failed to mark helpful",
      };
    }
  }, []);

  // Check if user has already reviewed
  const hasUserReviewed = useCallback(
    (userAddress: string) => {
      if (!userAddress) return false;
      return reviews.some(
        (r) => r.reviewerAddress && r.reviewerAddress.toLowerCase() === userAddress.toLowerCase()
      );
    },
    [reviews]
  );

  // Get user's review
  const getUserReview = useCallback(
    (userAddress: string) => {
      if (!userAddress) return undefined;
      return reviews.find(
        (r) => r.reviewerAddress && r.reviewerAddress.toLowerCase() === userAddress.toLowerCase()
      );
    },
    [reviews]
  );

  return {
    reviews,
    summary,
    isLoading,
    error,
    refresh: fetchReviews,
    submitReview,
    markHelpful,
    hasUserReviewed,
    getUserReview,
  };
}
src/hooks/use-search.ts
"use client";

import { useState, useCallback } from "react";

interface SearchResult {
  contentKey: string;
  metadataKey: string;
  operator: string;
  title: string;
  author: string;
  categories: string[];
  fileSize: number;
  storageType: string;
  coverUrl?: string;
  timestamp: number;
}

export function useSearch() {
  const [results, setResults] = useState<SearchResult[]>([]);
  const [isSearching, setIsSearching] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [query, setQuery] = useState("");

  const search = useCallback(async (searchQuery: string, options?: { category?: string; author?: string }) => {
    if (!searchQuery.trim() && !options?.category && !options?.author) {
      setResults([]);
      return;
    }

    setIsSearching(true);
    setError(null);
    setQuery(searchQuery);

    try {
      const params = new URLSearchParams();
      if (searchQuery) params.set("q", searchQuery);
      if (options?.category) params.set("category", options.category);
      if (options?.author) params.set("author", options.author);

      const response = await fetch(`/api/search?${params}`);

      if (!response.ok) {
        throw new Error("Search failed");
      }

      const data = await response.json();
      setResults(data.results || []);
    } catch (err) {
      console.error("[useSearch] Error:", err);
      setError(err instanceof Error ? err.message : "Search failed");
      setResults([]);
    } finally {
      setIsSearching(false);
    }
  }, []);

  const clearSearch = useCallback(() => {
    setResults([]);
    setQuery("");
    setError(null);
  }, []);

  return {
    search,
    clearSearch,
    results,
    isSearching,
    error,
    query,
  };
}
src/hooks/use-sponsored-transaction.ts
"use client";

import { useSendCalls, useCallsStatus } from "wagmi/experimental";
import { encodeFunctionData, type Address, type Abi } from "viem";
import { useCallback, useEffect, useState } from "react";
import { base } from "viem/chains";

// Paymaster URL from CDP - enables gas sponsorship for Base App users
// eslint-disable-next-line @neynar/no-process-env
const PAYMASTER_URL = process.env.NEXT_PUBLIC_PAYMASTER_URL;

interface UseSponsoredTransactionOptions {
  onSuccess?: (txHash: string) => void;
  onError?: (error: Error) => void;
}

interface ContractCall {
  address: Address;
  abi: Abi;
  functionName: string;
  args: unknown[];
  value?: bigint;
}

/**
 * Hook for sending sponsored transactions on Base using CDP Paymaster.
 *
 * This hook uses the wallet_sendCalls method with paymasterService capability,
 * which allows gas fees to be sponsored by the app's CDP builder credit.
 *
 * Only works with Coinbase Smart Wallet (Base App mode).
 * Falls back to regular transactions if paymaster is not configured.
 */
export function useSponsoredTransaction(options?: UseSponsoredTransactionOptions) {
  const { sendCalls, data: callsId, isPending, error } = useSendCalls();
  const [txHash, setTxHash] = useState<string | null>(null);

  // Get the calls ID as a string (it comes back as an object with id property)
  const callsIdString = typeof callsId === 'string' ? callsId : callsId?.id;

  // Poll for transaction status once we have a callsId
  const { data: callsStatus } = useCallsStatus({
    id: callsIdString as string,
    query: {
      enabled: !!callsIdString,
      refetchInterval: (data) => {
        // Stop polling once we have a receipt
        if (data.state.data?.status === "success") return false;
        return 1000; // Poll every second
      },
    },
  });

  // Handle success - extract transaction hash from receipts
  useEffect(() => {
    if (callsStatus?.status === "success" && callsStatus.receipts?.[0]?.transactionHash) {
      const hash = callsStatus.receipts[0].transactionHash;
      setTxHash(hash);
      options?.onSuccess?.(hash);
    }
  }, [callsStatus, options]);

  // Handle errors
  useEffect(() => {
    if (error) {
      options?.onError?.(error);
    }
  }, [error, options]);

  const sendSponsoredTransaction = useCallback(
    async (call: ContractCall) => {
      // Encode the contract call
      const data = encodeFunctionData({
        abi: call.abi,
        functionName: call.functionName,
        args: call.args,
      });

      // Build the calls array
      const calls = [
        {
          to: call.address,
          data,
          value: call.value ?? BigInt(0),
        },
      ];

      // Send with paymaster capability if configured
      const capabilities = PAYMASTER_URL
        ? {
            paymasterService: {
              url: PAYMASTER_URL,
            },
          }
        : undefined;

      try {
        await sendCalls({
          calls,
          chainId: base.id,
          capabilities,
        });
      } catch (err) {
        console.error("[useSponsoredTransaction] Error:", err);
        throw err;
      }
    },
    [sendCalls]
  );

  const reset = useCallback(() => {
    setTxHash(null);
  }, []);

  return {
    sendSponsoredTransaction,
    txHash,
    callsId: callsIdString,
    callsStatus,
    isPending,
    isConfirming: callsStatus?.status === "pending",
    isConfirmed: callsStatus?.status === "success",
    error,
    reset,
    // Whether gas sponsorship is enabled
    isSponsored: !!PAYMASTER_URL,
  };
}
src/hooks/use-stacks.ts
"use client";

import { useState, useEffect, useCallback, useMemo } from "react";
import { useAccount } from "wagmi";
import type { Stack, StackItem, CreateStackRequest } from "@/features/app/types";
import { useMembershipStatus } from "@/hooks/use-membership-status";

interface UseStacksOptions {
  owner?: string; // Filter by owner (single address)
  owners?: string[]; // Filter by multiple owners (for cross-platform identity)
  popular?: boolean; // Get popular stacks (backward compat, same as sortBy="upvotes")
  sortBy?: "upvotes" | "recent" | "items"; // Sort option
  limit?: number; // Limit results (legacy)
  page?: number; // Pagination: page number (1-indexed)
  pageSize?: number; // Pagination: items per page
  enabled?: boolean; // Enable/disable fetching
}

interface UseStacksReturn {
  stacks: Stack[];
  isLoading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
  createStack: (data: CreateStackRequest) => Promise<Stack | null>;
  deleteStack: (stackId: string, stackOwner?: string) => Promise<boolean>;
  updateStack: (stackId: string, name: string, description?: string) => Promise<Stack | null>;
  // Pagination info
  pagination: {
    page: number;
    pageSize: number;
    total: number;
    totalPages: number;
  } | null;
}

export function useStacks(options: UseStacksOptions = {}): UseStacksReturn {
  const { owner, owners, popular = false, sortBy, limit, page, pageSize, enabled = true } = options;
  const { address } = useAccount();
  const [stacks, setStacks] = useState<Stack[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [pagination, setPagination] = useState<{
    page: number;
    pageSize: number;
    total: number;
    totalPages: number;
  } | null>(null);

  const fetchStacks = useCallback(async () => {
    if (!enabled) return;

    setIsLoading(true);
    setError(null);

    try {
      // If multiple owners, fetch stacks for each and combine
      if (owners && owners.length > 0) {
        const allStacks: Stack[] = [];
        const seenIds = new Set<string>();

        for (const ownerAddr of owners) {
          const params = new URLSearchParams();
          params.set("owner", ownerAddr);
          if (sortBy) params.set("sortBy", sortBy);
          if (limit) params.set("limit", limit.toString());

          const response = await fetch(`/api/stacks?${params.toString()}`);
          const data = await response.json();

          if (data.success && data.stacks) {
            for (const stack of data.stacks) {
              // Dedupe by stack ID (same stack won't appear twice)
              if (!seenIds.has(stack.id)) {
                seenIds.add(stack.id);
                allStacks.push(stack);
              }
            }
          }
        }

        // Sort combined results by creation date (newest first)
        allStacks.sort((a, b) => b.createdAt - a.createdAt);
        setStacks(allStacks);
        setIsLoading(false);
        return;
      }

      // Single owner or no owner filter
      const params = new URLSearchParams();
      if (owner) params.set("owner", owner);
      if (popular) params.set("popular", "true");
      if (sortBy) params.set("sortBy", sortBy);
      if (limit) params.set("limit", limit.toString());
      if (page) params.set("page", page.toString());
      if (pageSize) params.set("pageSize", pageSize.toString());

      const response = await fetch(`/api/stacks?${params.toString()}`);
      const data = await response.json();

      if (data.success) {
        setStacks(data.stacks || []);
        // Set pagination info if available
        if (data.totalPages !== undefined) {
          setPagination({
            page: data.page || 1,
            pageSize: data.pageSize || 10,
            total: data.total || 0,
            totalPages: data.totalPages || 1,
          });
        } else {
          setPagination(null);
        }
      } else {
        setError(data.error || "Failed to fetch stacks");
      }
    } catch (err) {
      console.error("[useStacks] Fetch error:", err);
      setError("Failed to load stacks");
    } finally {
      setIsLoading(false);
    }
  }, [owner, owners, popular, sortBy, limit, page, pageSize, enabled]);

  useEffect(() => {
    fetchStacks();
  }, [fetchStacks]);

  const createStack = useCallback(async (data: CreateStackRequest): Promise<Stack | null> => {
    if (!address) {
      setError("Wallet not connected");
      return null;
    }

    try {
      const response = await fetch("/api/stacks", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          name: data.name,
          description: data.description,
          owner: address,
          ownerFid: data.ownerFid,
          ownerUsername: data.ownerUsername,
          ownerPfpUrl: data.ownerPfpUrl,
          txHash: data.txHash,
        }),
      });

      const result = await response.json();

      if (result.success) {
        // Add to local state
        setStacks(prev => [result.stack, ...prev]);
        return result.stack;
      } else {
        setError(result.error || "Failed to create stack");
        return null;
      }
    } catch (err) {
      console.error("[useStacks] Create error:", err);
      setError("Failed to create stack");
      return null;
    }
  }, [address]);

  const deleteStack = useCallback(async (stackId: string, stackOwner?: string): Promise<boolean> => {
    // Use provided stackOwner (for cross-address linked accounts) or fall back to connected address
    const ownerToUse = stackOwner || address;
    if (!ownerToUse) {
      setError("Wallet not connected");
      return false;
    }

    try {
      const params = new URLSearchParams({
        id: stackId,
        owner: ownerToUse,
      });

      const response = await fetch(`/api/stacks?${params.toString()}`, {
        method: "DELETE",
      });

      const result = await response.json();

      if (result.success) {
        // Remove from local state
        setStacks(prev => prev.filter(s => s.id !== stackId));
        return true;
      } else {
        setError(result.error || "Failed to delete stack");
        return false;
      }
    } catch (err) {
      console.error("[useStacks] Delete error:", err);
      setError("Failed to delete stack");
      return false;
    }
  }, [address]);

  const updateStack = useCallback(async (stackId: string, name: string, description?: string): Promise<Stack | null> => {
    if (!address) {
      setError("Wallet not connected");
      return null;
    }

    try {
      const response = await fetch("/api/stacks", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          stackId,
          action: "update-metadata",
          owner: address,
          name,
          description,
        }),
      });

      const result = await response.json();

      if (result.success) {
        // Update local state
        setStacks(prev => prev.map(s => s.id === stackId ? result.stack : s));
        return result.stack;
      } else {
        setError(result.error || "Failed to update stack");
        return null;
      }
    } catch (err) {
      console.error("[useStacks] Update error:", err);
      setError("Failed to update stack");
      return null;
    }
  }, [address]);

  return {
    stacks,
    isLoading,
    error,
    refresh: fetchStacks,
    createStack,
    deleteStack,
    updateStack,
    pagination,
  };
}

// Type for items with previous stacks info
type ItemWithPreviousStacks = {
  contentKey: string;
  title?: string;
  previousStacks: Array<{ id: string; name: string }>;
};

// Hook for a single stack with its items
interface UseStackReturn {
  stack: Stack | null;
  items: StackItem[];
  isLoading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
  addItem: (contentKey: string) => Promise<boolean>;
  removeItem: (contentKey: string) => Promise<boolean>;
  unlockStack: (txHash: string) => Promise<boolean>;
  reorderItems: (itemOrder: string[]) => Promise<boolean>;
  updateMetadata: (name: string, description?: string) => Promise<boolean>;
  setPrivacy: (isPrivate: boolean) => Promise<{
    success: boolean;
    promptShare: boolean;
    itemsWithPreviousStacks?: ItemWithPreviousStacks[];
  }>;
  restoreToStacks: (contentKey: string, stackIds: string[]) => Promise<{
    success: boolean;
    restoredTo?: string[];
    errors?: string[];
  }>;
}

export function useStack(stackId: string | null): UseStackReturn {
  const { address } = useAccount();
  const [stack, setStack] = useState<Stack | null>(null);
  const [items, setItems] = useState<StackItem[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchStack = useCallback(async () => {
    if (!stackId) return;

    setIsLoading(true);
    setError(null);

    try {
      // Pass viewer address to track views (only counted if different from owner)
      const viewerParam = address ? `&viewer=${address}` : "";
      const response = await fetch(`/api/stacks?id=${stackId}${viewerParam}`);
      const data = await response.json();

      if (data.success) {
        setStack(data.stack);
        setItems(data.items || []);
      } else {
        setError(data.error || "Failed to fetch stack");
      }
    } catch (err) {
      console.error("[useStack] Fetch error:", err);
      setError("Failed to load stack");
    } finally {
      setIsLoading(false);
    }
  }, [stackId, address]);

  useEffect(() => {
    fetchStack();
  }, [fetchStack]);

  const addItem = useCallback(async (contentKey: string): Promise<boolean> => {
    if (!stackId || !address) return false;

    try {
      const response = await fetch("/api/stacks", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          stackId,
          action: "add-item",
          owner: address,
          contentKey,
        }),
      });

      const result = await response.json();

      if (result.success) {
        await fetchStack(); // Refresh
        return true;
      } else {
        setError(result.error || "Failed to add item");
        return false;
      }
    } catch (err) {
      console.error("[useStack] Add item error:", err);
      setError("Failed to add item");
      return false;
    }
  }, [stackId, address, fetchStack]);

  const removeItem = useCallback(async (contentKey: string): Promise<boolean> => {
    if (!stackId || !address) return false;

    try {
      const response = await fetch("/api/stacks", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          stackId,
          action: "remove-item",
          owner: address,
          contentKey,
        }),
      });

      const result = await response.json();

      if (result.success) {
        await fetchStack(); // Refresh
        return true;
      } else {
        setError(result.error || "Failed to remove item");
        return false;
      }
    } catch (err) {
      console.error("[useStack] Remove item error:", err);
      setError("Failed to remove item");
      return false;
    }
  }, [stackId, address, fetchStack]);

  const unlockStack = useCallback(async (txHash: string): Promise<boolean> => {
    if (!stackId || !address) return false;

    try {
      const response = await fetch("/api/stacks", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          stackId,
          action: "unlock",
          owner: address,
          txHash,
        }),
      });

      const result = await response.json();

      if (result.success) {
        setStack(result.stack);
        return true;
      } else {
        setError(result.error || "Failed to unlock stack");
        return false;
      }
    } catch (err) {
      console.error("[useStack] Unlock error:", err);
      setError("Failed to unlock stack");
      return false;
    }
  }, [stackId, address]);

  const reorderItems = useCallback(async (itemOrder: string[]): Promise<boolean> => {
    if (!stackId || !address) return false;

    try {
      const response = await fetch("/api/stacks", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          stackId,
          action: "reorder-items",
          owner: address,
          itemOrder,
        }),
      });

      const result = await response.json();

      if (result.success) {
        setItems(result.items);
        return true;
      } else {
        setError(result.error || "Failed to reorder items");
        return false;
      }
    } catch (err) {
      console.error("[useStack] Reorder error:", err);
      setError("Failed to reorder items");
      return false;
    }
  }, [stackId, address]);

  const updateMetadata = useCallback(async (name: string, description?: string): Promise<boolean> => {
    if (!stackId || !address) return false;

    try {
      const response = await fetch("/api/stacks", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          stackId,
          action: "update-metadata",
          owner: address,
          name,
          description,
        }),
      });

      const result = await response.json();

      if (result.success) {
        setStack(result.stack);
        return true;
      } else {
        setError(result.error || "Failed to update stack");
        return false;
      }
    } catch (err) {
      console.error("[useStack] Update error:", err);
      setError("Failed to update stack");
      return false;
    }
  }, [stackId, address]);

  // Set privacy state (returns true if should prompt to share when going public)
  const setPrivacy = useCallback(async (isPrivate: boolean): Promise<{
    success: boolean;
    promptShare: boolean;
    itemsWithPreviousStacks?: ItemWithPreviousStacks[];
  }> => {
    if (!stackId || !address) return { success: false, promptShare: false };

    try {
      const response = await fetch("/api/stacks", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          stackId,
          action: "set-privacy",
          owner: address,
          isPrivate,
        }),
      });

      const result = await response.json();

      if (result.success) {
        setStack(result.stack);
        return {
          success: true,
          promptShare: result.promptShare || false,
          itemsWithPreviousStacks: result.itemsWithPreviousStacks,
        };
      } else {
        setError(result.error || "Failed to update privacy");
        return { success: false, promptShare: false };
      }
    } catch (err) {
      console.error("[useStack] Privacy update error:", err);
      setError("Failed to update privacy");
      return { success: false, promptShare: false };
    }
  }, [stackId, address]);

  // Restore an item to its previous stacks
  const restoreToStacks = useCallback(async (contentKey: string, stackIds: string[]): Promise<{
    success: boolean;
    restoredTo?: string[];
    errors?: string[];
  }> => {
    if (!stackId || !address) return { success: false };

    try {
      const response = await fetch("/api/stacks", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          stackId,
          action: "restore-to-stacks",
          owner: address,
          contentKey,
          stackIds,
        }),
      });

      const result = await response.json();

      if (result.success) {
        return {
          success: true,
          restoredTo: result.restoredTo,
          errors: result.errors,
        };
      } else {
        return { success: false, errors: [result.error || "Failed to restore"] };
      }
    } catch (err) {
      console.error("[useStack] Restore error:", err);
      return { success: false, errors: ["Failed to restore items"] };
    }
  }, [stackId, address]);

  return {
    stack,
    items,
    isLoading,
    error,
    refresh: fetchStack,
    addItem,
    removeItem,
    unlockStack,
    reorderItems,
    updateMetadata,
    setPrivacy,
    restoreToStacks,
  };
}

// Hook to get user's stacks (for "Add to Stack" flow)
// Uses all known addresses for the user (cross-platform identity)
export function useUserStacks() {
  const { address } = useAccount();
  const { registeredAddress, linkedAddresses, allMemberships, isLoading: isMembershipLoading } = useMembershipStatus();

  // Build list of all addresses that belong to this user
  // This enables finding stacks created on ANY platform (Farcaster, Base App, Web)
  const allAddresses = useMemo(() => {
    const addresses = new Set<string>();

    // Current connected wallet
    if (address) addresses.add(address.toLowerCase());

    // Membership registered address (the address used for membership)
    if (registeredAddress) addresses.add(registeredAddress.toLowerCase());

    // Linked addresses (additional wallets linked to membership)
    if (linkedAddresses) {
      for (const linked of linkedAddresses) {
        if (linked) addresses.add(linked.toLowerCase());
      }
    }

    // All membership addresses (for users with multiple memberships)
    if (allMemberships) {
      for (const membership of allMemberships) {
        if (membership.address) addresses.add(membership.address.toLowerCase());
      }
    }

    return Array.from(addresses);
  }, [address, registeredAddress, linkedAddresses, allMemberships]);

  // Use the multi-owner query if we have addresses
  const hasAddresses = allAddresses.length > 0;

  // Log for debugging cross-platform identity
  useEffect(() => {
    if (allAddresses.length > 0) {
      console.log("[useUserStacks] Querying stacks for addresses:", allAddresses.map(a => `${a.slice(0, 6)}...${a.slice(-4)}`).join(", "));
    }
  }, [allAddresses]);

  return useStacks({
    owners: hasAddresses ? allAddresses : undefined,
    enabled: hasAddresses && !isMembershipLoading,
  });
}

// Hook to check which stacks contain a specific item
export function useItemStacks(contentKey: string | null) {
  const [stacks, setStacks] = useState<Stack[]>([]);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    if (!contentKey) {
      setStacks([]);
      return;
    }

    const fetchItemStacks = async () => {
      setIsLoading(true);
      try {
        const response = await fetch(`/api/stacks?contentKey=${encodeURIComponent(contentKey)}`);
        const data = await response.json();
        if (data.success) {
          setStacks(data.stacks || []);
        }
      } catch (err) {
        console.error("[useItemStacks] Error:", err);
      } finally {
        setIsLoading(false);
      }
    };

    fetchItemStacks();
  }, [contentKey]);

  return { stacks, isLoading };
}
src/hooks/use-trending.ts
"use client";

import { useState, useEffect, useCallback, useRef } from "react";

interface TrendingStatus {
  isTrending: boolean;
  upvotesInLastHour: number;
}

interface TrendingItem {
  contentKey: string;
  upvotesInLastHour: number;
}

interface TrendingResponse {
  success: boolean;
  trendingStatus: Record<string, TrendingStatus>;
  allTrending: TrendingItem[];
  threshold: number;
  windowMs: number;
}

/**
 * Hook to check trending status for multiple content items
 * Trending = 100+ upvotes in the last hour
 */
export function useTrending(contentKeys: string[]) {
  const [trendingStatus, setTrendingStatus] = useState<Record<string, TrendingStatus>>({});
  const [allTrending, setAllTrending] = useState<TrendingItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Track if we've fetched with actual keys
  const hasFetchedRef = useRef(false);

  // Stable key for dependencies
  const keysString = contentKeys.filter(Boolean).join(",");

  const fetchTrending = useCallback(async () => {
    const keys = contentKeys.filter(Boolean);

    if (keys.length === 0) {
      if (hasFetchedRef.current) {
        setTrendingStatus({});
        setIsLoading(false);
      }
      return;
    }

    hasFetchedRef.current = true;
    setIsLoading(true);
    setError(null);

    try {
      const response = await fetch(
        `/api/trending?contentKeys=${encodeURIComponent(keys.join(","))}`
      );

      if (!response.ok) {
        throw new Error("Failed to fetch trending status");
      }

      const data: TrendingResponse = await response.json();

      if (data.success) {
        setTrendingStatus(data.trendingStatus);
        setAllTrending(data.allTrending);
      }
    } catch (err) {
      console.error("[useTrending] Error:", err);
      setError(err instanceof Error ? err.message : "Failed to fetch trending");
    } finally {
      setIsLoading(false);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [keysString]);

  useEffect(() => {
    fetchTrending();
  }, [fetchTrending]);

  // Auto-refresh every 5 minutes to keep trending status current
  useEffect(() => {
    if (contentKeys.filter(Boolean).length === 0) return;

    const interval = setInterval(fetchTrending, 5 * 60 * 1000);
    return () => clearInterval(interval);
  }, [fetchTrending, contentKeys]);

  const isTrending = useCallback(
    (contentKey: string): boolean => {
      const key = contentKey?.toLowerCase();
      return trendingStatus[key]?.isTrending ?? false;
    },
    [trendingStatus]
  );

  const getUpvotesInLastHour = useCallback(
    (contentKey: string): number => {
      const key = contentKey?.toLowerCase();
      return trendingStatus[key]?.upvotesInLastHour ?? 0;
    },
    [trendingStatus]
  );

  return {
    trendingStatus,
    allTrending,
    isLoading,
    error,
    isTrending,
    getUpvotesInLastHour,
    refresh: fetchTrending,
  };
}

/**
 * Hook to check if a single item is trending
 * Convenience wrapper around useTrending for single items
 */
export function useIsTrending(contentKey: string | undefined) {
  const keys = contentKey ? [contentKey] : [];
  const { isTrending, getUpvotesInLastHour, isLoading } = useTrending(keys);

  return {
    isTrending: contentKey ? isTrending(contentKey) : false,
    upvotesInLastHour: contentKey ? getUpvotesInLastHour(contentKey) : 0,
    isLoading,
  };
}
src/hooks/use-upload-reputation.ts
"use client";

import { useState, useCallback, useEffect } from "react";
import { useAccount } from "wagmi";
import type {
  UserUploadStats,
  UploadEligibility,
  DuplicateCheckResult,
} from "@/lib/net-protocol";
import { computeContentHash } from "@/lib/net-protocol";
import { useMembershipStatus } from "@/hooks/use-membership-status";

interface UseUploadLimitsReturn {
  // Current user's upload stats
  stats: UserUploadStats | null;
  uploadsRemaining: number;
  maxFileSizeAllowed: number;
  dailyLimit: number;
  isLoading: boolean;

  // Warm-up period info
  isInWarmupPeriod: boolean;
  daysRemainingInWarmup: number;
  hasUploadPass: boolean;

  // Check if a specific upload is allowed
  checkUpload: (file: File, metadata?: { title?: string; author?: string; isbn?: string }) => Promise<{
    eligible: UploadEligibility;
    duplicate: DuplicateCheckResult | null;
    contentHash: string;
  }>;

  // Record a completed upload
  recordUpload: (fileSize: number, contentKey: string) => Promise<void>;

  // Record Upload Pass purchase
  recordUploadPassPurchase: (txHash?: string) => Promise<void>;

  // Refresh stats
  refresh: () => Promise<void>;
}

export function useUploadLimits(): UseUploadLimitsReturn {
  const { address, isConnected } = useAccount();
  const { isMember, fid, registeredAddress, isLoading: isMembershipLoading } = useMembershipStatus();

  // Use the registered membership address if available, otherwise fall back to connected wallet
  // This ensures cross-platform users get correct stats even when connected with a different wallet
  const effectiveAddress = registeredAddress || address;

  const [stats, setStats] = useState<UserUploadStats | null>(null);
  const [uploadsRemaining, setUploadsRemaining] = useState(0);
  const [maxFileSizeAllowed, setMaxFileSizeAllowed] = useState(0);
  const [dailyLimit, setDailyLimit] = useState(10);
  const [isInWarmupPeriod, setIsInWarmupPeriod] = useState(false);
  const [daysRemainingInWarmup, setDaysRemainingInWarmup] = useState(0);
  const [hasUploadPass, setHasUploadPass] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  // Fetch user's upload stats
  const fetchStats = useCallback(async () => {
    if (!effectiveAddress || !isConnected) {
      setStats(null);
      setUploadsRemaining(0);
      setMaxFileSizeAllowed(0);
      setDailyLimit(10);
      setIsInWarmupPeriod(false);
      setDaysRemainingInWarmup(0);
      setHasUploadPass(false);
      setIsLoading(false);
      return;
    }

    try {
      setIsLoading(true);
      // Include FID for cross-platform membership lookup.
      // isMember is intentionally omitted — the server now derives membership
      // status from the registry rather than trusting a client-supplied param.
      const fidParam = fid ? `&fid=${fid}` : "";
      const url = `/api/upload-check?address=${effectiveAddress}${fidParam}`;
      console.log("[useUploadLimits] Fetching stats:", { url, effectiveAddress, registeredAddress, address, fid });
      const response = await fetch(url);

      if (!response.ok) {
        throw new Error("Failed to fetch upload stats");
      }

      const data = await response.json();

      setStats(data.stats);
      setUploadsRemaining(data.uploadsRemaining);
      setMaxFileSizeAllowed(data.maxFileSizeAllowed);
      setDailyLimit(data.dailyLimit);
      setIsInWarmupPeriod(data.isInWarmupPeriod);
      setDaysRemainingInWarmup(data.daysRemainingInWarmup);
      setHasUploadPass(data.hasUploadPass);
    } catch (error) {
      console.error("[useUploadLimits] Error fetching stats:", error);
    } finally {
      setIsLoading(false);
    }
  }, [effectiveAddress, registeredAddress, address, isConnected, isMember, fid]);

  // Initial fetch - wait for membership to load so we have registeredAddress and FID
  useEffect(() => {
    console.log("[useUploadLimits] Effect check:", { isMembershipLoading, effectiveAddress, registeredAddress, address, fid, isMember });
    if (!isMembershipLoading) {
      fetchStats();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [fetchStats, isMembershipLoading]);

  // Check if a specific file upload is allowed
  const checkUpload = useCallback(async (
    file: File,
    metadata?: { title?: string; author?: string; isbn?: string }
  ): Promise<{
    eligible: UploadEligibility;
    duplicate: DuplicateCheckResult | null;
    contentHash: string;
  }> => {
    if (!effectiveAddress) {
      throw new Error("Wallet not connected");
    }

    // Compute content hash for deduplication
    const contentHash = await computeContentHash(file);

    // Check eligibility and duplicates (include FID for cross-platform membership)
    // Use effectiveAddress for consistent cross-platform identity
    const response = await fetch("/api/upload-check", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        address: effectiveAddress,
        isMember,
        fid: fid || undefined,
        contentHash,
        title: metadata?.title || file.name,
        author: metadata?.author || undefined,
        isbn: metadata?.isbn || undefined,
        fileSize: file.size,
      }),
    });

    if (!response.ok) {
      throw new Error("Failed to check upload eligibility");
    }

    const data = await response.json();

    return {
      eligible: data.eligibility,
      duplicate: data.duplicateCheck,
      contentHash,
    };
  }, [effectiveAddress, isMember, fid]);

  // Record a completed upload
  const recordUpload = useCallback(async (fileSize: number, contentKey: string) => {
    if (!effectiveAddress) return;

    try {
      await fetch("/api/upload-check", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          address: effectiveAddress,
          fileSize,
          contentKey,
          fid: fid || undefined,
        }),
      });

      // Refresh stats after recording
      await fetchStats();
    } catch (error) {
      console.error("[useUploadLimits] Error recording upload:", error);
    }
  }, [effectiveAddress, fetchStats]);

  // Record Upload Pass purchase
  const recordUploadPassPurchase = useCallback(async (txHash?: string) => {
    if (!effectiveAddress) return;

    try {
      await fetch("/api/upload-check", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          address: effectiveAddress,
          txHash,
        }),
      });

      // Refresh stats after recording
      await fetchStats();
    } catch (error) {
      console.error("[useUploadLimits] Error recording upload pass:", error);
    }
  }, [effectiveAddress, fetchStats]);

  return {
    stats,
    uploadsRemaining,
    maxFileSizeAllowed,
    dailyLimit,
    isLoading: isLoading || isMembershipLoading,
    isInWarmupPeriod,
    daysRemainingInWarmup,
    hasUploadPass,
    checkUpload,
    recordUpload,
    recordUploadPassPurchase,
    refresh: fetchStats,
  };
}

// Keep old export name for backwards compatibility
export const useUploadReputation = useUploadLimits;
src/hooks/use-upvotes.ts
"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { useWriteContract, useWaitForTransactionReceipt, useAccount } from "wagmi";
import { keccak256, encodePacked, parseEther } from "viem";
import { base } from "viem/chains";
import { trackEngagement } from "@/lib/diagnostics";

// Contract addresses on Base
const UPVOTE_STORAGE_APP = "0x000000060CEB69D023227DF64CfB75eC37c75B62" as const;
const PURE_ALPHA_STRATEGY = "0x00000001b1bcdeddeafd5296aaf4f3f3e21ae876" as const;
const SCORE_CONTRACT = "0x0000000FA09B022E5616E5a173b4b67FA2FBcF28" as const;

// Helper to record upvote to KV storage
async function recordUpvoteToKV(params: {
  upvoter: string;
  storageKey: string;
  operator: string;
  amount: number;
  transactionHash: string;
  contentKey?: string;
}): Promise<boolean> {
  try {
    const response = await fetch("/api/upvote-events", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(params),
    });
    const data = await response.json();
    if (data.success) {
      console.log("[useUpvote] Recorded upvote to KV storage:", params.transactionHash);
      return true;
    }
    console.error("[useUpvote] Failed to record upvote:", data.error);
    return false;
  } catch (err) {
    console.error("[useUpvote] Error recording upvote to KV:", err);
    return false;
  }
}

// Cost per upvote in ETH
export const UPVOTE_COST_ETH = 0.000025;
export const UPVOTE_COST_WEI = parseEther(UPVOTE_COST_ETH.toString());

// ABI for UpvoteStorageApp
const UPVOTE_STORAGE_APP_ABI = [
  {
    name: "upvote",
    type: "function",
    stateMutability: "payable",
    inputs: [
      { name: "strategy", type: "address" },
      { name: "storageOperatorAddress", type: "address" },
      { name: "storageKey", type: "bytes32" },
      { name: "scoreDelta", type: "uint256" },
      { name: "scoreUnstoredContext", type: "bytes" },
    ],
    outputs: [],
  },
] as const;

// ABI for Score contract (querying)
const _SCORE_ABI = [
  {
    name: "getStrategyKeyScores",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "strategy", type: "address" },
      { name: "scoreKeys", type: "bytes32[]" },
    ],
    outputs: [{ name: "counts", type: "int256[]" }],
  },
  {
    name: "getAppStrategyKeyScores",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "app", type: "address" },
      { name: "strategy", type: "address" },
      { name: "scoreKeys", type: "bytes32[]" },
    ],
    outputs: [{ name: "counts", type: "int256[]" }],
  },
] as const;

// Generate scoreKey for storage content
export function generateScoreKey(storageKey: string, operatorAddress: string): `0x${string}` {
  // Ensure storageKey is bytes32 format (0x + 64 hex chars = 66 total)
  let key = storageKey.startsWith("0x") ? storageKey : `0x${storageKey}`;

  // If key is too short, left-pad with zeros (after 0x prefix)
  // bytes32 = 32 bytes = 64 hex chars + "0x" prefix = 66 chars total
  if (key.length < 66) {
    const hexPart = key.slice(2); // Remove 0x
    const paddedHex = hexPart.padStart(64, "0"); // Left-pad to 64 hex chars
    key = `0x${paddedHex}`;
  }

  // Keys should always be exactly 66 chars (0x + 64 hex) at this point.
  // Do NOT truncate — truncation silently corrupts the key and breaks score lookups.
  if (key.length !== 66) {
    console.warn("[generateScoreKey] Unexpected key length:", key.length, key);
  }

  return keccak256(
    encodePacked(
      ["bytes32", "address"],
      [key as `0x${string}`, operatorAddress.toLowerCase() as `0x${string}`]
    )
  );
}

// Pending upvote info for KV recording
interface PendingUpvote {
  storageKey: string;
  operator: string;
  amount: number;
  contentKey?: string;
}

// Hook for upvoting
export function useUpvote() {
  const { address, isConnected } = useAccount();
  const [isUpvoting, setIsUpvoting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Track pending upvote info for KV recording
  const pendingUpvoteRef = useRef<PendingUpvote | null>(null);

  // Synchronous double-click guard — checked before React state has a chance to update,
  // preventing duplicate wallet prompts on rapid successive clicks.
  const isProcessingRef = useRef(false);

  const { writeContract, data: txHash, isPending, isError: isWriteError, reset } = useWriteContract();

  const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({
    hash: txHash,
  });

  // Release the double-click guard when wagmi signals an error (e.g. user rejected the wallet prompt).
  // Without this, isProcessingRef stays true forever after a rejection, permanently locking the button.
  // reset() clears wagmi's internal isWriteError flag so it doesn't linger across subsequent attempts.
  useEffect(() => {
    if (isWriteError) {
      isProcessingRef.current = false;
      setIsUpvoting(false);
      pendingUpvoteRef.current = null;
      reset();
    }
  }, [isWriteError, reset]);

  // When transaction confirms, record to KV and reset state
  useEffect(() => {
    if (isConfirmed && txHash && address && pendingUpvoteRef.current) {
      const pending = pendingUpvoteRef.current;

      // Track successful upvote
      trackEngagement.upvote(pending.contentKey || pending.storageKey, address, "success");

      // Record to KV storage — awaited so failures are visible in logs
      recordUpvoteToKV({
        upvoter: address,
        storageKey: pending.storageKey,
        operator: pending.operator,
        amount: pending.amount,
        transactionHash: txHash,
        contentKey: pending.contentKey,
      }).then((ok) => {
        if (!ok) {
          console.error("[useUpvote] KV record failed for tx:", txHash);
        }
      });

      // Clear pending info and release double-click guard
      pendingUpvoteRef.current = null;
      isProcessingRef.current = false;
      setIsUpvoting(false);
      reset();
    }
  }, [isConfirmed, txHash, address, reset]);

  const upvote = useCallback(
    async (
      storageKey: string,
      operatorAddress: string,
      count: number = 1,
      contentKey?: string
    ) => {
      if (!isConnected || !address) {
        setError("Wallet not connected");
        return false;
      }

      if (count < 1) {
        setError("Must upvote at least 1");
        return false;
      }

      // Synchronous double-click guard (ref) — catches rapid re-clicks before React re-renders
      if (isProcessingRef.current || isPending || isUpvoting) {
        console.log("[useUpvote] Transaction already in progress, ignoring duplicate click");
        return false;
      }
      isProcessingRef.current = true;

      setIsUpvoting(true);
      setError(null);

      try {
        const totalCost = UPVOTE_COST_WEI * BigInt(count);

        // Ensure storageKey is properly formatted as bytes32
        const formattedKey = storageKey.startsWith("0x")
          ? storageKey as `0x${string}`
          : `0x${storageKey}` as `0x${string}`;

        // Store pending upvote info for KV recording when confirmed
        pendingUpvoteRef.current = {
          storageKey: formattedKey,
          operator: operatorAddress,
          amount: count,
          contentKey,
        };

        writeContract({
          address: UPVOTE_STORAGE_APP,
          abi: UPVOTE_STORAGE_APP_ABI,
          functionName: "upvote",
          args: [
            PURE_ALPHA_STRATEGY,
            operatorAddress as `0x${string}`,
            formattedKey,
            BigInt(count),
            "0x" as `0x${string}`, // empty scoreUnstoredContext
          ],
          value: totalCost,
          chainId: base.id,
        });

        // Note: isProcessingRef is cleared in the confirmation effect, not here,
        // because writeContract is async and we need the guard to persist until
        // the wallet prompt is either accepted or rejected.
        return true;
      } catch (err) {
        console.error("[useUpvote] Error:", err);
        const errorMsg = err instanceof Error ? err.message : "Failed to upvote";
        setError(errorMsg);
        setIsUpvoting(false);
        isProcessingRef.current = false;

        // Track failed upvote
        if (contentKey) {
          trackEngagement.upvote(contentKey, address || "", "error", errorMsg);
        }

        pendingUpvoteRef.current = null;
        return false;
      }
    },
    [isConnected, address, writeContract, isPending, isUpvoting]
  );

  return {
    upvote,
    isUpvoting: isUpvoting || isPending || isConfirming,
    isConfirmed,
    error,
    txHash,
    reset: () => {
      reset();
      setError(null);
      setIsUpvoting(false);
      pendingUpvoteRef.current = null;
      isProcessingRef.current = false;
    },
  };
}

// Hook for fetching upvote counts
export function useUpvoteCounts(
  items: Array<{ contentKey: string; operator: string }>
) {
  const [counts, setCounts] = useState<Map<string, number>>(new Map());
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // Track if we've ever fetched with items (to know if empty is intentional or loading)
  const hasFetchedWithItemsRef = useRef(false);

  // Serialize items for stable dependency comparison
  const itemsKey = JSON.stringify(items.map(i => `${i.contentKey}:${i.operator}`).sort());

  const fetchCounts = useCallback(async () => {
    if (items.length === 0) {
      // Only set loading to false if we've already fetched with items before
      // This prevents the "flash to 0" when items aren't ready yet
      if (hasFetchedWithItemsRef.current) {
        setCounts(new Map());
        setIsLoading(false);
      }
      return;
    }

    // Mark that we've fetched with actual items
    hasFetchedWithItemsRef.current = true;

    setIsLoading(true);
    setError(null);

    try {
      // Generate scoreKeys for all items
      const scoreKeys = items.map((item) =>
        generateScoreKey(item.contentKey, item.operator)
      );

      // Call the Score contract to get counts
      const response = await fetch("/api/upvotes", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          scoreKeys,
          contentKeys: items.map((i) => i.contentKey),
        }),
      });

      if (!response.ok) {
        throw new Error("Failed to fetch upvote counts");
      }

      const data = await response.json();
      const newCounts = new Map<string, number>();

      if (data.counts) {
        items.forEach((item, index) => {
          newCounts.set(item.contentKey, data.counts[index] || 0);
        });
      }

      setCounts(newCounts);
    } catch (err) {
      console.error("[useUpvoteCounts] Error:", err);
      setError(err instanceof Error ? err.message : "Failed to fetch counts");
    } finally {
      setIsLoading(false);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [itemsKey]);

  useEffect(() => {
    fetchCounts();
  }, [fetchCounts]);

  const getCount = useCallback(
    (contentKey: string) => counts.get(contentKey) || 0,
    [counts]
  );

  return {
    counts,
    getCount,
    isLoading,
    error,
    refresh: fetchCounts,
  };
}

// Export contract addresses for reference
export const UPVOTE_CONTRACTS = {
  UPVOTE_STORAGE_APP,
  PURE_ALPHA_STRATEGY,
  SCORE_CONTRACT,
};

// Hook for fetching last upvote timestamps per content (for "recently upvoted" sorting)
export function useUpvoteTimestamps(operatorAddress: string | undefined) {
  const [timestamps, setTimestamps] = useState<Map<string, number>>(new Map());
  const [isLoading, setIsLoading] = useState(true);

  const fetchTimestamps = useCallback(async () => {
    if (!operatorAddress) {
      setTimestamps(new Map());
      setIsLoading(false);
      return;
    }

    setIsLoading(true);

    try {
      const response = await fetch("/api/upvote-events");
      if (!response.ok) {
        throw new Error("Failed to fetch upvote events");
      }

      const data = await response.json();
      const newTimestamps = new Map<string, number>();

      // Find the most recent upvote timestamp for each content by this operator
      if (data.topUpvoters) {
        for (const upvoter of data.topUpvoters) {
          for (const item of upvoter.itemsUpvoted || []) {
            // Filter to items belonging to this operator
            if (item.operator?.toLowerCase() === operatorAddress.toLowerCase()) {
              const contentKey = item.contentKey || item.storageKey;
              const existingTimestamp = newTimestamps.get(contentKey) || 0;
              if (item.timestamp > existingTimestamp) {
                newTimestamps.set(contentKey, item.timestamp);
              }
            }
          }
        }
      }

      setTimestamps(newTimestamps);
    } catch (err) {
      console.error("[useUpvoteTimestamps] Error:", err);
    } finally {
      setIsLoading(false);
    }
  }, [operatorAddress]);

  useEffect(() => {
    fetchTimestamps();
  }, [fetchTimestamps]);

  const getLastUpvoteTime = useCallback(
    (contentKey: string) => timestamps.get(contentKey) || 0,
    [timestamps]
  );

  return {
    timestamps,
    getLastUpvoteTime,
    isLoading,
    refresh: fetchTimestamps,
  };
}
src/hooks/use-usdc-approval.ts
"use client";

/**
 * USDC Approval Hook for x402 Relay Payments
 *
 * Handles USDC balance checking and approval for the relay treasury.
 * Works on both Farcaster and Base App platforms.
 *
 * Usage:
 * ```tsx
 * const { balance, allowance, approve, isApproving } = useUsdcApproval();
 *
 * // Check if approval is needed
 * if (needsApproval(estimatedCostUsdc)) {
 *   await approve(estimatedCostUsdc);
 * }
 * ```
 */

import { useState, useCallback, useEffect } from "react";
import { useAccount, useSendCalls, usePublicClient, useWriteContract } from "wagmi";
import { encodeFunctionData, parseUnits, formatUnits } from "viem";
import type { Address } from "viem";

import { getRelayConfig } from "@/lib/relay-feature-flags";
import { BASE_CHAIN_ID } from "@/lib/net-protocol";
import { detectFarcasterFrame } from "@/lib/app-mode";

// =============================================================================
// CONSTANTS
// =============================================================================

// Base USDC Contract
export const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" as Address;
export const USDC_DECIMALS = 6;

// ERC20 ABI subset for approval operations
const ERC20_ABI = [
  {
    name: "approve",
    type: "function",
    inputs: [
      { name: "spender", type: "address" },
      { name: "value", type: "uint256" },
    ],
    outputs: [{ name: "", type: "bool" }],
  },
  {
    name: "allowance",
    type: "function",
    inputs: [
      { name: "owner", type: "address" },
      { name: "spender", type: "address" },
    ],
    outputs: [{ name: "", type: "uint256" }],
  },
  {
    name: "balanceOf",
    type: "function",
    inputs: [{ name: "account", type: "address" }],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

// =============================================================================
// TYPES
// =============================================================================

export interface UsdcApprovalState {
  // Balances (in human-readable format, e.g., "10.50")
  balance: string;
  balanceRaw: bigint;
  allowance: string;
  allowanceRaw: bigint;

  // Loading states
  isLoadingBalance: boolean;
  isApproving: boolean;

  // Errors
  error: string | null;
}

export interface ApprovalResult {
  success: boolean;
  txHash?: `0x${string}`;
  error?: string;
}

// =============================================================================
// HOOK
// =============================================================================

export function useUsdcApproval(spenderAddress?: Address) {
  const { address, isConnected } = useAccount();
  const publicClient = usePublicClient();
  const { sendCallsAsync } = useSendCalls();
  const { writeContractAsync } = useWriteContract();

  // Use provided spender or default to relay treasury
  const relayConfig = getRelayConfig();
  const spender = spenderAddress || relayConfig.service.treasuryAddress;

  // Detect platform
  const isFarcasterMode = typeof window !== "undefined" && detectFarcasterFrame();

  const [state, setState] = useState<UsdcApprovalState>({
    balance: "0",
    balanceRaw: BigInt(0),
    allowance: "0",
    allowanceRaw: BigInt(0),
    isLoadingBalance: false,
    isApproving: false,
    error: null,
  });

  /**
   * Fetch current USDC balance
   */
  const fetchBalance = useCallback(async (): Promise<bigint> => {
    if (!publicClient || !address) return BigInt(0);

    try {
      const balance = await publicClient.readContract({
        address: USDC_ADDRESS,
        abi: ERC20_ABI,
        functionName: "balanceOf",
        args: [address],
      });
      return balance as bigint;
    } catch (error) {
      console.error("Failed to fetch USDC balance:", error);
      return BigInt(0);
    }
  }, [publicClient, address]);

  /**
   * Fetch current allowance for spender
   */
  const fetchAllowance = useCallback(async (): Promise<bigint> => {
    if (!publicClient || !address) return BigInt(0);

    try {
      const allowance = await publicClient.readContract({
        address: USDC_ADDRESS,
        abi: ERC20_ABI,
        functionName: "allowance",
        args: [address, spender],
      });
      return allowance as bigint;
    } catch (error) {
      console.error("Failed to fetch USDC allowance:", error);
      return BigInt(0);
    }
  }, [publicClient, address, spender]);

  /**
   * Refresh balance and allowance
   */
  const refresh = useCallback(async () => {
    if (!isConnected || !address) return;

    setState((prev) => ({ ...prev, isLoadingBalance: true, error: null }));

    try {
      const [balanceRaw, allowanceRaw] = await Promise.all([
        fetchBalance(),
        fetchAllowance(),
      ]);

      setState((prev) => ({
        ...prev,
        balance: formatUnits(balanceRaw, USDC_DECIMALS),
        balanceRaw,
        allowance: formatUnits(allowanceRaw, USDC_DECIMALS),
        allowanceRaw,
        isLoadingBalance: false,
      }));
    } catch (error) {
      setState((prev) => ({
        ...prev,
        isLoadingBalance: false,
        error: error instanceof Error ? error.message : "Failed to fetch balance",
      }));
    }
  }, [isConnected, address, fetchBalance, fetchAllowance]);

  /**
   * Check if approval is needed for a given amount
   */
  const needsApproval = useCallback(
    (amountUsdc: number): boolean => {
      const requiredRaw = parseUnits(amountUsdc.toString(), USDC_DECIMALS);
      return state.allowanceRaw < requiredRaw;
    },
    [state.allowanceRaw]
  );

  /**
   * Check if user has sufficient balance
   */
  const hasSufficientBalance = useCallback(
    (amountUsdc: number): boolean => {
      const requiredRaw = parseUnits(amountUsdc.toString(), USDC_DECIMALS);
      return state.balanceRaw >= requiredRaw;
    },
    [state.balanceRaw]
  );

  /**
   * Approve USDC spending
   *
   * @param amountUsdc - Amount in human-readable USDC (e.g., 10.50)
   * @param addBuffer - Whether to add 20% buffer (default true)
   */
  const approve = useCallback(
    async (amountUsdc: number, addBuffer = true): Promise<ApprovalResult> => {
      if (!address) {
        return { success: false, error: "Wallet not connected" };
      }

      setState((prev) => ({ ...prev, isApproving: true, error: null }));

      // Add buffer for gas fluctuations
      const finalAmount = addBuffer ? amountUsdc * 1.2 : amountUsdc;
      const amountRaw = parseUnits(finalAmount.toFixed(USDC_DECIMALS), USDC_DECIMALS);

      try {
        let txHash: `0x${string}` | undefined;

        if (isFarcasterMode) {
          // Farcaster: Use sendCalls (EIP-5792)
          const approveCalldata = encodeFunctionData({
            abi: ERC20_ABI,
            functionName: "approve",
            args: [spender, amountRaw],
          });

          const result = await sendCallsAsync({
            calls: [{ to: USDC_ADDRESS, data: approveCalldata }],
            chainId: BASE_CHAIN_ID,
          });

          txHash = typeof result === "string" ? (result as `0x${string}`) : undefined;
        } else {
          // Base App: Can use writeContract directly or sendCalls
          // Try sendCalls first, fall back to writeContract
          try {
            const approveCalldata = encodeFunctionData({
              abi: ERC20_ABI,
              functionName: "approve",
              args: [spender, amountRaw],
            });

            const result = await sendCallsAsync({
              calls: [{ to: USDC_ADDRESS, data: approveCalldata }],
              chainId: BASE_CHAIN_ID,
            });

            txHash = typeof result === "string" ? (result as `0x${string}`) : undefined;
          } catch {
            // Fallback to writeContract
            txHash = await writeContractAsync({
              address: USDC_ADDRESS,
              abi: ERC20_ABI,
              functionName: "approve",
              args: [spender, amountRaw],
            });
          }
        }

        // Wait for confirmation
        await new Promise((resolve) => setTimeout(resolve, 3000));

        // Refresh allowance
        const newAllowance = await fetchAllowance();

        setState((prev) => ({
          ...prev,
          isApproving: false,
          allowance: formatUnits(newAllowance, USDC_DECIMALS),
          allowanceRaw: newAllowance,
        }));

        return { success: true, txHash };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : "Approval failed";

        // Check for user rejection
        const isUserRejection =
          errorMessage.toLowerCase().includes("user rejected") ||
          errorMessage.toLowerCase().includes("user denied") ||
          errorMessage.toLowerCase().includes("user cancelled");

        setState((prev) => ({
          ...prev,
          isApproving: false,
          error: isUserRejection ? "User rejected approval" : errorMessage,
        }));

        return {
          success: false,
          error: isUserRejection ? "User rejected approval" : errorMessage,
        };
      }
    },
    [address, spender, isFarcasterMode, sendCallsAsync, writeContractAsync, fetchAllowance]
  );

  /**
   * Approve maximum USDC (unlimited approval)
   */
  const approveMax = useCallback(async (): Promise<ApprovalResult> => {
    // Max uint256 for unlimited approval
    const maxAmount = BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");

    if (!address) {
      return { success: false, error: "Wallet not connected" };
    }

    setState((prev) => ({ ...prev, isApproving: true, error: null }));

    try {
      const approveCalldata = encodeFunctionData({
        abi: ERC20_ABI,
        functionName: "approve",
        args: [spender, maxAmount],
      });

      await sendCallsAsync({
        calls: [{ to: USDC_ADDRESS, data: approveCalldata }],
        chainId: BASE_CHAIN_ID,
      });

      await new Promise((resolve) => setTimeout(resolve, 3000));

      const newAllowance = await fetchAllowance();

      setState((prev) => ({
        ...prev,
        isApproving: false,
        allowance: formatUnits(newAllowance, USDC_DECIMALS),
        allowanceRaw: newAllowance,
      }));

      return { success: true };
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : "Approval failed";

      setState((prev) => ({
        ...prev,
        isApproving: false,
        error: errorMessage,
      }));

      return { success: false, error: errorMessage };
    }
  }, [address, spender, sendCallsAsync, fetchAllowance]);

  /**
   * Revoke approval (set to 0)
   */
  const revokeApproval = useCallback(async (): Promise<ApprovalResult> => {
    if (!address) {
      return { success: false, error: "Wallet not connected" };
    }

    setState((prev) => ({ ...prev, isApproving: true, error: null }));

    try {
      const approveCalldata = encodeFunctionData({
        abi: ERC20_ABI,
        functionName: "approve",
        args: [spender, BigInt(0)],
      });

      await sendCallsAsync({
        calls: [{ to: USDC_ADDRESS, data: approveCalldata }],
        chainId: BASE_CHAIN_ID,
      });

      await new Promise((resolve) => setTimeout(resolve, 3000));

      setState((prev) => ({
        ...prev,
        isApproving: false,
        allowance: "0",
        allowanceRaw: BigInt(0),
      }));

      return { success: true };
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : "Revoke failed";

      setState((prev) => ({
        ...prev,
        isApproving: false,
        error: errorMessage,
      }));

      return { success: false, error: errorMessage };
    }
  }, [address, spender, sendCallsAsync]);

  // Auto-fetch on mount and address change
  useEffect(() => {
    if (isConnected && address) {
      refresh();
    }
  }, [isConnected, address, refresh]);

  return {
    // State
    ...state,
    spender,

    // Computed
    hasBalance: state.balanceRaw > BigInt(0),
    hasAllowance: state.allowanceRaw > BigInt(0),

    // Methods
    refresh,
    needsApproval,
    hasSufficientBalance,
    approve,
    approveMax,
    revokeApproval,

    // Account
    isConnected,
    address,
    isFarcasterMode,
  };
}

// =============================================================================
// UTILITY FUNCTIONS
// =============================================================================

/**
 * Parse USDC amount from string to raw bigint
 */
export function parseUsdc(amount: string | number): bigint {
  return parseUnits(amount.toString(), USDC_DECIMALS);
}

/**
 * Format raw USDC bigint to human-readable string
 */
export function formatUsdc(amount: bigint): string {
  return formatUnits(amount, USDC_DECIMALS);
}

/**
 * Format USDC with currency symbol
 */
export function formatUsdcDisplay(amount: bigint | string | number): string {
  const value = typeof amount === "bigint" ? formatUnits(amount, USDC_DECIMALS) : amount.toString();
  return `$${Number(value).toFixed(2)}`;
}
src/hooks/use-user-net-link.ts
"use client";

import { useState, useEffect, useCallback } from "react";

interface NetLinkData {
  url: string;
  label: string;
  updatedAt?: number;
}

export function useUserNetLink(address?: string, fid?: number) {
  const [link, setLink] = useState<NetLinkData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchLink = useCallback(async () => {
    if (!address) {
      setLink(null);
      setIsLoading(false);
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      // Include FID for cross-platform link lookup
      const fidParam = fid ? `&fid=${fid}` : "";
      const response = await fetch(
        `/api/user-net-link?address=${encodeURIComponent(address)}${fidParam}`
      );
      const data = await response.json();

      if (data.success) {
        setLink(data.link);
      } else {
        setError(data.error);
      }
    } catch {
      setError("Failed to fetch link");
    } finally {
      setIsLoading(false);
    }
  }, [address, fid]);

  useEffect(() => {
    fetchLink();
  }, [fetchLink]);

  const updateLink = useCallback((url: string, label: string) => {
    setLink({ url, label, updatedAt: Date.now() });
  }, []);

  return {
    link,
    isLoading,
    error,
    refresh: fetchLink,
    updateLink,
  };
}
src/hooks/use-user-profile.ts
"use client";

/**
 * Unified User Profile Hook
 *
 * Provides user profile data (pfp, username, fid) regardless of platform.
 * - On Farcaster: Uses SDK context, supplements from Neynar if incomplete
 * - On Base App: Fetches from Neynar API using wallet address
 * - On Web: Fetches custom profile from membership (customUsername, customPfpUrl, WID)
 *
 * This centralizes profile fetching so all components get consistent data.
 */

import { useState, useEffect } from "react";
import { useAccount } from "wagmi";
import { useFarcasterUser } from "@/neynar-farcaster-sdk/mini";
import { useAppMode } from "@/lib/app-mode";

export interface UserProfile {
  fid?: number;
  username?: string;
  displayName?: string;
  pfpUrl?: string;
  address?: string;
  // Membership info (available on all platforms)
  memberId?: number;
  ensSubname?: string; // e.g., "123.netlibrary.eth"
  // Unified identity: Farcaster username stored at signup, shown on ALL platforms
  storedFarcasterUsername?: string; // e.g., "geaux.eth" - the social identity
  // Web platform specific
  wid?: string;
  customUsername?: string;
  customPfpUrl?: string;
  signupPlatform?: "farcaster" | "base-app" | "web";
}

interface UseUserProfileResult {
  profile: UserProfile | null;
  isLoading: boolean;
  error: string | null;
}

export function useUserProfile(): UseUserProfileResult {
  const appMode = useAppMode();
  const { address, isConnected } = useAccount();
  const { data: farcasterUser, isLoading: isFarcasterLoading } = useFarcasterUser();

  const [supplementedProfile, setSupplementedProfile] = useState<UserProfile | null>(null);
  // Start as true on Base App so we wait for the initial fetch
  const [isSupplementing, setIsSupplementing] = useState(true);
  const [hasFetchedOnce, setHasFetchedOnce] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Fetch/supplement profile from Neynar or membership data
  // - In Base App mode: always fetch by address
  // - In Web mode: fetch by address, include membership custom profile
  // - In Farcaster mode: supplement if SDK context is missing username/displayName
  // Note: Check for empty strings too, not just undefined/null
  useEffect(() => {
    const hasUsername = farcasterUser?.username && farcasterUser.username.trim().length > 0;
    const hasDisplayName = farcasterUser?.displayName && farcasterUser.displayName.trim().length > 0;
    const needsSupplementation = appMode === "farcaster" && farcasterUser?.fid && !hasUsername && !hasDisplayName;
    const isBaseApp = appMode === "base-app";
    const isWeb = appMode === "web";

    if (!isBaseApp && !isWeb && !needsSupplementation) {
      setSupplementedProfile(null);
      setIsSupplementing(false);
      setHasFetchedOnce(true);
      return;
    }

    if ((isBaseApp || isWeb) && (!address || !isConnected)) {
      setSupplementedProfile(null);
      setIsSupplementing(false);
      setHasFetchedOnce(true);
      return;
    }

    setIsSupplementing(true);
    setError(null);

    async function fetchProfile() {
      try {
        let response;

        // If we have an FID (Farcaster mode with incomplete data), fetch by FID
        if (needsSupplementation && farcasterUser?.fid) {
          response = await fetch("/api/resolve-user", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ fids: [farcasterUser.fid] }),
          });

          if (response.ok) {
            const data = await response.json();
            if (data.users?.[0]) {
              const user = data.users[0];
              setSupplementedProfile({
                fid: farcasterUser.fid,
                username: user.username,
                displayName: user.display_name,
                pfpUrl: user.pfp_url || farcasterUser.pfpUrl,
                address: address,
              });
              return;
            }
          }
        }

        // Otherwise fetch by address (Base App/Web mode or FID fetch failed)
        if (address) {
          // Fetch Neynar profile
          response = await fetch("/api/resolve-user", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ addresses: [address] }),
          });

          let neynarProfile: { fid?: number; username?: string; displayName?: string; pfpUrl?: string } | null = null;
          if (response.ok) {
            const data = await response.json();
            const lowerAddress = address.toLowerCase();
            if (data.users?.[lowerAddress]) {
              neynarProfile = data.users[lowerAddress];
            }
          }

          // Fetch membership info for ALL platforms (not just web)
          // This gives us memberId, ensSubname, and crucially the stored Farcaster username
          let membershipProfile: {
            memberId?: number;
            ensSubname?: string;
            wid?: string;
            customUsername?: string;
            customPfpUrl?: string;
            signupPlatform?: "farcaster" | "base-app" | "web";
            storedFarcasterUsername?: string; // The key field: username from Farcaster signup
          } | null = null;

          try {
            // Use membership API to get member info including stored Farcaster username
            const membershipResponse = await fetch(`/api/membership?address=${address}`);
            if (membershipResponse.ok) {
              const membershipData = await membershipResponse.json();
              if (membershipData.isMember && membershipData.member) {
                membershipProfile = {
                  memberId: membershipData.member.memberId,
                  ensSubname: membershipData.member.ensSubname,
                  wid: membershipData.member.wid,
                  customUsername: membershipData.member.customUsername,
                  customPfpUrl: membershipData.member.customPfpUrl,
                  signupPlatform: membershipData.member.signupPlatform,
                  // The stored Farcaster username - this is what we want to show everywhere
                  // It's stored in member.username when someone signs up via Farcaster
                  storedFarcasterUsername: membershipData.member.username,
                };
              }
            }
          } catch {
            // Ignore - membership profile is optional
          }

          // Build final profile
          // Priority for username/displayName: Farcaster username (stored at signup) > customUsername > Neynar
          // Priority for PFP: customPfpUrl > Neynar pfpUrl > identicon
          // The key insight: When someone signs up via Farcaster, we store their username.
          // That same username should show on Base App and Browser too for unified identity.
          const finalProfile: UserProfile = {
            fid: neynarProfile?.fid || farcasterUser?.fid,
            address: address,
          };

          // Add membership info if available (works on ALL platforms)
          if (membershipProfile) {
            finalProfile.memberId = membershipProfile.memberId;
            finalProfile.ensSubname = membershipProfile.ensSubname;
            finalProfile.wid = membershipProfile.wid;
            finalProfile.customUsername = membershipProfile.customUsername;
            finalProfile.customPfpUrl = membershipProfile.customPfpUrl;
            finalProfile.signupPlatform = membershipProfile.signupPlatform;
            // Also capture the stored Farcaster username from membership
            finalProfile.storedFarcasterUsername = membershipProfile.storedFarcasterUsername;

            // Username priority: stored Farcaster username > customUsername > Neynar username
            // This ensures @geaux.eth shows on Base App and Browser if signed up via Farcaster
            finalProfile.username = membershipProfile.storedFarcasterUsername || membershipProfile.customUsername || neynarProfile?.username;
            // Display name priority: stored Farcaster username > customUsername > Neynar displayName
            finalProfile.displayName = membershipProfile.storedFarcasterUsername || membershipProfile.customUsername || neynarProfile?.displayName;
            finalProfile.pfpUrl = membershipProfile.customPfpUrl || neynarProfile?.pfpUrl;
          } else if (neynarProfile) {
            finalProfile.username = neynarProfile.username;
            finalProfile.displayName = neynarProfile.displayName;
            finalProfile.pfpUrl = neynarProfile.pfpUrl;
          }

          setSupplementedProfile(finalProfile);
        }
      } catch (err) {
        console.error("Failed to fetch user profile:", err);
        setError(err instanceof Error ? err.message : "Failed to fetch profile");
        setSupplementedProfile({ fid: farcasterUser?.fid, address: address });
      } finally {
        setIsSupplementing(false);
        setHasFetchedOnce(true);
      }
    }

    fetchProfile();
  }, [appMode, address, isConnected, farcasterUser?.fid, farcasterUser?.username, farcasterUser?.displayName, farcasterUser?.pfpUrl]);

  // Return appropriate profile based on platform
  if (appMode === "farcaster") {
    // Check for valid (non-empty) username/displayName
    const sdkHasUsername = farcasterUser?.username && farcasterUser.username.trim().length > 0;
    const sdkHasDisplayName = farcasterUser?.displayName && farcasterUser.displayName.trim().length > 0;

    // If SDK data is complete, use it directly
    if (farcasterUser && (sdkHasUsername || sdkHasDisplayName)) {
      return {
        profile: {
          fid: farcasterUser.fid,
          username: farcasterUser.username,
          displayName: farcasterUser.displayName,
          pfpUrl: farcasterUser.pfpUrl,
          address: address,
        },
        isLoading: isFarcasterLoading,
        error: null,
      };
    }

    // SDK data incomplete - use supplemented profile if available
    if (supplementedProfile) {
      return {
        profile: supplementedProfile,
        isLoading: isSupplementing,
        error,
      };
    }

    // Still loading or no data - provide FID-based fallback display name
    return {
      profile: farcasterUser ? {
        fid: farcasterUser.fid,
        username: farcasterUser.username,
        // If no displayName/username, show FID-based identifier instead of nothing
        displayName: farcasterUser.displayName || (farcasterUser.fid ? `User #${farcasterUser.fid}` : undefined),
        pfpUrl: farcasterUser.pfpUrl,
        address: address,
      } : null,
      isLoading: isFarcasterLoading || isSupplementing,
      error: null,
    };
  }

  if (appMode === "base-app") {
    // Loading if either: still supplementing OR haven't fetched at all yet (initial state)
    const isLoadingProfile = isSupplementing || (!hasFetchedOnce && isConnected);
    return {
      profile: supplementedProfile,
      isLoading: isLoadingProfile,
      error,
    };
  }

  if (appMode === "web") {
    // Web mode - use supplemented profile (fetched from membership data)
    const isLoadingProfile = isSupplementing || (!hasFetchedOnce && isConnected);
    return {
      profile: supplementedProfile,
      isLoading: isLoadingProfile,
      error,
    };
  }

  // Still detecting mode
  return {
    profile: null,
    isLoading: true,
    error: null,
  };
}
src/hooks/use-user-stats.ts
"use client";

import { useState, useEffect, useCallback } from "react";
import {
  UserStreak,
  UserAchievements,
  AchievementId,
} from "@/lib/net-protocol";

// Fetch user achievements from our API (stored in KV database)
// First call triggers a recalculation from actual stats to ensure achievements are up-to-date
async function fetchUserAchievementsFromApi(address: string, forceRecalculate = true): Promise<AchievementId[]> {
  try {
    // Always recalculate on first load to ensure achievements are correct
    const url = forceRecalculate
      ? `/api/achievements/seed?address=${encodeURIComponent(address)}&recalculate=true`
      : `/api/achievements/seed?address=${encodeURIComponent(address)}`;
    const response = await fetch(url);
    if (!response.ok) return [];
    const data = await response.json();
    // Achievements come as { id, earnedAt }[] - extract just the IDs
    const achievements = data.achievements || [];
    return achievements.map((a: { id: string }) => a.id as AchievementId);
  } catch {
    return [];
  }
}

// Fetch user streak from our API (stored in KV database)
async function fetchUserStreakFromApi(address: string): Promise<UserStreak | null> {
  try {
    const response = await fetch(`/api/streaks?address=${encodeURIComponent(address)}`);
    if (!response.ok) return null;
    const data = await response.json();
    return data.streak || null;
  } catch {
    return null;
  }
}

// Hook to get user streak data
export function useUserStreak(address?: string) {
  const [streak, setStreak] = useState<UserStreak | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchStreak = useCallback(async () => {
    if (!address) {
      setStreak(null);
      setIsLoading(false);
      return;
    }

    setIsLoading(true);
    try {
      const userStreak = await fetchUserStreakFromApi(address);
      if (userStreak) {
        setStreak(userStreak);
      } else {
        // Default empty streak
        setStreak({
          address: address.toLowerCase(),
          currentStreak: 0,
          longestStreak: 0,
          lastReadDate: "",
          totalDaysActive: 0,
          readingHistory: [],
        });
      }
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to fetch streak");
    } finally {
      setIsLoading(false);
    }
  }, [address]);

  useEffect(() => {
    fetchStreak();
  }, [fetchStreak]);

  return { streak, isLoading, error, refresh: fetchStreak };
}

// Hook to get user achievements
export function useUserAchievements(address?: string) {
  const [achievements, setAchievements] = useState<UserAchievements | null>(null);
  const [earnedIds, setEarnedIds] = useState<AchievementId[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchAchievements = useCallback(async () => {
    if (!address) {
      setAchievements(null);
      setEarnedIds([]);
      setIsLoading(false);
      return;
    }

    setIsLoading(true);
    try {
      const achievementIds = await fetchUserAchievementsFromApi(address);
      setEarnedIds(achievementIds);
      setAchievements({
        address: address.toLowerCase(),
        earnedAchievements: achievementIds.map(id => ({ id, earnedAt: Date.now() })),
      });
      setError(null);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to fetch achievements");
    } finally {
      setIsLoading(false);
    }
  }, [address]);

  useEffect(() => {
    fetchAchievements();
  }, [fetchAchievements]);

  return { achievements, earnedIds, isLoading, error, refresh: fetchAchievements };
}

// Combined hook for all user stats
export function useUserStats(address?: string) {
  const { streak, isLoading: streakLoading, refresh: refreshStreak } = useUserStreak(address);
  const { earnedIds, isLoading: achievementsLoading, refresh: refreshAchievements } = useUserAchievements(address);

  const refresh = useCallback(() => {
    refreshStreak();
    refreshAchievements();
  }, [refreshStreak, refreshAchievements]);

  return {
    streak,
    earnedIds,
    isLoading: streakLoading || achievementsLoading,
    refresh,
  };
}
src/hooks/use-wallet-capabilities.ts
"use client";

import { useCapabilities } from "wagmi";
import { base } from "viem/chains";

interface WalletCapabilities {
  hasAuxiliaryFunds: boolean;
  hasPaymasterService: boolean;
  hasAtomicBatch: boolean;
  isLoading: boolean;
}

/**
 * Query wallet_getCapabilities for the connected wallet on Base.
 *
 * Used to detect:
 * - auxiliaryFunds: Coinbase Smart Wallet users who can pay from exchange
 *   balance via MagicSpend (even if onchain USDC balance is zero)
 * - paymasterService: Wallet can have gas sponsored
 * - atomic (atomicBatch): Wallet supports EIP-5792 sendCalls batching
 *
 * Falls back to all-false for EOA wallets or wallets that don't support
 * wallet_getCapabilities (MetaMask, Rainbow, etc.).
 */
export function useWalletCapabilities(): WalletCapabilities {
  const { data: caps, isLoading } = useCapabilities();

  if (isLoading || !caps) {
    return {
      hasAuxiliaryFunds: false,
      hasPaymasterService: false,
      hasAtomicBatch: false,
      isLoading,
    };
  }

  // Capabilities may be keyed by chain ID as a hex string ("0x2105"),
  // a decimal string ("8453"), or a plain number (8453) depending on the
  // wagmi version and wallet implementation.  Try all three forms so we
  // don't silently return all-false when the key format doesn't match.
  const hexKey = `0x${base.id.toString(16)}` as unknown as number; // cast to satisfy index type
  const decKey = String(base.id) as unknown as number;
  const baseCaps = (
    (caps[base.id] as Record<string, unknown> | undefined) ||
    (caps[hexKey] as Record<string, unknown> | undefined) ||
    (caps[decKey] as Record<string, unknown> | undefined)
  );

  if (!baseCaps) {
    return {
      hasAuxiliaryFunds: false,
      hasPaymasterService: false,
      hasAtomicBatch: false,
      isLoading: false,
    };
  }

  const auxiliaryFunds = baseCaps.auxiliaryFunds as { supported?: boolean } | undefined;
  const paymasterService = baseCaps.paymasterService as { supported?: boolean } | undefined;
  const atomic = baseCaps.atomic as string | undefined;

  return {
    hasAuxiliaryFunds: !!auxiliaryFunds?.supported,
    hasPaymasterService: !!paymasterService?.supported,
    hasAtomicBatch: atomic === "supported" || atomic === "ready",
    isLoading: false,
  };
}

🧩 Components (93)

src/app/embed/components/embed-footer.tsx
"use client";

import Image from "next/image";

interface EmbedFooterProps {
  appUrl?: string;
}

export function EmbedFooter({ appUrl = "https://netlibrary.app" }: EmbedFooterProps) {
  return (
    <a
      href={appUrl}
      target="_blank"
      rel="noopener noreferrer"
      className="flex items-center justify-center gap-1.5 py-2 px-3 bg-black/50 border-t border-[#00ff00]/20 hover:bg-[#00ff00]/5 transition-colors"
    >
      <Image
        src="/app-logo.png"
        alt="Net Library"
        width={16}
        height={16}
        className="rounded-sm"
      />
      <span className="text-[10px] font-mono text-gray-400 hover:text-[#00ff00] transition-colors">
        Powered by Net Library
      </span>
    </a>
  );
}
src/app/share/components/redirect-to-home.tsx
"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";

interface RedirectToHomeProps {
  /** Optional path to redirect to (e.g., "/?book=abc" or "/?stack=123") */
  targetPath?: string;
}

/**
 * Client-side redirect to home page or a specific deep link path.
 * Used in share pages to allow crawlers (X/Twitter, Farcaster) to read OG metadata
 * before redirecting users to the main app.
 */
export function RedirectToHome({ targetPath = "/" }: RedirectToHomeProps) {
  const router = useRouter();

  useEffect(() => {
    // Small delay to ensure metadata is readable by crawlers
    const timeout = setTimeout(() => {
      router.replace(targetPath);
    }, 100);

    return () => clearTimeout(timeout);
  }, [router, targetPath]);

  return null;
}
src/components/error-boundary.tsx
"use client";

import { Component, ReactNode } from "react";
import { Card, CardContent, P, Small, H4 } from "@neynar/ui";
import { createAppError } from "@/lib/error-codes";
import { WarningIcon, RefreshIcon } from "@/components/icons/net-library-icons";
import { createLogger } from "@/lib/logger";

interface ErrorBoundaryProps {
  children: ReactNode;
  fallback?: ReactNode;
  onError?: (error: Error, errorInfo: React.ErrorInfo) => void;
  /** Name of the section for error reporting */
  section?: string;
}

interface ErrorBoundaryState {
  hasError: boolean;
  error: Error | null;
  errorCode: string;
}

/**
 * Error boundary component that catches JavaScript errors in child components
 * and displays a fallback UI instead of crashing the whole app.
 */
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
  constructor(props: ErrorBoundaryProps) {
    super(props);
    this.state = { hasError: false, error: null, errorCode: "NL-0000" };
  }

  static getDerivedStateFromError(error: Error): ErrorBoundaryState {
    const appError = createAppError(error);
    return { hasError: true, error, errorCode: appError.code };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {
    const { onError, section } = this.props;

    // Log the error using structured logger
    const log = createLogger(section ? `ErrorBoundary:${section}` : "ErrorBoundary");
    log.error("Caught error", error);
    log.error("Component stack", errorInfo.componentStack);

    // Call optional error handler
    if (onError) {
      onError(error, errorInfo);
    }
  }

  handleRetry = () => {
    this.setState({ hasError: false, error: null, errorCode: "NL-0000" });
  };

  render() {
    const { children, fallback, section } = this.props;
    const { hasError, error, errorCode } = this.state;

    if (hasError) {
      // Custom fallback
      if (fallback) {
        return fallback;
      }

      // Default error UI
      return (
        <div className="p-4">
          <Card className="bg-red-500/10 border-2 border-red-500/30">
            <CardContent className="p-6 text-center">
              <div className="mb-4 flex justify-center"><WarningIcon size={40} className="text-red-400" /></div>
              <H4 className="text-red-400 font-mono mb-2">
                {section ? `Something went wrong in ${section}` : "Something went wrong"}
              </H4>
              <P className="text-gray-400 font-mono mb-4">
                {createAppError(error).message}
              </P>
              <Small className="text-gray-500 font-mono block mb-4">
                Error code: {errorCode}
              </Small>
              <button
                onClick={this.handleRetry}
                className="px-4 py-2 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg text-[#00ff00] font-mono hover:bg-[#00ff00]/20 transition-colors"
              >
                <RefreshIcon size={14} className="inline mr-1" /> Try Again
              </button>
            </CardContent>
          </Card>
        </div>
      );
    }

    return children;
  }
}

/**
 * Higher-order component to wrap a component with error boundary
 */
export function withErrorBoundary<P extends object>(
  Component: React.ComponentType<P>,
  section?: string
) {
  return function WrappedComponent(props: P) {
    return (
      <ErrorBoundary section={section}>
        <Component {...props} />
      </ErrorBoundary>
    );
  };
}
src/components/icons/net-library-icons.tsx
"use client";

/**
 * Net Library Brand Icons
 * Lucide-style icons (24x24 viewBox, 2px stroke, round linecaps)
 * Used throughout the app to replace emojis for a professional, branded look
 */

import { type SVGProps } from "react";

type IconProps = SVGProps<SVGSVGElement> & {
  size?: number;
};

const defaultProps = {
  viewBox: "0 0 24 24",
  fill: "none",
  stroke: "currentColor",
  strokeWidth: 2,
  strokeLinecap: "round" as const,
  strokeLinejoin: "round" as const,
};

// ============================================
// CONTENT TYPES
// ============================================

// 📄 Document/Text
export function DocumentIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <polyline points="14,2 14,8 20,8" />
      <line x1="16" y1="13" x2="8" y2="13" />
      <line x1="16" y1="17" x2="8" y2="17" />
      <polyline points="10,9 9,9 8,9" />
    </svg>
  );
}

// 🖼️ Image/Photo
export function ImageIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
      <circle cx="8.5" cy="8.5" r="1.5" />
      <polyline points="21,15 16,10 5,21" />
    </svg>
  );
}

// 🎵 Audio/Music
export function AudioIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M9 18V5l12-2v13" />
      <circle cx="6" cy="18" r="3" />
      <circle cx="18" cy="16" r="3" />
    </svg>
  );
}

// 🎬 Video
export function VideoIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="2" y="4" width="20" height="16" rx="2" />
      <polygon points="10,8 16,12 10,16" fill="currentColor" stroke="none" />
    </svg>
  );
}

// 🔗 Link
export function LinkIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
      <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
    </svg>
  );
}

// 📁 Folder
export function FolderIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z" />
    </svg>
  );
}

// 📦 Package/Archive
export function PackageIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <line x1="16.5" y1="9.4" x2="7.5" y2="4.21" />
      <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />
      <polyline points="3.27,6.96 12,12.01 20.73,6.96" />
      <line x1="12" y1="22.08" x2="12" y2="12" />
    </svg>
  );
}

// 📚 Library/Books
export function LibraryIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20" />
      <path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z" />
    </svg>
  );
}

// ============================================
// ACTIONS
// ============================================

// ⬆️ Upload
export function UploadIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
      <polyline points="17,8 12,3 7,8" />
      <line x1="12" y1="3" x2="12" y2="15" />
    </svg>
  );
}

// ⬇️ Download
export function DownloadIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
      <polyline points="7,10 12,15 17,10" />
      <line x1="12" y1="15" x2="12" y2="3" />
    </svg>
  );
}

// 🔄 Refresh/Sync
export function RefreshIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <polyline points="23,4 23,10 17,10" />
      <polyline points="1,20 1,14 7,14" />
      <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15" />
    </svg>
  );
}

// ➕ Add/Plus
export function AddIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <line x1="12" y1="5" x2="12" y2="19" />
      <line x1="5" y1="12" x2="19" y2="12" />
    </svg>
  );
}

// ✏️ Edit
export function EditIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
      <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
    </svg>
  );
}

// 🗑️ Delete/Trash
export function TrashIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <polyline points="3,6 5,6 21,6" />
      <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
    </svg>
  );
}

// 🔍 Search
export function SearchIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="11" cy="11" r="8" />
      <line x1="21" y1="21" x2="16.65" y2="16.65" />
    </svg>
  );
}

// 📋 Copy
export function CopyIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="9" y="9" width="13" height="13" rx="2" ry="2" />
      <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1" />
    </svg>
  );
}

// 📤 Share/Send (three connected circles - alternative share style)
export function ShareNetworkIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="18" cy="5" r="3" />
      <circle cx="6" cy="12" r="3" />
      <circle cx="18" cy="19" r="3" />
      <line x1="8.59" y1="13.51" x2="15.42" y2="17.49" />
      <line x1="15.41" y1="6.51" x2="8.59" y2="10.49" />
    </svg>
  );
}

// ============================================
// STATUS & FEEDBACK
// ============================================

// ✅ Success/Check
export function CheckIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <polyline points="20,6 9,17 4,12" />
    </svg>
  );
}

// ✅ Success Circle
export function CheckCircleIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M22 11.08V12a10 10 0 1 1-5.93-9.14" />
      <polyline points="22,4 12,14.01 9,11.01" />
    </svg>
  );
}

// ❌ Error/Close
export function CloseIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <line x1="18" y1="6" x2="6" y2="18" />
      <line x1="6" y1="6" x2="18" y2="18" />
    </svg>
  );
}

// ⚠️ Warning
export function WarningIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
      <line x1="12" y1="9" x2="12" y2="13" />
      <line x1="12" y1="17" x2="12.01" y2="17" />
    </svg>
  );
}

// ℹ️ Info
export function InfoIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="12" cy="12" r="10" />
      <line x1="12" y1="16" x2="12" y2="12" />
      <line x1="12" y1="8" x2="12.01" y2="8" />
    </svg>
  );
}

// 🚫 Banned/Prohibited
export function BanIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="12" cy="12" r="10" />
      <line x1="4.93" y1="4.93" x2="19.07" y2="19.07" />
    </svg>
  );
}

// ❌ X Circle (error in circle)
export function XCircleIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="12" cy="12" r="10" />
      <line x1="15" y1="9" x2="9" y2="15" />
      <line x1="9" y1="9" x2="15" y2="15" />
    </svg>
  );
}

// 🌱 Seedling/Growth
export function SeedlingIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M7 20h10" />
      <path d="M10 20c5.5-2.5.8-6.4 3-10" />
      <path d="M9.5 9.4c1.1.8 1.8 2.2 2.3 3.7-2 .4-3.5.4-4.8-.3-1.2-.6-2.3-1.9-3-4.2 2.8-.5 4.4 0 5.5.8z" />
      <path d="M14.1 6a7 7 0 0 0-1.1 4c1.9-.1 3.3-.6 4.3-1.4 1-1 1.6-2.3 1.7-4.6-2.7.1-4 1-4.9 2z" />
    </svg>
  );
}

// 📋 Clipboard
export function ClipboardIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2" />
      <rect x="8" y="2" width="8" height="4" rx="1" ry="1" />
    </svg>
  );
}

// ⏳ Loading/Pending
export function LoadingIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="12" cy="12" r="10" />
      <polyline points="12,6 12,12 16,14" />
    </svg>
  );
}

// 🔔 Notification
export function BellIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9" />
      <path d="M13.73 21a2 2 0 0 1-3.46 0" />
    </svg>
  );
}

// 🎉 Celebration/Party
export function PartyIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <polygon points="12,2 15.09,8.26 22,9.27 17,14.14 18.18,21.02 12,17.77 5.82,21.02 7,14.14 2,9.27 8.91,8.26" />
    </svg>
  );
}

// ============================================
// ORGANIZATION
// ============================================

// 📊 Stats/Chart
export function ChartIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <line x1="18" y1="20" x2="18" y2="10" />
      <line x1="12" y1="20" x2="12" y2="4" />
      <line x1="6" y1="20" x2="6" y2="14" />
    </svg>
  );
}

// 📋 List
export function ListIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <line x1="8" y1="6" x2="21" y2="6" />
      <line x1="8" y1="12" x2="21" y2="12" />
      <line x1="8" y1="18" x2="21" y2="18" />
      <line x1="3" y1="6" x2="3.01" y2="6" />
      <line x1="3" y1="12" x2="3.01" y2="12" />
      <line x1="3" y1="18" x2="3.01" y2="18" />
    </svg>
  );
}

// 🏷️ Tag/Label
export function TagIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M20.59 13.41l-7.17 7.17a2 2 0 0 1-2.83 0L2 12V2h10l8.59 8.59a2 2 0 0 1 0 2.82z" />
      <line x1="7" y1="7" x2="7.01" y2="7" />
    </svg>
  );
}

// 📅 Calendar
export function CalendarIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
      <line x1="16" y1="2" x2="16" y2="6" />
      <line x1="8" y1="2" x2="8" y2="6" />
      <line x1="3" y1="10" x2="21" y2="10" />
    </svg>
  );
}

// 🗂️ Archive
export function ArchiveIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <polyline points="21,8 21,21 3,21 3,8" />
      <rect x="1" y="3" width="22" height="5" />
      <line x1="10" y1="12" x2="14" y2="12" />
    </svg>
  );
}

// ⭐ Star/Favorite
export function StarIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <polygon points="12,2 15.09,8.26 22,9.27 17,14.14 18.18,21.02 12,17.77 5.82,21.02 7,14.14 2,9.27 8.91,8.26" />
    </svg>
  );
}

// 🔖 Bookmark
export function BookmarkIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z" />
    </svg>
  );
}

// ============================================
// USERS & SOCIAL
// ============================================

// 👤 User
export function UserIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
      <circle cx="12" cy="7" r="4" />
    </svg>
  );
}

// 👥 Users/Group
export function UsersIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2" />
      <circle cx="9" cy="7" r="4" />
      <path d="M23 21v-2a4 4 0 0 0-3-3.87" />
      <path d="M16 3.13a4 4 0 0 1 0 7.75" />
    </svg>
  );
}

// 💬 Chat/Message
export function ChatIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
    </svg>
  );
}

// 💬 Message (alias for ChatIcon)
export const MessageIcon = ChatIcon;

// ❤️ Heart/Like
export function HeartIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
    </svg>
  );
}

// 🌐 Globe/World
export function GlobeIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="12" cy="12" r="10" />
      <line x1="2" y1="12" x2="22" y2="12" />
      <path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" />
    </svg>
  );
}

// ============================================
// FINANCE & TRANSACTIONS
// ============================================

// 💰 Money/Wallet
export function WalletIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="1" y="4" width="22" height="16" rx="2" ry="2" />
      <line x1="1" y1="10" x2="23" y2="10" />
      <circle cx="18" cy="15" r="1" fill="currentColor" />
    </svg>
  );
}

// 💳 Credit Card
export function CreditCardIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="1" y="4" width="22" height="16" rx="2" ry="2" />
      <line x1="1" y1="10" x2="23" y2="10" />
    </svg>
  );
}

// 💵 Dollar/Currency
export function DollarIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <line x1="12" y1="1" x2="12" y2="23" />
      <path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6" />
    </svg>
  );
}

// 🧾 Receipt
export function ReceiptIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1-2-1z" />
      <line x1="8" y1="8" x2="16" y2="8" />
      <line x1="8" y1="12" x2="16" y2="12" />
      <line x1="8" y1="16" x2="12" y2="16" />
    </svg>
  );
}

// ⛽ Gas/Fuel
export function GasIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M3 22V6a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16" />
      <rect x="5" y="8" width="8" height="5" />
      <path d="M15 10h2a2 2 0 0 1 2 2v5a2 2 0 0 0 2 2h0a2 2 0 0 0 2-2V8l-3-3" />
    </svg>
  );
}

// ============================================
// NAVIGATION & UI
// ============================================

// ⚙️ Settings/Gear
export function SettingsIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="12" cy="12" r="3" />
      <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z" />
    </svg>
  );
}

// 🏠 Home
export function HomeIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
      <polyline points="9,22 9,12 15,12 15,22" />
    </svg>
  );
}

// 🔲 Grid
export function GridIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="3" y="3" width="7" height="7" />
      <rect x="14" y="3" width="7" height="7" />
      <rect x="14" y="14" width="7" height="7" />
      <rect x="3" y="14" width="7" height="7" />
    </svg>
  );
}

// ◀️ Back/Left Arrow
export function ArrowLeftIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <line x1="19" y1="12" x2="5" y2="12" />
      <polyline points="12,19 5,12 12,5" />
    </svg>
  );
}

// ▶️ Forward/Right Arrow
export function ArrowRightIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <line x1="5" y1="12" x2="19" y2="12" />
      <polyline points="12,5 19,12 12,19" />
    </svg>
  );
}

// 🔽 Down Arrow/Expand
export function ChevronDownIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <polyline points="6,9 12,15 18,9" />
    </svg>
  );
}

// 🔼 Up Arrow/Collapse
export function ChevronUpIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <polyline points="18,15 12,9 6,15" />
    </svg>
  );
}

// ⋮ More/Menu
export function MoreIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="12" cy="12" r="1" fill="currentColor" />
      <circle cx="12" cy="5" r="1" fill="currentColor" />
      <circle cx="12" cy="19" r="1" fill="currentColor" />
    </svg>
  );
}

// 📱 Phone/Mobile
export function PhoneIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="5" y="2" width="14" height="20" rx="2" ry="2" />
      <line x1="12" y1="18" x2="12.01" y2="18" />
    </svg>
  );
}

// 🖥️ Desktop/Monitor
export function MonitorIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
      <line x1="8" y1="21" x2="16" y2="21" />
      <line x1="12" y1="17" x2="12" y2="21" />
    </svg>
  );
}

// ============================================
// PLATFORM INDICATORS
// ============================================

// 🟣 Farcaster logo (the distinctive frame/window shape)
export function FarcasterIcon({ size = 24, className = "", ...props }: IconProps & { className?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 1000 1000" fill="none" className={className} {...props}>
      <path d="M257.778 155.556H742.222V844.445H671.111V528.889H670.414C662.554 441.677 589.258 373.333 500 373.333C410.742 373.333 337.446 441.677 329.586 528.889H328.889V844.445H257.778V155.556Z" fill="currentColor"/>
      <path d="M128.889 253.333L157.778 351.111H182.222V746.667C169.949 746.667 160 756.616 160 768.889V795.556H155.556C143.283 795.556 133.333 805.505 133.333 817.778V844.445H382.222V817.778C382.222 805.505 372.273 795.556 360 795.556H355.556V768.889C355.556 756.616 345.606 746.667 333.333 746.667H306.667V253.333H128.889Z" fill="currentColor"/>
      <path d="M675.556 746.667C663.283 746.667 653.333 756.616 653.333 768.889V795.556H648.889C636.616 795.556 626.667 805.505 626.667 817.778V844.445H875.556V817.778C875.556 805.505 865.606 795.556 853.333 795.556H848.889V768.889C848.889 756.616 838.94 746.667 826.667 746.667V351.111H851.111L880 253.333H702.222V746.667H675.556Z" fill="currentColor"/>
    </svg>
  );
}

// 🟣 Farcaster indicator (purple - alias for backwards compat)
export function FarcasterIndicator({ size = 24, ...props }: IconProps) {
  return <FarcasterIcon size={size} className="text-purple-400" {...props} />;
}

// 🔵 Base logo (blue rounded square - the official Base brand symbol)
export function BaseIcon({ size = 24, className = "", ...props }: IconProps & { className?: string }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="none" className={className} {...props}>
      <rect x="2" y="2" width="20" height="20" rx="4" />
    </svg>
  );
}

// 🌐 Web/Browser indicator (alias for BrowserIcon for platform context)
export function WebIcon({ size = 24, className = "", ...props }: IconProps & { className?: string }) {
  return <BrowserIcon size={size} className={className} {...props} />;
}

// ⬡ Blockchain/Onchain
export function BlockchainIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M12 2L2 7l10 5 10-5-10-5z" />
      <path d="M2 17l10 5 10-5" />
      <path d="M2 12l10 5 10-5" />
    </svg>
  );
}

// ============================================
// MISC
// ============================================

// ⚡ Lightning/Fast
export function LightningIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <polygon points="13,2 3,14 12,14 11,22 21,10 12,10" />
    </svg>
  );
}

// 🔒 Lock/Secure
export function LockIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
      <path d="M7 11V7a5 5 0 0 1 10 0v4" />
    </svg>
  );
}

// 🔓 Unlock
export function UnlockIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="3" y="11" width="18" height="11" rx="2" ry="2" />
      <path d="M7 11V7a5 5 0 0 1 9.9-1" />
    </svg>
  );
}

// 🌙 Moon/Dark
export function MoonIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
    </svg>
  );
}

// ☀️ Sun/Light
export function SunIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="12" cy="12" r="5" />
      <line x1="12" y1="1" x2="12" y2="3" />
      <line x1="12" y1="21" x2="12" y2="23" />
      <line x1="4.22" y1="4.22" x2="5.64" y2="5.64" />
      <line x1="18.36" y1="18.36" x2="19.78" y2="19.78" />
      <line x1="1" y1="12" x2="3" y2="12" />
      <line x1="21" y1="12" x2="23" y2="12" />
      <line x1="4.22" y1="19.78" x2="5.64" y2="18.36" />
      <line x1="18.36" y1="5.64" x2="19.78" y2="4.22" />
    </svg>
  );
}

// 🎲 Random/Dice
export function DiceIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
      <circle cx="8" cy="8" r="1" fill="currentColor" />
      <circle cx="16" cy="8" r="1" fill="currentColor" />
      <circle cx="12" cy="12" r="1" fill="currentColor" />
      <circle cx="8" cy="16" r="1" fill="currentColor" />
      <circle cx="16" cy="16" r="1" fill="currentColor" />
    </svg>
  );
}

// 🎯 Target/Goal
export function TargetIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="12" cy="12" r="10" />
      <circle cx="12" cy="12" r="6" />
      <circle cx="12" cy="12" r="2" />
    </svg>
  );
}

// 🔗 External Link
export function ExternalLinkIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
      <polyline points="15,3 21,3 21,9" />
      <line x1="10" y1="14" x2="21" y2="3" />
    </svg>
  );
}

// ↗️ Share (diagonal arrow - universal share icon)
export function ShareIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <polyline points="15 3 21 3 21 9" />
      <line x1="10" y1="14" x2="21" y2="3" />
    </svg>
  );
}

// 📶 Signal/Connection
export function SignalIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M5 12.55a11 11 0 0 1 14.08 0" />
      <path d="M1.42 9a16 16 0 0 1 21.16 0" />
      <path d="M8.53 16.11a6 6 0 0 1 6.95 0" />
      <line x1="12" y1="20" x2="12.01" y2="20" />
    </svg>
  );
}

// 🔧 Wrench/Tool
export function WrenchIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z" />
    </svg>
  );
}

// 🏆 Trophy
export function TrophyIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6" />
      <path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18" />
      <path d="M4 22h16" />
      <path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22" />
      <path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22" />
      <path d="M18 2H6v7a6 6 0 0 0 12 0V2Z" />
    </svg>
  );
}

// 🏃 Activity/Running
export function ActivityIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <polyline points="22,12 18,12 15,21 9,3 6,12 2,12" />
    </svg>
  );
}

// 📍 Pin/Location
export function PinIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z" />
      <circle cx="12" cy="10" r="3" />
    </svg>
  );
}

// 🎨 Palette/Theme
export function PaletteIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="13.5" cy="6.5" r="0.5" fill="currentColor" />
      <circle cx="17.5" cy="10.5" r="0.5" fill="currentColor" />
      <circle cx="8.5" cy="7.5" r="0.5" fill="currentColor" />
      <circle cx="6.5" cy="12.5" r="0.5" fill="currentColor" />
      <path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.555C21.965 6.012 17.461 2 12 2z" />
    </svg>
  );
}

// 🧪 Test/Experiment
export function FlaskIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M9 3h6" />
      <path d="M10 9V3" />
      <path d="M14 9V3" />
      <path d="M17.5 21H6.5a1 1 0 0 1-.83-1.55l5.08-7.63A1 1 0 0 0 11 11V9h2v2a1 1 0 0 0 .25.66l5.08 7.63a1 1 0 0 1-.83 1.55z" />
    </svg>
  );
}

// 💡 Lightbulb (tip, idea)
export function LightbulbIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5" />
      <path d="M9 18h6" />
      <path d="M10 22h4" />
    </svg>
  );
}

// ✏️ Pencil (edit, write)
export function PencilIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M17 3a2.83 2.83 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5Z" />
      <path d="m15 5 4 4" />
    </svg>
  );
}

// 👁️ Eye (visible)
export function EyeIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z" />
      <circle cx="12" cy="12" r="3" />
    </svg>
  );
}

// 🙈 Eye Off (hidden)
export function EyeOffIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24" />
      <line x1="1" y1="1" x2="23" y2="23" />
    </svg>
  );
}

// ⏱️ Clock (time, timer, expiration)
export function ClockIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="12" cy="12" r="10" />
      <polyline points="12 6 12 12 16 14" />
    </svg>
  );
}

// 💾 Save/Floppy Disk
export function SaveIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
      <polyline points="17 21 17 13 7 13 7 21" />
      <polyline points="7 3 7 8 15 8" />
    </svg>
  );
}

// 🪂 Parachute/Airdrop
export function ParachuteIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M12 2C6.5 2 2 6 2 10c0 1.5.5 2.9 1.4 4L12 22l8.6-8c.9-1.1 1.4-2.5 1.4-4 0-4-4.5-8-10-8z" />
      <line x1="4" y1="10" x2="12" y2="22" />
      <line x1="20" y1="10" x2="12" y2="22" />
      <line x1="12" y1="10" x2="12" y2="22" />
      <path d="M5 10c0-4 3-7 7-7s7 3 7 7" />
    </svg>
  );
}

// 📇 Contact Book/Directory
export function ContactBookIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="4" y="2" width="16" height="20" rx="2" />
      <line x1="8" y1="6" x2="8" y2="6.01" />
      <line x1="8" y1="10" x2="8" y2="10.01" />
      <line x1="8" y1="14" x2="8" y2="14.01" />
      <line x1="8" y1="18" x2="8" y2="18.01" />
      <circle cx="14" cy="8" r="2" />
      <path d="M14 12c-2 0-3 1-3 2v1h6v-1c0-1-1-2-3-2z" />
    </svg>
  );
}

// 📭 Empty Inbox/Mailbox
export function InboxEmptyIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <polyline points="22 12 16 12 14 15 10 15 8 12 2 12" />
      <path d="M5.45 5.11L2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z" />
    </svg>
  );
}

// 📝 Text File / Note
export function NoteIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
      <polyline points="14 2 14 8 20 8" />
      <line x1="16" y1="13" x2="8" y2="13" />
      <line x1="16" y1="17" x2="8" y2="17" />
    </svg>
  );
}

// 🔥 Flame/Trending/Hot
export function FlameIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z" />
    </svg>
  );
}

// 💵 Dollar Bill / Money
export function DollarBillIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="2" y="6" width="20" height="12" rx="2" />
      <circle cx="12" cy="12" r="3" />
      <path d="M6 12h.01M18 12h.01" />
    </svg>
  );
}

// 🚦 Traffic Light / Rate Limit
export function TrafficLightIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="6" y="2" width="12" height="20" rx="2" />
      <circle cx="12" cy="7" r="2" />
      <circle cx="12" cy="12" r="2" />
      <circle cx="12" cy="17" r="2" />
    </svg>
  );
}

// ↩️ Undo / Return
export function UndoIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M3 7v6h6" />
      <path d="M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13" />
    </svg>
  );
}

// ↪️ Redo / Forward
export function RedoIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M21 7v6h-6" />
      <path d="M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7" />
    </svg>
  );
}

// 👆 Pointer / Select
export function PointerIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M22 14a8 8 0 0 1-8 8" />
      <path d="M18 11v-1a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v0" />
      <path d="M14 10V9a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v1" />
      <path d="M10 9.5V4a2 2 0 0 0-2-2v0a2 2 0 0 0-2 2v10" />
      <path d="M18 11a2 2 0 1 1 4 0v3a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15" />
    </svg>
  );
}

// 🖌️ Brush / Paint
export function BrushIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M9.06 11.9l8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08" />
      <path d="M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z" />
    </svg>
  );
}

// 🧹 Eraser
export function EraserIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M7 21h10" />
      <path d="M5.7 15.3 13 8l4 4-7.3 7.3a2.83 2.83 0 0 1-4 0v0a2.83 2.83 0 0 1 0-4Z" />
      <path d="m17 4 4 4-1.8 1.8" />
    </svg>
  );
}

// 🔤 Text / Type
export function TypeIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <polyline points="4 7 4 4 20 4 20 7" />
      <line x1="9" y1="20" x2="15" y2="20" />
      <line x1="12" y1="4" x2="12" y2="20" />
    </svg>
  );
}

// 😀 Smile / Emoji
export function SmileIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="12" cy="12" r="10" />
      <path d="M8 14s1.5 2 4 2 4-2 4-2" />
      <line x1="9" y1="9" x2="9.01" y2="9" />
      <line x1="15" y1="9" x2="15.01" y2="9" />
    </svg>
  );
}

// 📷 Camera
export function CameraIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z" />
      <circle cx="12" cy="13" r="3" />
    </svg>
  );
}

// 🐸 Frog / Meme
export function FrogIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="8" cy="8" r="2" />
      <circle cx="16" cy="8" r="2" />
      <path d="M9 14c.5 1 1.5 2 3 2s2.5-1 3-2" />
      <path d="M12 20c-4 0-8-2-8-8a8 8 0 0 1 16 0c0 6-4 8-8 8z" />
    </svg>
  );
}

// 🎯 Crosshair / Target (nudge)
export function CrosshairIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="12" cy="12" r="10" />
      <line x1="22" y1="12" x2="18" y2="12" />
      <line x1="6" y1="12" x2="2" y2="12" />
      <line x1="12" y1="6" x2="12" y2="2" />
      <line x1="12" y1="22" x2="12" y2="18" />
    </svg>
  );
}

// 🔍 Zoom / Magnify (already have SearchIcon, this is for zoom specifically)
export function ZoomIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="11" cy="11" r="8" />
      <line x1="21" y1="21" x2="16.65" y2="16.65" />
      <line x1="11" y1="8" x2="11" y2="14" />
      <line x1="8" y1="11" x2="14" y2="11" />
    </svg>
  );
}

// 🧲 Magnet / Snap
export function MagnetIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M6 15V9a6 6 0 0 1 12 0v6" />
      <path d="M6 9H3v6h3" />
      <path d="M18 9h3v6h-3" />
    </svg>
  );
}

// 📐 Ruler / Resize
export function RulerIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M21.3 8.7 8.7 21.3c-1 1-2.5 1-3.4 0l-2.6-2.6c-1-1-1-2.5 0-3.4L15.3 2.7c1-1 2.5-1 3.4 0l2.6 2.6c1 1 1 2.5 0 3.4Z" />
      <path d="m7.5 10.5 2 2" />
      <path d="m10.5 7.5 2 2" />
      <path d="m13.5 4.5 2 2" />
      <path d="m4.5 13.5 2 2" />
    </svg>
  );
}

// 📚 Layers / Stack
export function LayersIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <polygon points="12 2 2 7 12 12 22 7 12 2" />
      <polyline points="2 17 12 22 22 17" />
      <polyline points="2 12 12 17 22 12" />
    </svg>
  );
}

// 🏁 Checkered Flag / Transparent
export function CheckeredIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="3" y="3" width="18" height="18" rx="2" />
      <rect x="3" y="3" width="9" height="9" fill="currentColor" fillOpacity="0.3" stroke="none" />
      <rect x="12" y="12" width="9" height="9" fill="currentColor" fillOpacity="0.3" stroke="none" />
    </svg>
  );
}

// ============================================
// ARROWS & DIRECTIONAL
// ============================================

// ⬆️ Arrow Up
export function ArrowUpIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M12 19V5" />
      <path d="M5 12l7-7 7 7" />
    </svg>
  );
}

// ⬇️ Arrow Down
export function ArrowDownIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M12 5v14" />
      <path d="M19 12l-7 7-7-7" />
    </svg>
  );
}

// ↔️ Horizontal / Width
export function ArrowHorizontalIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M21 12H3" />
      <path d="M15 6l6 6-6 6" />
      <path d="M9 6l-6 6 6 6" />
    </svg>
  );
}

// ↕️ Vertical / Height
export function ArrowVerticalIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M12 3v18" />
      <path d="M6 9l6-6 6 6" />
      <path d="M6 15l6 6 6-6" />
    </svg>
  );
}

// ↺ Rotate Counter-Clockwise
export function RotateCcwIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
      <path d="M3 3v5h5" />
    </svg>
  );
}

// ↻ Rotate Clockwise
export function RotateCwIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M21 12a9 9 0 1 1-9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" />
      <path d="M21 3v5h-5" />
    </svg>
  );
}

// Bring to Front / Forward
export function BringForwardIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="8" y="8" width="13" height="13" rx="2" />
      <path d="M4 16V6a2 2 0 0 1 2-2h10" />
    </svg>
  );
}

// Send to Back / Backward
export function SendBackwardIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="3" y="3" width="13" height="13" rx="2" />
      <path d="M21 8v10a2 2 0 0 1-2 2H9" />
    </svg>
  );
}

// Align Left
export function AlignLeftIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <line x1="3" y1="3" x2="3" y2="21" />
      <rect x="7" y="6" width="14" height="4" rx="1" />
      <rect x="7" y="14" width="8" height="4" rx="1" />
    </svg>
  );
}

// Align Center Horizontal
export function AlignCenterHIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <line x1="12" y1="3" x2="12" y2="21" />
      <rect x="5" y="6" width="14" height="4" rx="1" />
      <rect x="7" y="14" width="10" height="4" rx="1" />
    </svg>
  );
}

// Align Right
export function AlignRightIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <line x1="21" y1="3" x2="21" y2="21" />
      <rect x="3" y="6" width="14" height="4" rx="1" />
      <rect x="9" y="14" width="8" height="4" rx="1" />
    </svg>
  );
}

// Align Top
export function AlignTopIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <line x1="3" y1="3" x2="21" y2="3" />
      <rect x="6" y="7" width="4" height="14" rx="1" />
      <rect x="14" y="7" width="4" height="8" rx="1" />
    </svg>
  );
}

// Align Center Vertical
export function AlignCenterVIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <line x1="3" y1="12" x2="21" y2="12" />
      <rect x="6" y="5" width="4" height="14" rx="1" />
      <rect x="14" y="7" width="4" height="10" rx="1" />
    </svg>
  );
}

// Align Bottom
export function AlignBottomIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <line x1="3" y1="21" x2="21" y2="21" />
      <rect x="6" y="3" width="4" height="14" rx="1" />
      <rect x="14" y="9" width="4" height="8" rx="1" />
    </svg>
  );
}

// ============================================
// MEDIA CONTROLS
// ============================================

// ▶️ Play
export function PlayIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="none" {...props}>
      <path d="M8 5.14v13.72c0 .86.98 1.36 1.68.86l9.02-6.86c.58-.44.58-1.28 0-1.72L9.68 4.28C8.98 3.78 8 4.28 8 5.14z" />
    </svg>
  );
}

// ⏸️ Pause
export function PauseIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="none" {...props}>
      <rect x="6" y="4" width="4" height="16" rx="1" />
      <rect x="14" y="4" width="4" height="16" rx="1" />
    </svg>
  );
}

// ⏹️ Stop
export function StopIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="none" {...props}>
      <rect x="4" y="4" width="16" height="16" rx="2" />
    </svg>
  );
}

// ⏭️ Skip Forward
export function SkipForwardIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="none" {...props}>
      <path d="M5 4.99v14.02c0 .67.77 1.05 1.32.66l8.18-6.04c.47-.35.47-1.05 0-1.4l-8.18-5.9C5.77 3.94 5 4.32 5 4.99z" />
      <rect x="17" y="5" width="3" height="14" rx="1" />
    </svg>
  );
}

// ⏮️ Skip Back
export function SkipBackIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="none" {...props}>
      <path d="M19 19.01V4.99c0-.67-.77-1.05-1.32-.66l-8.18 6.04c-.47.35-.47 1.05 0 1.4l8.18 5.9c.55.39 1.32.01 1.32-.66z" />
      <rect x="4" y="5" width="3" height="14" rx="1" />
    </svg>
  );
}

// ============================================
// ACHIEVEMENTS & BADGES
// ============================================

// 🏅 Medal/Achievement
export function MedalIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="12" cy="8" r="6" />
      <path d="M15.477 12.89 17 22l-5-3-5 3 1.523-9.11" />
    </svg>
  );
}

// 🏆 Trophy (already exists but adding alias)
export function AwardIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <circle cx="12" cy="8" r="6" />
      <path d="M15.477 12.89 17 22l-5-3-5 3 1.523-9.11" />
    </svg>
  );
}

// ⭐ Star (filled version for achievements)
export function StarFilledIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="none" {...props}>
      <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
    </svg>
  );
}

// 🚀 Rocket/Launch
export function RocketIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z" />
      <path d="M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z" />
      <path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0" />
      <path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5" />
    </svg>
  );
}

// 👑 Crown
export function CrownIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M2 4l3 12h14l3-12-6 7-4-7-4 7-6-7z" />
      <path d="M3 20h18" />
    </svg>
  );
}

// 💎 Gem/Diamond
export function GemIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M6 3h12l4 6-10 13L2 9z" />
      <path d="M2 9h20" />
      <path d="M12 22V9" />
      <path d="M6 3l6 6 6-6" />
    </svg>
  );
}

// 🔥 Flame (already exists)

// 🌟 Sparkle/Shine
export function SparkleIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M12 3v4m0 10v4M3 12h4m10 0h4" />
      <path d="M5.6 5.6l2.8 2.8m7.2 7.2l2.8 2.8M5.6 18.4l2.8-2.8m7.2-7.2l2.8-2.8" />
    </svg>
  );
}

// 📊 Chart/Stats (for leaderboard achievements)
export function ChartBarIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="3" y="12" width="4" height="9" rx="1" />
      <rect x="10" y="8" width="4" height="13" rx="1" />
      <rect x="17" y="3" width="4" height="18" rx="1" />
    </svg>
  );
}

// 📚 Stack of Books (for collection achievements)
export function BookStackIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20" />
      <path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z" />
      <path d="M8 7h8" />
      <path d="M8 11h6" />
    </svg>
  );
}

// 🤝 Handshake
export function HandshakeIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="m11 17 2 2a1 1 0 1 0 3-3" />
      <path d="m14 14 2.5 2.5a1 1 0 1 0 3-3l-3.88-3.88a3 3 0 0 0-4.24 0l-.88.88a1 1 0 1 1-3-3l2.81-2.81a5.79 5.79 0 0 1 7.06-.87l.47.28a2 2 0 0 0 1.42.25L21 4" />
      <path d="m21 3 1 11h-2" />
      <path d="M3 3 2 14l6.5 6.5a1 1 0 1 0 3-3" />
      <path d="M3 4h8" />
    </svg>
  );
}

// 🧩 Widget/Puzzle Piece
export function WidgetIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="3" y="3" width="7" height="7" rx="1" />
      <rect x="14" y="3" width="7" height="7" rx="1" />
      <rect x="3" y="14" width="7" height="7" rx="1" />
      <rect x="14" y="14" width="7" height="7" rx="1" />
    </svg>
  );
}

// 🌐 Browser/Web
export function BrowserIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="3" y="3" width="18" height="18" rx="2" />
      <path d="M3 9h18" />
      <path d="M9 21V9" />
    </svg>
  );
}

// 📤 Upload (already exists, but alias)
export function ExportIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
      <polyline points="17 8 12 3 7 8" />
      <line x1="12" y1="3" x2="12" y2="15" />
    </svg>
  );
}

// 💵 Money/Dollar
export function MoneyIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="2" y="6" width="20" height="12" rx="2" />
      <circle cx="12" cy="12" r="3" />
      <path d="M2 10h2" />
      <path d="M20 10h2" />
      <path d="M2 14h2" />
      <path d="M20 14h2" />
    </svg>
  );
}

// 📱 Smartphone/Mobile
export function SmartphoneIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} {...defaultProps} {...props}>
      <rect x="5" y="2" width="14" height="20" rx="2" ry="2" />
      <line x1="12" y1="18" x2="12.01" y2="18" />
    </svg>
  );
}

// 🔵 Blue circle (Base platform indicator) - filled version
export function CircleFilledIcon({ size = 24, ...props }: IconProps) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="none" {...props}>
      <circle cx="12" cy="12" r="10" />
    </svg>
  );
}

src/components/sketch/index.ts
export { SketchButton } from "./sketch-button";
export { SketchCard } from "./sketch-card";
export { SketchHeading } from "./sketch-heading";
export { SketchInput } from "./sketch-input";
export { SketchTextarea } from "./sketch-textarea";
export { SketchFilters } from "./sketch-filters";
export { SketchDemo } from "./sketch-demo";
export { SketchMiniLayout } from "./sketch-mini-layout";
src/components/sketch/sketch-button.tsx
import { ButtonHTMLAttributes, ReactNode } from "react";

interface SketchButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  children: ReactNode;
  variant?: "default" | "heavy";
}

export function SketchButton({
  children,
  variant = "default",
  className = "",
  ...props
}: SketchButtonProps) {
  const baseClass =
    variant === "heavy" ? "sketch-button sketch-border-heavy" : "sketch-button";

  return (
    <button
      className={`${baseClass} ${className} px-6 py-3 text-lg`}
      {...props}
    >
      {children}
    </button>
  );
}
src/components/sketch/sketch-card.tsx
import { ComponentPropsWithoutRef } from "react";

interface SketchCardProps extends ComponentPropsWithoutRef<"div"> {
  padding?: "sm" | "md" | "lg";
}

export function SketchCard({
  children,
  className = "",
  padding = "md",
  ...props
}: SketchCardProps) {
  const paddingClasses = {
    sm: "p-4",
    md: "p-6",
    lg: "p-8",
  };

  return (
    <div
      className={`sketch-card ${paddingClasses[padding]} ${className}`}
      {...props}
    >
      {children}
    </div>
  );
}
src/components/sketch/sketch-demo.tsx
"use client";

import { useState } from "react";
import { SketchButton } from "./sketch-button";
import { SketchCard } from "./sketch-card";
import { SketchHeading } from "./sketch-heading";
import { SketchInput } from "./sketch-input";
import { SketchTextarea } from "./sketch-textarea";
import { SketchFilters } from "./sketch-filters";

export function SketchDemo() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState("");
  const [message, setMessage] = useState("");

  return (
    <>
      <SketchFilters />
      <div className="min-h-screen sketch-paper p-4 md:p-8">
        <div className="max-w-4xl mx-auto space-y-8">
          <SketchCard padding="lg">
            <SketchHeading level={1} underline>
              Sketch Components Demo
            </SketchHeading>
            <p className="sketch-text text-xl mt-4">
              Hand-drawn wireframe components for rapid prototyping! 📝
            </p>
          </SketchCard>

          <SketchCard>
            <SketchHeading level={2} scribble>
              Interactive Counter
            </SketchHeading>

            <div className="mt-6 flex items-center gap-4">
              <SketchButton onClick={() => setCount(count - 1)}>-</SketchButton>
              <div className="sketch-border px-8 py-4">
                <span className="sketch-text text-3xl font-bold">{count}</span>
              </div>
              <SketchButton onClick={() => setCount(count + 1)}>+</SketchButton>
            </div>

            <div className="mt-4">
              <SketchButton
                variant="heavy"
                onClick={() => setCount(0)}
                className="w-full"
              >
                Reset Counter
              </SketchButton>
            </div>
          </SketchCard>

          <SketchCard>
            <SketchHeading level={2} highlight>
              Contact Form
            </SketchHeading>

            <div className="mt-6 space-y-4">
              <SketchInput
                label="Your Name"
                placeholder="John Doe"
                value={name}
                onChange={(e) => setName(e.target.value)}
              />

              <SketchTextarea
                label="Your Message"
                placeholder="Type your message here..."
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                rows={5}
              />

              <SketchButton
                onClick={() => {
                  if (name && message) {
                    alert(`Thanks ${name}! We got your message: "${message}"`);
                    setName("");
                    setMessage("");
                  } else {
                    alert("Please fill out all fields!");
                  }
                }}
                className="w-full"
              >
                Send Message
              </SketchButton>
            </div>
          </SketchCard>

          <SketchCard>
            <SketchHeading level={2}>Text Decorations</SketchHeading>

            <div className="mt-6 space-y-4">
              <div>
                <SketchHeading level={3} underline>
                  Underlined Heading
                </SketchHeading>
              </div>

              <div>
                <SketchHeading level={3} scribble>
                  Scribbled Heading
                </SketchHeading>
              </div>

              <div>
                <SketchHeading level={3} highlight>
                  Highlighted Heading
                </SketchHeading>
              </div>

              <p className="sketch-text text-lg">
                Mix and match with{" "}
                <span className="sketch-highlight">highlighted text</span> and{" "}
                <span className="sketch-underline">underlined phrases</span>!
              </p>
            </div>
          </SketchCard>

          <SketchCard>
            <SketchHeading level={2}>Button Variants</SketchHeading>

            <div className="mt-6 flex flex-wrap gap-4">
              <SketchButton onClick={() => alert("Default!")}>
                Default
              </SketchButton>
              <SketchButton variant="heavy" onClick={() => alert("Heavy!")}>
                Heavy Border
              </SketchButton>
              <SketchButton
                className="bg-blue-200"
                onClick={() => alert("Custom!")}
              >
                Custom Color
              </SketchButton>
            </div>
          </SketchCard>

          <SketchCard>
            <SketchHeading level={2}>Intensity Levels</SketchHeading>

            <div className="mt-6 space-y-6">
              <div className="sketch-light p-4 border-2 border-black bg-white">
                <p className="sketch-text text-lg">
                  Light sketch effect - subtle wobble
                </p>
              </div>

              <div className="sketch-medium p-4 border-2 border-black bg-white">
                <p className="sketch-text text-lg">
                  Medium sketch effect - more wobbly
                </p>
              </div>

              <div className="sketch-heavy p-4 border-2 border-black bg-white">
                <p className="sketch-text text-lg">
                  Heavy sketch effect - very hand-drawn!
                </p>
              </div>
            </div>
          </SketchCard>

          <div className="sketch-border-heavy p-6 bg-white">
            <p className="sketch-text text-center text-xl">
              Perfect for wireframes, prototypes, and rapid development! 🎨
            </p>
          </div>
        </div>
      </div>
    </>
  );
}
src/components/sketch/sketch-filters.tsx
export function SketchFilters() {
  return (
    <svg
      style={{ position: "absolute", width: 0, height: 0 }}
      xmlns="http://www.w3.org/2000/svg"
    >
      <defs>
        {/* Turbulence filter for wobbly hand-drawn effect - subtle */}
        <filter id="sketchy" x="-10%" y="-10%" width="120%" height="120%">
          <feTurbulence
            type="fractalNoise"
            baseFrequency="0.02"
            numOctaves="2"
            result="noise"
            seed="2"
          />
          <feDisplacementMap in="SourceGraphic" in2="noise" scale="1" />
        </filter>

        {/* Medium sketch effect - gentle wobble */}
        <filter
          id="sketchy-medium"
          x="-15%"
          y="-15%"
          width="130%"
          height="130%"
        >
          <feTurbulence
            type="fractalNoise"
            baseFrequency="0.03"
            numOctaves="3"
            result="noise"
            seed="3"
          />
          <feDisplacementMap in="SourceGraphic" in2="noise" scale="1.5" />
        </filter>

        {/* Heavy sketch effect - noticeable but not extreme */}
        <filter id="sketchy-heavy" x="-20%" y="-20%" width="140%" height="140%">
          <feTurbulence
            type="fractalNoise"
            baseFrequency="0.04"
            numOctaves="3"
            result="noise"
            seed="5"
          />
          <feDisplacementMap in="SourceGraphic" in2="noise" scale="2" />
        </filter>

        {/* Pencil sketch texture */}
        <filter id="pencil-sketch" x="-20%" y="-20%" width="140%" height="140%">
          <feTurbulence
            type="fractalNoise"
            baseFrequency="2"
            numOctaves="5"
            result="noise"
          />
          <feDiffuseLighting
            in="noise"
            lightingColor="white"
            surfaceScale="1"
            result="light"
          >
            <feDistantLight azimuth="45" elevation="60" />
          </feDiffuseLighting>
          <feComposite in="SourceGraphic" in2="light" operator="multiply" />
        </filter>

        {/* Rough border path for hand-drawn borders - softened */}
        <filter id="rough-border">
          <feTurbulence
            type="fractalNoise"
            baseFrequency="0.06 0.03"
            numOctaves="2"
            result="turbulence"
          />
          <feDisplacementMap
            in="SourceGraphic"
            in2="turbulence"
            scale="1.5"
            xChannelSelector="R"
            yChannelSelector="G"
          />
        </filter>
      </defs>
    </svg>
  );
}
src/components/sketch/sketch-heading.tsx
import { ReactNode } from "react";

interface SketchHeadingProps {
  children: ReactNode;
  level?: 1 | 2 | 3 | 4;
  underline?: boolean;
  scribble?: boolean;
  highlight?: boolean;
  className?: string;
}

export function SketchHeading({
  children,
  level = 1,
  underline = false,
  scribble = false,
  highlight = false,
  className = "",
}: SketchHeadingProps) {
  const sizes = {
    1: "text-5xl",
    2: "text-4xl",
    3: "text-3xl",
    4: "text-2xl",
  };

  const Tag = `h${level}` as keyof HTMLElementTagNameMap;

  let effectClass = "";
  if (underline) effectClass = "sketch-underline";
  if (scribble) effectClass = "sketch-scribble";
  if (highlight) effectClass = "sketch-highlight";

  return (
    <Tag
      className={`sketch-text font-bold ${sizes[level]} ${effectClass} ${className}`}
    >
      {children}
    </Tag>
  );
}
src/components/sketch/sketch-input.tsx
import { InputHTMLAttributes } from "react";

interface SketchInputProps extends InputHTMLAttributes<HTMLInputElement> {
  label?: string;
}

export function SketchInput({
  label,
  className = "",
  ...props
}: SketchInputProps) {
  return (
    <div className="flex flex-col gap-2">
      {label && (
        <label className="sketch-text text-lg font-bold">{label}</label>
      )}
      <input className={`sketch-input text-base ${className}`} {...props} />
    </div>
  );
}
src/components/sketch/sketch-mini-layout.tsx
"use client";

import { ReactNode, useState } from "react";
import { SketchHeading } from "./sketch-heading";
import { SketchFilters } from "./sketch-filters";

type SketchTab = {
  label: string;
  content: ReactNode;
};

type SketchMiniLayoutProps = {
  /**
   * App title shown in header
   */
  title?: string;
  /**
   * Layout mode:
   * - "scroll" (default): Fixed header, scrollable content
   * - "fixed": Full viewport, no scroll (for games/dashboards)
   * - "tabs": Full viewport with tab navigation
   */
  mode?: "scroll" | "fixed" | "tabs";
  /**
   * For tabs mode: array of tab objects
   */
  tabs?: SketchTab[];
  /**
   * Default selected tab (lowercase label)
   */
  defaultTab?: string;
  /**
   * Footer content (optional, fixed at bottom)
   */
  footer?: ReactNode;
  /**
   * Content to display on the right side of the header
   */
  headerRight?: ReactNode;
  /**
   * Main content (for scroll/fixed modes)
   */
  children?: ReactNode;
};

/**
 * SketchMiniLayout - Wireframe layout for Farcaster mini apps
 *
 * Use this to define your app's layout structure in Phase 1.
 * In Phase 2, replace with StandardMiniLayout or GameMiniLayout.
 *
 * @example Scrolling content app
 * ```tsx
 * <SketchMiniLayout title="My App" mode="scroll">
 *   <SketchCard>Content here...</SketchCard>
 * </SketchMiniLayout>
 * ```
 *
 * @example Viewport-filling app (games, dashboards)
 * ```tsx
 * <SketchMiniLayout title="My Game" mode="fixed" footer={<SketchButton>Play</SketchButton>}>
 *   <GameBoard />
 * </SketchMiniLayout>
 * ```
 *
 * @example Tabbed app
 * ```tsx
 * <SketchMiniLayout
 *   title="My App"
 *   mode="tabs"
 *   tabs={[
 *     { label: "Home", content: <HomeScreen /> },
 *     { label: "Stats", content: <StatsScreen /> },
 *     { label: "Settings", content: <SettingsScreen /> },
 *   ]}
 * />
 * ```
 */
export function SketchMiniLayout({
  title = "App Name",
  mode = "scroll",
  tabs,
  defaultTab,
  footer,
  headerRight,
  children,
}: SketchMiniLayoutProps) {
  const [activeTab, setActiveTab] = useState(
    defaultTab || tabs?.[0]?.label.toLowerCase() || "",
  );

  // Tabs mode
  if (mode === "tabs" && tabs) {
    return (
      <>
        <SketchFilters />
        <div className="h-dvh flex flex-col overflow-hidden sketch-paper p-1">
          {/* Sketchy outer border */}
          <div
            className="flex-1 flex flex-col min-h-0 sketch-border"
            style={{ filter: "url(#sketchy)" }}
          >
            {/* Header */}
            <header className="shrink-0 px-3 py-2 sketch-border-b flex items-center justify-between">
              <SketchHeading level={4}>{title}</SketchHeading>
              {headerRight && <div>{headerRight}</div>}
            </header>

            {/* Tab Navigation */}
            <nav className="shrink-0 flex sketch-border-b">
              {tabs.map((tab) => {
                const tabValue = tab.label.toLowerCase();
                const isActive = activeTab === tabValue;
                return (
                  <button
                    key={tabValue}
                    onClick={() => setActiveTab(tabValue)}
                    className={`
                      flex-1 px-3 py-2 sketch-text text-sm font-medium
                      border-r-2 border-foreground/30 last:border-r-0
                      transition-colors
                      ${isActive ? "bg-foreground/10" : "hover:bg-foreground/5"}
                    `}
                  >
                    {tab.label}
                  </button>
                );
              })}
            </nav>

            {/* Tab Content */}
            <main className="flex-1 overflow-y-auto p-3">
              {tabs.find((t) => t.label.toLowerCase() === activeTab)?.content}
            </main>

            {/* Optional Footer */}
            {footer && (
              <footer className="shrink-0 p-3 sketch-border-t">{footer}</footer>
            )}
          </div>
        </div>
      </>
    );
  }

  // Fixed mode (viewport-filling, no scroll)
  if (mode === "fixed") {
    return (
      <>
        <SketchFilters />
        <div className="h-dvh flex flex-col overflow-hidden sketch-paper p-1">
          {/* Sketchy outer border */}
          <div
            className="flex-1 flex flex-col min-h-0 sketch-border"
            style={{ filter: "url(#sketchy)" }}
          >
            {/* Header */}
            <header className="shrink-0 px-3 py-2 sketch-border-b">
              <SketchHeading level={4}>{title}</SketchHeading>
            </header>

            {/* Main Content */}
            <main className="flex-1 flex flex-col min-h-0 overflow-hidden p-3">
              {children}
            </main>

            {/* Optional Footer */}
            {footer && (
              <footer className="shrink-0 p-3 sketch-border-t">{footer}</footer>
            )}
          </div>
        </div>
      </>
    );
  }

  // Scroll mode (default)
  return (
    <>
      <SketchFilters />
      <div className="min-h-dvh flex flex-col sketch-paper p-1">
        {/* Sketchy outer border */}
        <div
          className="flex-1 flex flex-col sketch-border"
          style={{ filter: "url(#sketchy)" }}
        >
          {/* Fixed Header */}
          <header className="sticky top-1 z-10 px-3 py-2 sketch-border-b bg-[#fafafa]/95 backdrop-blur-sm">
            <SketchHeading level={4}>{title}</SketchHeading>
          </header>

          {/* Scrollable Content */}
          <main className="flex-1 p-3">{children}</main>

          {/* Optional Fixed Footer */}
          {footer && (
            <footer className="sticky bottom-1 p-3 sketch-border-t bg-[#fafafa]/95 backdrop-blur-sm">
              {footer}
            </footer>
          )}
        </div>
      </div>
    </>
  );
}
src/components/sketch/sketch-textarea.tsx
import { TextareaHTMLAttributes } from "react";

interface SketchTextareaProps
  extends TextareaHTMLAttributes<HTMLTextAreaElement> {
  label?: string;
}

export function SketchTextarea({
  label,
  className = "",
  ...props
}: SketchTextareaProps) {
  return (
    <div className="flex flex-col gap-2">
      {label && (
        <label className="sketch-text text-lg font-bold">{label}</label>
      )}
      <textarea
        className={`sketch-input text-base min-h-[100px] ${className}`}
        {...props}
      />
    </div>
  );
}
src/components/theme-client.tsx
"use client";

import { Theme } from "@neynar/ui";

export function ThemeClient() {
  return <Theme />;
}
src/features/app/components/achievements.tsx
"use client";

import { useState, useEffect } from "react";
import { Card, CardContent, P, Small, H4 } from "@neynar/ui";
import { ClipboardIcon, LockIcon, CheckIcon, GridIcon, MedalIcon, UploadIcon, LinkIcon, StarIcon, GemIcon, SparkleIcon, CrownIcon, RocketIcon, ChartBarIcon, SaveIcon, WidgetIcon, HandshakeIcon, ShareIcon } from "@/components/icons/net-library-icons";
import { ACHIEVEMENTS, type AchievementId, type Achievement, type AchievementIconId } from "@/lib/net-protocol";
import { safeComposeCast, safeOpenUrl, useAppMode } from "@/lib/app-mode";
import { useUserProfile } from "@/hooks/use-user-profile";
import { useStoragePassModal, STORAGE_PASS_PRICE_USD } from "./unlimited-storage-pass-modal";
import { useAccount } from "wagmi";

// Achievement icon component - maps iconId to actual SVG icons
// Exported for use in share image generation
export function AchievementIcon({ iconId, size = 24, className = "" }: { iconId: AchievementIconId; size?: number; className?: string }) {
  const iconProps = { size, className };

  switch (iconId) {
    // Membership
    case "shield":
      return (
        <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
          <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
        </svg>
      );
    case "link":
      return <LinkIcon {...iconProps} />;
    case "star":
      return <StarIcon {...iconProps} />;
    case "gem":
      return <GemIcon {...iconProps} />;

    // Uploads
    case "upload":
      return <UploadIcon {...iconProps} />;
    case "sparkle":
      return <SparkleIcon {...iconProps} />;
    case "star-shine":
      return (
        <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="none" className={className}>
          <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
        </svg>
      );
    case "crown":
      return <CrownIcon {...iconProps} />;

    // Upvotes Given
    case "arrow-up":
      return (
        <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
          <path d="M12 19V5" />
          <path d="M5 12l7-7 7 7" />
        </svg>
      );
    case "heart-green":
      return (
        <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="none" className={className}>
          <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
        </svg>
      );
    case "circle-green":
      return (
        <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="none" className={className}>
          <circle cx="12" cy="12" r="10" />
        </svg>
      );
    case "square-green":
      return (
        <svg width={size} height={size} viewBox="0 0 24 24" fill="currentColor" stroke="none" className={className}>
          <rect x="3" y="3" width="18" height="18" rx="2" />
        </svg>
      );

    // Upvotes Received
    case "heart":
      return (
        <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
          <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
        </svg>
      );
    case "chart":
      return <ChartBarIcon {...iconProps} />;
    case "rocket":
      return <RocketIcon {...iconProps} />;
    case "crown-gold":
      return <CrownIcon {...iconProps} />;

    // Data
    case "save":
      return <SaveIcon {...iconProps} />;
    case "disc":
      return (
        <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
          <circle cx="12" cy="12" r="10" />
          <circle cx="12" cy="12" r="3" />
        </svg>
      );
    case "disc-shine":
      return (
        <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
          <circle cx="12" cy="12" r="10" />
          <circle cx="12" cy="12" r="3" />
          <path d="M12 2v2" />
          <path d="M12 20v2" />
          <path d="M2 12h2" />
          <path d="M20 12h2" />
        </svg>
      );
    case "archive":
      return (
        <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
          <rect x="2" y="3" width="20" height="5" rx="1" />
          <path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8" />
          <path d="M10 12h4" />
        </svg>
      );

    // Comments
    case "message":
      return (
        <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
        </svg>
      );
    case "megaphone":
      return (
        <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
          <path d="M3 11l18-5v12L3 13V11z" />
          <path d="M11.6 16.8a3 3 0 1 1-5.8-1.6" />
        </svg>
      );
    case "broadcast":
      return (
        <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
          <circle cx="12" cy="12" r="2" />
          <path d="M16.24 7.76a6 6 0 0 1 0 8.49m-8.48-.01a6 6 0 0 1 0-8.49m11.31-2.82a10 10 0 0 1 0 14.14m-14.14 0a10 10 0 0 1 0-14.14" />
        </svg>
      );
    case "crystal":
      return (
        <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className={className}>
          <circle cx="12" cy="12" r="10" />
          <path d="M12 2a4.5 4.5 0 0 0 0 9 4.5 4.5 0 0 1 0 9" />
          <path d="M12 7v10" />
        </svg>
      );

    default:
      return <MedalIcon {...iconProps} />;
  }
}

interface AchievementBadgeProps {
  achievement: Achievement;
  earned?: boolean;
  earnedAt?: number;
  size?: "xs" | "sm" | "md" | "lg";
  showTooltip?: boolean;
  isSelected?: boolean;
  onSelect?: () => void;
}

interface UserInfo {
  username?: string;
  pfpUrl?: string;
}

const RARITY_COLORS = {
  common: "border-gray-500 bg-gray-500/10",
  rare: "border-blue-500 bg-blue-500/10",
  epic: "border-purple-500 bg-purple-500/10",
  legendary: "border-yellow-500 bg-yellow-500/10",
};

// Get share text for achievement
function getAchievementShareText(achievement: Achievement, username?: string) {
  const earnerText = username ? `@${username} just` : "I just";
  return `Achievement Unlocked: ${achievement.name}!\n\n${earnerText} earned this badge on Net Library.\n\nJoin us in building the world's biggest decentralized onchain library powered by @netprotocol`;
}

function getAchievementShareUrl(achievement: Achievement, isBaseApp: boolean, userInfo?: UserInfo) {
  const baseUrl = typeof window !== "undefined" ? window.location.origin : "";
  const shareParams = new URLSearchParams({
    name: achievement.name,
    iconId: achievement.iconId,
    rarity: achievement.rarity,
    t: String(Date.now()),
    source: isBaseApp ? "base" : "farcaster",
  });
  // Add user info if available
  if (userInfo?.username) {
    shareParams.set("username", userInfo.username);
  }
  if (userInfo?.pfpUrl) {
    shareParams.set("pfpUrl", userInfo.pfpUrl);
  }
  return `${baseUrl}/share/achievement?${shareParams.toString()}`;
}

// Share achievement to Farcaster/Feed
export async function shareAchievement(achievement: Achievement, isBaseApp: boolean = false, userInfo?: UserInfo) {
  const castText = getAchievementShareText(achievement, userInfo?.username);
  const shareUrl = getAchievementShareUrl(achievement, isBaseApp, userInfo);

  try {
    await safeComposeCast({
      text: castText,
      embeds: [shareUrl],
    });
  } catch (err) {
    console.error("Failed to share:", err);
  }
}

// Share achievement to X
export async function shareAchievementToX(achievement: Achievement, isBaseApp: boolean = false, userInfo?: UserInfo) {
  const castText = getAchievementShareText(achievement, userInfo?.username).replace("@netprotocol", "@netprotocolapp");
  // Always use source=web for X shares so users land in browser experience
  const shareUrl = getAchievementShareUrl(achievement, false, userInfo).replace(/source=(base|farcaster)/, "source=web");
  // If no source param exists, add it
  const xShareUrl = shareUrl.includes("source=") ? shareUrl : `${shareUrl}&source=web`;

  try {
    const xIntentParams = new URLSearchParams({
      text: castText,
      url: xShareUrl,
    });
    const xIntentUrl = `https://twitter.com/intent/tweet?${xIntentParams.toString()}`;
    // For Base App, open in system browser to avoid in-app interception
    if (isBaseApp) {
      window.open(xIntentUrl, "_blank", "noopener,noreferrer");
    } else {
      await safeOpenUrl(xIntentUrl);
    }
  } catch (err) {
    console.error("Failed to share to X:", err);
  }
}

// Achievement share button with dropdown
function AchievementShareButton({ achievement }: { achievement: Achievement }) {
  const [showMenu, setShowMenu] = useState(false);
  const appMode = useAppMode();
  const isBaseApp = appMode === "base-app";
  const { profile } = useUserProfile();

  // Get user info for sharing
  const userInfo: UserInfo = {
    username: profile?.username,
    pfpUrl: profile?.pfpUrl,
  };

  return (
    <div className="relative">
      <button
        onClick={() => setShowMenu(!showMenu)}
        className="w-full py-1.5 rounded bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] text-[10px] font-mono uppercase tracking-wider hover:bg-[#00ff00]/20 transition-all flex items-center justify-center gap-1"
      >
        <ShareIcon size={10} /> Share Achievement ▾
      </button>

      {showMenu && (
        <>
          <div className="fixed inset-0 z-40" onClick={() => setShowMenu(false)} />
          <div className="absolute bottom-full left-0 right-0 mb-1 bg-black border border-[#00ff00]/30 rounded-lg overflow-hidden z-50 shadow-lg">
            <button
              onClick={() => { setShowMenu(false); shareAchievement(achievement, isBaseApp, userInfo); }}
              className={`w-full px-3 py-2 text-left text-[10px] font-mono flex items-center gap-2 transition-colors ${
                isBaseApp
                  ? "hover:bg-[#0052FF]/20 text-[#0052FF]"
                  : "hover:bg-[#8A63D2]/20 text-[#8A63D2]"
              }`}
            >
              {isBaseApp ? (
                <svg width="12" height="12" viewBox="0 0 111 111" fill="none">
                  <path d="M54.921 110.034C85.359 110.034 110.034 85.402 110.034 55.017C110.034 24.6319 85.359 0 54.921 0C26.0432 0 2.35281 22.1714 0 50.3923H72.8467V59.6416H0C2.35281 87.8625 26.0432 110.034 54.921 110.034Z" fill="#0052FF"/>
                </svg>
              ) : (
                <svg width="12" height="12" viewBox="0 0 1000 1000" fill="#8A63D2">
                  <path d="M257.778 155.556H742.222V844.445H671.111V528.889H670.414C662.554 441.677 589.258 373.333 500 373.333C410.742 373.333 337.446 441.677 329.586 528.889H328.889V844.445H257.778V155.556Z"/>
                  <path d="M128.889 253.333L157.778 351.111H182.222V746.667C169.949 746.667 160 756.616 160 768.889V795.556H155.556C143.283 795.556 133.333 805.505 133.333 817.778V844.445H382.222V817.778C382.222 805.505 372.273 795.556 360 795.556H355.556V768.889C355.556 756.616 345.606 746.667 333.333 746.667H306.667V253.333H128.889Z"/>
                  <path d="M675.556 746.667C663.283 746.667 653.333 756.616 653.333 768.889V795.556H648.889C636.616 795.556 626.667 805.505 626.667 817.778V844.445H875.556V817.778C875.556 805.505 865.606 795.556 853.333 795.556H848.889V768.889C848.889 756.616 838.94 746.667 826.667 746.667V351.111H851.111L880 253.333H702.222V746.667H675.556Z"/>
                </svg>
              )}
              {isBaseApp ? "Share to Feed" : "Share to Farcaster"}
            </button>
            <button
              onClick={() => { setShowMenu(false); shareAchievementToX(achievement, isBaseApp, userInfo); }}
              className="w-full px-3 py-2 text-left text-[10px] font-mono flex items-center gap-2 hover:bg-white/10 text-white transition-colors border-t border-gray-800"
            >
              <svg width="10" height="10" viewBox="0 0 24 24" fill="white">
                <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
              </svg>
              Share to X
            </button>
          </div>
        </>
      )}
    </div>
  );
}

const RARITY_GLOW = {
  common: "",
  rare: "shadow-[0_0_10px_rgba(59,130,246,0.3)]",
  epic: "shadow-[0_0_15px_rgba(138,99,210,0.4)]", // Official Farcaster purple #8A63D2
  legendary: "shadow-[0_0_20px_rgba(234,179,8,0.5)]",
};

export function AchievementBadge({
  achievement,
  earned = true,
  size = "md",
  isSelected = false,
  onSelect,
}: AchievementBadgeProps & { tooltipPosition?: "top" | "bottom" }) {
  const sizeClasses = {
    xs: "w-6 h-6",
    sm: "w-8 h-8",
    md: "w-12 h-12",
    lg: "w-16 h-16"
  };

  const iconSizes = {
    xs: 12,
    sm: 16,
    md: 24,
    lg: 32
  };

  return (
    <button
      type="button"
      onClick={onSelect}
      className={`
        relative
        ${sizeClasses[size]}
        rounded-full border-2 flex items-center justify-center
        transition-all duration-300
        ${earned ? RARITY_COLORS[achievement.rarity] : "border-gray-700 bg-gray-900/50 opacity-40"}
        ${earned ? RARITY_GLOW[achievement.rarity] : ""}
        ${earned ? "active:scale-95" : ""}
        ${isSelected ? "ring-2 ring-[#00ff00] ring-offset-2 ring-offset-black scale-110" : ""}
      `}
    >
      <span className={earned ? "" : "grayscale opacity-50"}>
        <AchievementIcon iconId={achievement.iconId} size={iconSizes[size]} />
      </span>
    </button>
  );
}

export function AchievementGrid({
  earnedIds,
  showLocked = true,
  maxDisplay,
  size = "xs"
}: {
  earnedIds: AchievementId[];
  showLocked?: boolean;
  maxDisplay?: number;
  size?: "xs" | "sm" | "md" | "lg";
}) {
  const earnedSet = new Set(earnedIds);
  let displayAchievements = ACHIEVEMENTS;

  if (!showLocked) {
    displayAchievements = ACHIEVEMENTS.filter(a => earnedSet.has(a.id));
  }

  if (maxDisplay) {
    displayAchievements = displayAchievements.slice(0, maxDisplay);
  }

  const remainderSizeClass = size === "xs" ? "w-6 h-6" : "w-8 h-8";
  const remainderTextSize = size === "xs" ? "text-[8px]" : "text-[10px]";

  return (
    <div className="flex flex-wrap gap-1.5">
      {displayAchievements.map((achievement) => (
        <AchievementBadge
          key={achievement.id}
          achievement={achievement}
          earned={earnedSet.has(achievement.id)}
          size={size}
        />
      ))}
      {maxDisplay && ACHIEVEMENTS.length > maxDisplay && (
        <div className={`${remainderSizeClass} rounded-full border-2 border-gray-700 bg-gray-900/50 flex items-center justify-center`}>
          <Small className={`text-gray-500 font-mono ${remainderTextSize}`}>
            +{ACHIEVEMENTS.length - maxDisplay}
          </Small>
        </div>
      )}
    </div>
  );
}

// Achievement rows organized by category (order: common → rare → epic → legendary)
const ACHIEVEMENT_ROWS: { label: string; ids: AchievementId[] }[] = [
  { label: "Membership", ids: ["early-adopter", "linked", "og-member", "founding-member"] },
  { label: "Uploads", ids: ["first-upload", "contributor-5", "contributor-25", "contributor-100"] },
  { label: "Upvotes Given", ids: ["first-upvote", "upvote-supporter", "upvote-champion", "upvote-whale"] },
  { label: "Upvotes Received", ids: ["upvoted-creator", "trending-creator", "viral-creator", "legendary-creator"] },
  { label: "Data Uploaded", ids: ["data-1mb", "data-100mb", "data-1000mb", "data-10000mb"] },
  { label: "Comments", ids: ["first-comment", "commenter-10", "commenter-100", "commenter-1000"] },
];

export function AchievementsSection({
  earnedIds,
  totalPossible = ACHIEVEMENTS.length,
  isMember = true,
}: {
  earnedIds: AchievementId[];
  totalPossible?: number;
  isMember?: boolean;
}) {
  const [selectedAchievement, setSelectedAchievement] = useState<Achievement | null>(null);
  const [isExpanded, setIsExpanded] = useState(false);

  // Filter earnedIds to only include valid achievement IDs that exist in ACHIEVEMENTS
  const validAchievementIds = new Set(ACHIEVEMENTS.map(a => a.id));
  const validEarnedIds = earnedIds.filter(id => validAchievementIds.has(id));

  const earnedCount = isMember ? validEarnedIds.length : 0;
  const progressPercent = (earnedCount / totalPossible) * 100;

  const earnedSet = new Set(isMember ? validEarnedIds : []);

  // Create a map for quick achievement lookup
  const achievementMap = new Map(ACHIEVEMENTS.map(a => [a.id, a]));

  const handleSelect = (achievement: Achievement) => {
    if (!isMember) return; // Non-members can't select achievements
    // Toggle selection - if already selected, deselect
    setSelectedAchievement(prev => prev?.id === achievement.id ? null : achievement);
  };

  return (
    <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
      <CardContent className="p-4 space-y-3">
        {/* Header - always visible */}
        <div className="flex items-center justify-between">
          <H4 className="text-[#00ff00] font-mono flex items-center gap-2"><MedalIcon size={18} /> Achievements</H4>
          <Small className="text-[#00ff00] font-mono">
            {earnedCount}/{totalPossible}
          </Small>
        </div>

        {/* Progress bar - always visible */}
        <div className="h-2 bg-gray-800 rounded-full overflow-hidden">
          <div
            className="h-full bg-gradient-to-r from-[#00ff00]/50 to-[#00ff00] transition-all duration-500"
            style={{ width: `${progressPercent}%` }}
          />
        </div>

        {/* Expand/Collapse button */}
        <button
          onClick={() => setIsExpanded(!isExpanded)}
          className="w-full py-3 flex items-center justify-center gap-2 text-gray-400 hover:text-[#00ff00] transition-colors bg-[#00ff00]/5 hover:bg-[#00ff00]/10 rounded-lg border border-[#00ff00]/20"
        >
          <span className="font-mono text-sm font-medium">
            {isExpanded ? "Hide Achievements" : "View Achievements"}
          </span>
          <span className={`text-sm transition-transform duration-200 ${isExpanded ? "rotate-180" : ""}`}>
            ▼
          </span>
        </button>

        {/* Collapsible content */}
        {isExpanded && (
          <div className="space-y-4 pt-3 border-t border-gray-800 mt-3">
            {/* Non-member message */}
            {!isMember ? (
              <div className="py-6 text-center">
                <LockIcon size={32} className="mx-auto mb-3 text-gray-600" />
                <P className="text-gray-400 font-mono text-sm">Members Only</P>
                <Small className="text-gray-500 font-mono block mt-1">
                  Become a Net Library member to track your achievements and earn badges for your contributions.
                </Small>
              </div>
            ) : (
              <>
                {/* Selected achievement info panel */}
                {selectedAchievement && (
                  <div
                    className={`p-3 rounded-lg border ${
                      earnedSet.has(selectedAchievement.id)
                        ? `${RARITY_COLORS[selectedAchievement.rarity]} ${RARITY_GLOW[selectedAchievement.rarity]}`
                        : "border-gray-700 bg-gray-900/50"
                    }`}
                  >
                    <div className="flex items-center gap-3">
                      <span className={`${!earnedSet.has(selectedAchievement.id) ? "grayscale opacity-50" : ""}`}>
                        <AchievementIcon iconId={selectedAchievement.iconId} size={28} />
                      </span>
                      <div className="flex-1 min-w-0">
                        <P className={`font-mono font-bold text-sm ${earnedSet.has(selectedAchievement.id) ? "text-white" : "text-gray-500"}`}>
                          {selectedAchievement.name}
                        </P>
                        <Small className={`font-mono text-xs ${earnedSet.has(selectedAchievement.id) ? "text-gray-300" : "text-gray-600"}`}>
                          {selectedAchievement.description}
                        </Small>
                      </div>
                      <div className="flex flex-col items-end gap-1">
                        <Small className={`font-mono text-[10px] uppercase px-2 py-0.5 rounded ${
                          selectedAchievement.rarity === "legendary" ? "bg-yellow-500/20 text-yellow-400" :
                          selectedAchievement.rarity === "epic" ? "bg-purple-500/20 text-purple-400" :
                          selectedAchievement.rarity === "rare" ? "bg-blue-500/20 text-blue-400" :
                          "bg-gray-500/20 text-gray-400"
                        }`}>
                          {selectedAchievement.rarity}
                        </Small>
                        {earnedSet.has(selectedAchievement.id) ? (
                          <Small className="text-[#00ff00] font-mono text-[10px] flex items-center gap-1"><CheckIcon size={10} /> Earned</Small>
                        ) : (
                          <Small className="text-gray-500 font-mono text-[10px] flex items-center gap-1"><LockIcon size={10} /> Locked</Small>
                        )}
                      </div>
                    </div>
                    {earnedSet.has(selectedAchievement.id) && (
                      <div className="mt-2">
                        <AchievementShareButton achievement={selectedAchievement} />
                      </div>
                    )}
                  </div>
                )}

                {/* Tap instruction */}
                {!selectedAchievement && (
                  <Small className="text-gray-500 font-mono text-[10px] text-center block">
                    Tap an achievement to see details
                  </Small>
                )}

                {/* Achievement rows by category */}
                <div className="space-y-3">
                  {ACHIEVEMENT_ROWS.map((row, rowIndex) => (
                    <div key={rowIndex} className="space-y-1">
                      <Small className="text-gray-500 font-mono text-[9px] uppercase tracking-wider text-center block">
                        {row.label}
                      </Small>
                      <div className="flex gap-3 justify-center">
                        {row.ids.map((id) => {
                          const achievement = achievementMap.get(id);
                          if (!achievement) return null;
                          return (
                            <AchievementBadge
                              key={achievement.id}
                              achievement={achievement}
                              earned={earnedSet.has(achievement.id)}
                              size="md"
                              isSelected={selectedAchievement?.id === achievement.id}
                              onSelect={() => handleSelect(achievement)}
                            />
                          );
                        })}
                      </div>
                    </div>
                  ))}
                </div>

                {/* Rarity legend */}
                <div className="flex flex-wrap gap-3 pt-2 border-t border-gray-800 justify-center">
                  {(["common", "rare", "epic", "legendary"] as const).map((rarity) => (
                    <div key={rarity} className="flex items-center gap-1">
                      <div className={`w-2 h-2 rounded-full ${RARITY_COLORS[rarity].replace("bg-", "bg-").replace("/10", "")}`} />
                      <Small className="text-gray-500 font-mono text-[10px] capitalize">{rarity}</Small>
                    </div>
                  ))}
                </div>
              </>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}

// Recent achievement unlock notification
export function AchievementUnlockToast({
  achievement,
  onClose
}: {
  achievement: Achievement;
  onClose: () => void;
}) {
  return (
    <div className="fixed top-4 left-1/2 -translate-x-1/2 z-50 animate-slide-down">
      <Card className={`bg-black border-2 ${RARITY_COLORS[achievement.rarity]} ${RARITY_GLOW[achievement.rarity]}`}>
        <CardContent className="p-4 space-y-3">
          <div className="flex items-center gap-4">
            <div><AchievementIcon iconId={achievement.iconId} size={40} /></div>
            <div className="flex-1">
              <Small className="text-[#00ff00] font-mono uppercase tracking-wider">Achievement Unlocked!</Small>
              <P className="text-white font-mono font-bold">{achievement.name}</P>
              <Small className="text-gray-400 font-mono">{achievement.description}</Small>
            </div>
            <button onClick={onClose} className="text-gray-500 hover:text-white">✕</button>
          </div>
          <AchievementShareButton achievement={achievement} />
        </CardContent>
      </Card>
    </div>
  );
}

// Embed type definitions
type EmbedType = "card" | "item" | "stack" | "grid" | "user" | "feed" | "stats";
type EmbedIconType = "card" | "book" | "stack" | "grid" | "user" | "library" | "chart";

interface EmbedTypeConfig {
  id: EmbedType;
  label: string;
  iconType: EmbedIconType;
  description: string;
  needsPicker: boolean; // Whether user needs to select specific content
  height: number;
}

// Embed icon component
function EmbedIcon({ type, size = 16, className = "" }: { type: EmbedIconType; size?: number; className?: string }) {
  const props = { width: size, height: size, className };
  const strokeProps = { ...props, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round" as const, strokeLinejoin: "round" as const };

  switch (type) {
    case "card":
      return (
        <svg {...strokeProps}>
          <rect x="2" y="5" width="20" height="14" rx="2" />
          <line x1="2" y1="10" x2="22" y2="10" />
        </svg>
      );
    case "book":
      return (
        <svg {...strokeProps}>
          <path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z" />
          <path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z" />
        </svg>
      );
    case "stack":
      return (
        <svg {...strokeProps}>
          <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
          <polyline points="14 2 14 8 20 8" />
          <line x1="16" y1="13" x2="8" y2="13" />
          <line x1="16" y1="17" x2="8" y2="17" />
        </svg>
      );
    case "grid":
      return (
        <svg {...strokeProps}>
          <rect x="3" y="3" width="7" height="7" />
          <rect x="14" y="3" width="7" height="7" />
          <rect x="14" y="14" width="7" height="7" />
          <rect x="3" y="14" width="7" height="7" />
        </svg>
      );
    case "user":
      return (
        <svg {...strokeProps}>
          <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
          <circle cx="12" cy="7" r="4" />
        </svg>
      );
    case "library":
      return (
        <svg {...strokeProps}>
          <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20" />
          <path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z" />
        </svg>
      );
    case "chart":
      return (
        <svg {...strokeProps}>
          <rect x="3" y="12" width="4" height="9" rx="1" />
          <rect x="10" y="8" width="4" height="13" rx="1" />
          <rect x="17" y="3" width="4" height="18" rx="1" />
        </svg>
      );
    default:
      return <WidgetIcon size={size} className={className} />;
  }
}

const EMBED_TYPES: EmbedTypeConfig[] = [
  { id: "card", label: "Card", iconType: "card", description: "Your library member card", needsPicker: false, height: 320 },
  { id: "item", label: "Item", iconType: "book", description: "Single book/item", needsPicker: true, height: 200 },
  { id: "stack", label: "Stack", iconType: "stack", description: "A curated collection", needsPicker: true, height: 400 },
  { id: "grid", label: "Grid", iconType: "grid", description: "Visual curation board", needsPicker: true, height: 380 },
  { id: "user", label: "Profile", iconType: "user", description: "User profile & stats", needsPicker: false, height: 280 },
  { id: "feed", label: "Feed", iconType: "library", description: "Scrollable item list", needsPicker: false, height: 400 },
  { id: "stats", label: "Stats", iconType: "chart", description: "Global statistics", needsPicker: false, height: 120 },
];

// Types for picker data
interface PickerItem {
  id: string;
  title: string;
  subtitle?: string;
}

interface MemberResourcesProps {
  isMember?: boolean;
  userAddress?: string;
  userFid?: number;
  userUploads?: Array<{ contentKey: string; title: string; author?: string }>;
  userStacks?: Array<{ id: string; name: string; itemCount?: number }>;
  userGrids?: Array<{ id: string; name: string; size?: number }>;
}

// Member Resources Section - Collapsible section for member-only features
export function MemberResourcesSection({
  isMember = false,
  userAddress = "",
  userFid,
  userUploads = [],
  userStacks = [],
  userGrids = [],
}: MemberResourcesProps) {
  const [isExpanded, setIsExpanded] = useState(false);
  const [selectedEmbed, setSelectedEmbed] = useState<EmbedType | null>(null);
  const [selectedItem, setSelectedItem] = useState<PickerItem | null>(null);
  const [copiedType, setCopiedType] = useState<string | null>(null);
  const [showPicker, setShowPicker] = useState(false);

  // Get base URL
  const getBaseUrl = () => {
    return typeof window !== "undefined" ? window.location.origin : "https://netlibrary.app";
  };

  // Generate embed URL based on type and selected content
  const getEmbedUrl = (type: EmbedType, item?: PickerItem | null): string => {
    const baseUrl = getBaseUrl();
    switch (type) {
      case "card":
        return `${baseUrl}/embed/card/${userAddress}`;
      case "item":
        return item ? `${baseUrl}/embed/item/${item.id}` : `${baseUrl}/embed/item/[SELECT_ITEM]`;
      case "stack":
        return item ? `${baseUrl}/embed/stack/${item.id}` : `${baseUrl}/embed/stack/[SELECT_STACK]`;
      case "grid":
        return item ? `${baseUrl}/embed/grid/${item.id}` : `${baseUrl}/embed/grid/[SELECT_GRID]`;
      case "user":
        return `${baseUrl}/embed/user/${userAddress}`;
      case "feed":
        return `${baseUrl}/embed/feed?uploader=${userAddress}`;
      case "stats":
        return `${baseUrl}/embed/stats`;
      default:
        return baseUrl;
    }
  };

  // Generate iframe code
  const getIframeCode = (type: EmbedType, item?: PickerItem | null): string => {
    const url = getEmbedUrl(type, item);
    const config = EMBED_TYPES.find(e => e.id === type);
    const height = config?.height || 300;
    return `<iframe src="${url}" width="100%" height="${height}" frameborder="0" style="border-radius: 12px; border: 1px solid #00ff0033;"></iframe>`;
  };

  // Get picker items based on embed type
  const getPickerItems = (type: EmbedType): PickerItem[] => {
    switch (type) {
      case "item":
        return userUploads.map(u => ({
          id: u.contentKey,
          title: u.title,
          subtitle: u.author,
        }));
      case "stack":
        return userStacks.map(s => ({
          id: s.id,
          title: s.name,
          subtitle: `${s.itemCount || 0} items`,
        }));
      case "grid":
        return userGrids.map(g => ({
          id: g.id,
          title: g.name,
          subtitle: g.size ? `${g.size}×${g.size}` : undefined,
        }));
      default:
        return [];
    }
  };

  // Copy to clipboard
  const copyToClipboard = async (text: string, type: string) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopiedType(type);
      setTimeout(() => setCopiedType(null), 2000);
    } catch {
      const textarea = document.createElement("textarea");
      textarea.value = text;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand("copy");
      document.body.removeChild(textarea);
      setCopiedType(type);
      setTimeout(() => setCopiedType(null), 2000);
    }
  };

  // Handle embed type selection
  const handleEmbedSelect = (type: EmbedType) => {
    if (selectedEmbed === type) {
      setSelectedEmbed(null);
      setSelectedItem(null);
      setShowPicker(false);
    } else {
      setSelectedEmbed(type);
      setSelectedItem(null);
      const config = EMBED_TYPES.find(e => e.id === type);
      setShowPicker(config?.needsPicker || false);
    }
  };

  // Check if preview is ready (has all required data)
  const isPreviewReady = (type: EmbedType): boolean => {
    const config = EMBED_TYPES.find(e => e.id === type);
    if (!config) return false;
    if (config.needsPicker) return !!selectedItem;
    if (type === "card" || type === "user" || type === "feed") return !!userAddress;
    return true;
  };

  return (
    <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
      <CardContent className="p-4 space-y-3">
        {/* Header - always visible */}
        <div className="flex items-center justify-between">
          <H4 className="text-[#00ff00] font-mono flex items-center gap-2"><HandshakeIcon size={18} /> Member Resources</H4>
          <Small className="text-[#00ff00]/70 font-mono">
            {isMember ? "Active" : "Locked"}
          </Small>
        </div>

        {/* Expand/Collapse button */}
        <button
          onClick={() => setIsExpanded(!isExpanded)}
          className="w-full py-3 flex items-center justify-center gap-2 text-gray-400 hover:text-[#00ff00] transition-colors bg-[#00ff00]/5 hover:bg-[#00ff00]/10 rounded-lg border border-[#00ff00]/20"
        >
          <span className="font-mono text-sm font-medium">
            {isExpanded ? "Hide Resources" : "View Resources"}
          </span>
          <span className={`text-sm transition-transform duration-200 ${isExpanded ? "rotate-180" : ""}`}>
            ▼
          </span>
        </button>

        {/* Collapsible content */}
        {isExpanded && (
          <div className="space-y-4 pt-3 border-t border-[#00ff00]/20 mt-3">
            {/* Non-member message */}
            {!isMember ? (
              <div className="py-6 text-center">
                <LockIcon size={32} className="mx-auto mb-3 text-gray-600" />
                <P className="text-gray-400 font-mono text-sm">Members Only</P>
                <Small className="text-gray-500 font-mono block mt-1">
                  Become a Net Library member to access embeddable widgets.
                </Small>
              </div>
            ) : (
              <>
                {/* API Key Section — first in dropdown (C20) */}
                <ApiKeySection userAddress={userAddress} userFid={userFid} />

                {/* My Passwords Section — manage saved encryption passwords */}
                <PasswordsSection userAddress={userAddress} userFid={userFid} />

                {/* Embeds Section */}
                <div className="space-y-3">
                  <div className="flex items-center gap-2">
                    <GridIcon size={14} className="text-[#00ff00]" />
                    <Small className="text-[#00ff00] font-mono text-[11px] uppercase tracking-wider">
                      Embed Widgets
                    </Small>
                  </div>
                  <Small className="text-gray-500 font-mono text-[10px] block">
                    Add Net Library content to any website.
                  </Small>

                  {/* Embed type selector - 4 columns (2 rows for 7 widgets) */}
                  <div className="grid grid-cols-4 gap-1">
                    {EMBED_TYPES.map((embed) => (
                      <button
                        key={embed.id}
                        onClick={() => handleEmbedSelect(embed.id)}
                        className={`py-2 px-1 rounded-lg transition-all flex flex-col items-center justify-center ${
                          selectedEmbed === embed.id
                            ? "bg-[#00ff00]/20 border border-[#00ff00]/50 text-[#00ff00]"
                            : "bg-[#1a1a1a] border border-transparent text-gray-400 hover:border-[#00ff00]/30"
                        }`}
                      >
                        <EmbedIcon type={embed.iconType} size={16} />
                        <Small className="font-mono text-[8px] mt-0.5 text-center w-full">{embed.label}</Small>
                      </button>
                    ))}
                  </div>

                  {/* Selected embed details */}
                  {selectedEmbed && (
                    <div className="p-3 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 space-y-3">
                      {(() => {
                        const embed = EMBED_TYPES.find(e => e.id === selectedEmbed)!;
                        const pickerItems = getPickerItems(selectedEmbed);
                        const previewReady = isPreviewReady(selectedEmbed);

                        return (
                          <>
                            {/* Header */}
                            <div className="flex items-center gap-2">
                              <EmbedIcon type={embed.iconType} size={24} />
                              <div>
                                <P className="text-white font-mono text-sm font-medium">{embed.label} Embed</P>
                                <Small className="text-gray-400 font-mono text-[10px]">{embed.description}</Small>
                              </div>
                            </div>

                            {/* Content Picker - for embeds that need specific selection */}
                            {showPicker && (
                              <div className="space-y-2">
                                <Small className="text-gray-500 font-mono text-[9px] uppercase block">
                                  Select {embed.id === "item" ? "an Item" : embed.id === "grid" ? "a Grid" : "a Stack"}
                                </Small>
                                <div className="max-h-32 overflow-y-auto space-y-1 bg-black/30 rounded-lg p-2">
                                  {pickerItems.length === 0 ? (
                                    <Small className="text-gray-500 font-mono text-[10px] block text-center py-2">
                                      No {embed.id === "item" ? "uploads" : embed.id === "grid" ? "grids" : "stacks"} yet
                                    </Small>
                                  ) : (
                                    pickerItems.map((item) => (
                                      <button
                                        key={item.id}
                                        onClick={() => setSelectedItem(selectedItem?.id === item.id ? null : item)}
                                        className={`w-full text-left px-2 py-1.5 rounded transition-all ${
                                          selectedItem?.id === item.id
                                            ? "bg-[#00ff00]/30 border border-[#00ff00]/50"
                                            : "hover:bg-[#00ff00]/10 border border-transparent"
                                        }`}
                                      >
                                        <Small className="text-white font-mono text-[10px] block truncate">
                                          {item.title}
                                        </Small>
                                        {item.subtitle && (
                                          <Small className="text-gray-500 font-mono text-[9px] block truncate">
                                            {item.subtitle}
                                          </Small>
                                        )}
                                      </button>
                                    ))
                                  )}
                                </div>
                              </div>
                            )}

                            {/* Live Preview */}
                            <div className="bg-black/50 rounded-lg border border-[#00ff00]/20 overflow-hidden">
                              <div className="px-3 py-1.5 border-b border-[#00ff00]/10 flex items-center justify-between">
                                <Small className="text-gray-500 font-mono text-[9px] uppercase">Live Preview</Small>
                                {previewReady && (
                                  <span className="w-2 h-2 rounded-full bg-[#00ff00] animate-pulse" />
                                )}
                              </div>
                              {previewReady ? (
                                <iframe
                                  src={getEmbedUrl(selectedEmbed, selectedItem)}
                                  className="w-full border-0"
                                  style={{ height: Math.min(embed.height, 200) }}
                                  title={`${embed.label} embed preview`}
                                />
                              ) : (
                                <div
                                  className="flex items-center justify-center bg-[#0d0d0d]"
                                  style={{ height: Math.min(embed.height, 200) }}
                                >
                                  <div className="text-center">
                                    <span className="block mb-1 opacity-30"><EmbedIcon type={embed.iconType} size={28} /></span>
                                    <Small className="text-gray-500 font-mono text-[9px]">
                                      {embed.needsPicker ? "Select content above" : "Preview loading..."}
                                    </Small>
                                  </div>
                                </div>
                              )}
                            </div>

                            {/* Embed URL */}
                            <div>
                              <Small className="text-gray-500 font-mono text-[9px] uppercase mb-1 block">Embed URL</Small>
                              <div className="flex gap-2">
                                <code className="flex-1 px-2 py-1.5 bg-black/50 rounded text-[9px] font-mono text-[#00ff00]/80 overflow-x-auto whitespace-nowrap">
                                  {getEmbedUrl(selectedEmbed, selectedItem)}
                                </code>
                                <button
                                  onClick={() => copyToClipboard(getEmbedUrl(selectedEmbed, selectedItem), `url-${selectedEmbed}`)}
                                  className={`px-2 py-1.5 rounded text-[10px] font-mono transition-all flex-shrink-0 ${
                                    copiedType === `url-${selectedEmbed}`
                                      ? "bg-[#00ff00]/20 text-[#00ff00]"
                                      : "bg-[#00ff00]/20 text-[#00ff00] hover:bg-[#00ff00]/30"
                                  }`}
                                >
                                  {copiedType === `url-${selectedEmbed}` ? "✓" : <ClipboardIcon size={12} />}
                                </button>
                              </div>
                            </div>

                            {/* Copy HTML button */}
                            <button
                              onClick={() => copyToClipboard(getIframeCode(selectedEmbed, selectedItem), `iframe-${selectedEmbed}`)}
                              className={`w-full py-2 px-3 rounded-lg text-xs font-mono transition-all ${
                                copiedType === `iframe-${selectedEmbed}`
                                  ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/30"
                                  : "bg-[#00ff00]/20 text-[#00ff00] hover:bg-[#00ff00]/30 border border-[#00ff00]/30"
                              }`}
                            >
                              {copiedType === `iframe-${selectedEmbed}` ? "✓ HTML Copied!" : "Copy HTML Embed Code"}
                            </button>
                          </>
                        );
                      })()}
                    </div>
                  )}
                </div>

                {/* Unlimited Pass Section */}
                <UnlimitedPassSection />
              </>
            )}
          </div>
        )}
      </CardContent>
    </Card>
  );
}

// =============================================================================
// API Key Section (C20) - Self-service API key generation for members
// =============================================================================

type ApiKeyState =
  | { status: "loading" }
  | { status: "no_key" }
  | { status: "has_key"; prefix: string; createdAt?: number; isActive: boolean }
  | { status: "just_generated"; apiKey: string };

function ApiKeySection({ userAddress, userFid }: { userAddress?: string; userFid?: number }) {
  const [keyState, setKeyState] = useState<ApiKeyState>({ status: "loading" });
  const [isWorking, setIsWorking] = useState(false);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [copiedKey, setCopiedKey] = useState(false);
  const [copiedInstall, setCopiedInstall] = useState(false);
  const [copiedConfig, setCopiedConfig] = useState(false);
  const [confirmAction, setConfirmAction] = useState<"regenerate" | "revoke" | null>(null);

  // Build identity params for Farcaster/web path (Path B)
  const identityBody = userFid
    ? { fid: userFid }
    : userAddress
    ? { address: userAddress }
    : null;

  // Check key status via POST { action: "status" } — avoids GET-with-body fragility.
  // GET is Bearer-only on the server; Farcaster/web users use this POST path.
  const checkKeyStatus = () => {
    if (!identityBody) {
      setKeyState({ status: "no_key" });
      return;
    }

    fetch("/api/v1/membership/api-key", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...identityBody, action: "status" }),
    })
      .then((r) => r.json())
      .then((data) => {
        if (data.hasKey) {
          setKeyState({
            status: "has_key",
            prefix: data.apiKeyPrefix || "nlk_???...",
            createdAt: data.createdAt,
            isActive: data.isActive !== false,
          });
        } else {
          setKeyState({ status: "no_key" });
        }
      })
      .catch(() => setKeyState({ status: "no_key" }));
  };

  useEffect(() => {
    if (!userFid && !userAddress) {
      setKeyState({ status: "no_key" });
      return;
    }
    setKeyState({ status: "loading" });
    setErrorMsg(null);
    checkKeyStatus();
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [userFid, userAddress]);

  const generateKey = async (regenerate = false) => {
    if (!identityBody) return;
    setIsWorking(true);
    setErrorMsg(null);
    try {
      const res = await fetch("/api/v1/membership/api-key", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...identityBody, ...(regenerate ? { regenerate: true } : {}) }),
      });
      if (!res.ok) {
        const errorData = await res.json().catch(() => ({}));
        setErrorMsg(errorData.error || "Failed to generate API key. Please try again.");
        return;
      }
      const data = await res.json();
      if (data.success && data.apiKey) {
        setKeyState({ status: "just_generated", apiKey: data.apiKey });
      }
    } catch {
      setErrorMsg("Network error — check your connection and try again.");
    } finally {
      setIsWorking(false);
      setConfirmAction(null);
    }
  };

  const revokeKey = async () => {
    if (!identityBody) return;
    setIsWorking(true);
    setErrorMsg(null);
    try {
      // Use POST { action: "revoke" } — DELETE is Bearer-only on the server,
      // and DELETE bodies are unreliable across proxies and CDNs.
      const res = await fetch("/api/v1/membership/api-key", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...identityBody, action: "revoke" }),
      });
      if (!res.ok) {
        const errorData = await res.json().catch(() => ({}));
        setErrorMsg(errorData.error || "Failed to revoke API key. Please try again.");
        return;
      }
      setKeyState({ status: "no_key" });
    } catch {
      setErrorMsg("Network error — could not revoke key. Please try again.");
    } finally {
      setIsWorking(false);
      setConfirmAction(null);
    }
  };

  const copyKey = async (key: string) => {
    try {
      await navigator.clipboard.writeText(key);
    } catch {
      const el = document.createElement("textarea");
      el.value = key;
      document.body.appendChild(el);
      el.select();
      document.execCommand("copy");
      document.body.removeChild(el);
    }
    setCopiedKey(true);
    setTimeout(() => setCopiedKey(false), 2000);
  };

  const copyInstall = async () => {
    const cmd = "npm install -g netlibrary-cli";
    try { await navigator.clipboard.writeText(cmd); } catch { /* ignore */ }
    setCopiedInstall(true);
    setTimeout(() => setCopiedInstall(false), 2000);
  };

  const copyConfig = async (key: string) => {
    // Guard: if key is absent/null/undefined, use a clear placeholder rather
    // than copying a broken command with the literal string "null" or "undefined".
    const safeKey = key && key !== "null" && key !== "undefined" ? key : "<your-key>";
    const cmd = `netlibrary config set apiKey ${safeKey}`;
    try { await navigator.clipboard.writeText(cmd); } catch { /* ignore */ }
    setCopiedConfig(true);
    setTimeout(() => setCopiedConfig(false), 2000);
  };

  // Reusable CLI Quick Start card shown in all key states
  const CliCard = ({ apiKey }: { apiKey?: string }) => (
    <div className="mt-2 rounded-lg bg-[#001100] border border-[#00ff00]/40 p-3 space-y-3">
      {/* Header */}
      <div className="flex items-center justify-between">
        <Small className="text-[#00ff00] font-mono text-sm font-bold uppercase tracking-wider">
          ⌨️ NET LIBRARY CLI
        </Small>
      </div>
      <Small className="text-gray-300 font-mono text-xs block">
        Upload, search, and manage your library from the command line or through any agent.
      </Small>

      {/* Install command */}
      <div>
        <Small className="text-gray-500 font-mono text-[10px] block mb-1">1. Install:</Small>
        <div className="flex items-center gap-2 bg-black rounded-lg px-3 py-2.5">
          <code className="flex-1 font-mono text-sm text-[#00ff00] select-all">
            npm install -g netlibrary-cli
          </code>
          <button
            onClick={copyInstall}
            className="flex-shrink-0 text-gray-500 hover:text-[#00ff00] transition-colors"
            title="Copy install command"
          >
            {copiedInstall ? <CheckIcon size={14} className="text-[#00ff00]" /> : <ClipboardIcon size={14} />}
          </button>
        </div>
      </div>

      {/* Config command */}
      <div>
        <Small className="text-gray-500 font-mono text-[10px] block mb-1">2. Configure your key:</Small>
        <div className="flex items-center gap-2 bg-black rounded-lg px-3 py-2.5">
          <code className="flex-1 font-mono text-sm text-[#00ff00] overflow-x-auto whitespace-nowrap select-all">
            netlibrary config set apiKey {apiKey || "<your-key>"}
          </code>
          <button
            onClick={() => copyConfig(apiKey || "<your-key>")}
            className="flex-shrink-0 text-gray-500 hover:text-[#00ff00] transition-colors"
            title="Copy config command"
          >
            {copiedConfig ? <CheckIcon size={14} className="text-[#00ff00]" /> : <ClipboardIcon size={14} />}
          </button>
        </div>
      </div>

      {/* Docs link */}
      <button
        onClick={() => safeOpenUrl("https://github.com/geaux-eth/net-library")}
        className="flex items-center gap-1 text-[#00ff00]/60 hover:text-[#00ff00] font-mono text-xs transition-colors"
      >
        <span>📖</span>
        <span className="underline underline-offset-2">Docs: github.com/geaux-eth/net-library</span>
      </button>
    </div>
  );

  return (
    <div className="pb-3 border-b border-[#00ff00]/10 space-y-3">
      {/* Section header */}
      <div className="flex items-center gap-2">
        <svg width={14} height={14} viewBox="0 0 24 24" fill="none" stroke="#00ff00" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="8" cy="15" r="4" />
          <path d="M12 11l8-8m-3 0l3 3m-6 3l3 3" />
        </svg>
        <Small className="text-[#00ff00] font-mono text-[11px] uppercase tracking-wider">
          API Key
        </Small>
      </div>

      {/* Error message */}
      {errorMsg && (
        <div className="p-2 bg-red-500/10 border border-red-500/30 rounded-lg">
          <Small className="text-red-400 font-mono text-xs">{errorMsg}</Small>
        </div>
      )}

      {/* Confirm dialogs */}
      {confirmAction && (
        <div className="p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30 space-y-2">
          <Small className="text-yellow-400 font-mono text-[10px] block">
            {confirmAction === "regenerate"
              ? "This will invalidate your current key. Continue?"
              : "This will permanently revoke your API key. You can generate a new one later."}
          </Small>
          <div className="flex gap-2">
            <button
              onClick={() => confirmAction === "regenerate" ? generateKey(true) : revokeKey()}
              disabled={isWorking}
              className="flex-1 py-1.5 rounded font-mono text-[10px] bg-yellow-500/20 text-yellow-400 hover:bg-yellow-500/30 transition-colors border border-yellow-500/30"
            >
              {isWorking ? "..." : "Confirm"}
            </button>
            <button
              onClick={() => setConfirmAction(null)}
              className="flex-1 py-1.5 rounded font-mono text-[10px] bg-[#1a1a1a] text-gray-400 hover:bg-[#2a2a2a] transition-colors border border-[#2a2a2a]"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      {/* States */}
      {keyState.status === "loading" && (
        <div className="flex items-center justify-center py-3">
          <div className="w-4 h-4 border-2 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
        </div>
      )}

      {keyState.status === "no_key" && (
        <div className="p-3 rounded-lg bg-[#1a1a1a] border border-[#2a2a2a] space-y-3">
          <Small className="text-gray-400 font-mono text-[10px] block">
            Get an API key to use the Net Library CLI and API for uploads, searches, and more.
          </Small>
          {identityBody ? (
            // Web / Farcaster member — generate key directly
            <button
              onClick={() => generateKey(false)}
              disabled={isWorking}
              className="w-full py-2 rounded font-mono text-[10px] bg-[#00ff00]/10 text-[#00ff00] hover:bg-[#00ff00]/20 transition-colors border border-[#00ff00]/20 disabled:opacity-40"
            >
              {isWorking ? "Generating..." : "Generate API Key"}
            </button>
          ) : (
            // No identity available — guide to self-register
            <div className="p-2 rounded bg-[#00ff00]/5 border border-[#00ff00]/20 space-y-1">
              <Small className="text-[#00ff00] font-mono text-[9px] block font-semibold">To get a key (headless / CLI):</Small>
              <Small className="text-gray-400 font-mono text-[9px] block">
                1. Send $2 USDC to the treasury on Base
              </Small>
              <Small className="text-gray-400 font-mono text-[9px] block">
                2. POST /api/v1/agents/membership with &#123; selfRegister: true, name, address, txHash &#125;
              </Small>
              <Small className="text-gray-400 font-mono text-[9px] block">
                3. Then POST /api/v1/membership/api-key with &#123; address &#125; to generate your key
              </Small>
            </div>
          )}
          <CliCard />
        </div>
      )}

      {keyState.status === "just_generated" && (
        <div className="p-3 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 space-y-3">
          <Small className="text-[#00ff00] font-mono text-[10px] block font-semibold">
            Your API key (save it now — shown only once):
          </Small>
          <div className="flex gap-2 items-center">
            <code className="flex-1 px-2 py-1.5 bg-black/50 rounded text-[10px] font-mono text-[#00ff00] overflow-x-auto whitespace-nowrap">
              {keyState.apiKey}
            </code>
            <button
              onClick={() => copyKey(keyState.apiKey)}
              className="px-2 py-1.5 rounded text-[10px] font-mono transition-all flex-shrink-0 bg-[#00ff00]/20 text-[#00ff00] hover:bg-[#00ff00]/30"
              title="Copy to clipboard"
            >
              {copiedKey ? <CheckIcon size={12} /> : <ClipboardIcon size={12} />}
            </button>
          </div>
          <div className="flex items-start gap-2 p-2 rounded bg-yellow-500/10 border border-yellow-500/20">
            <span className="text-yellow-400 text-xs flex-shrink-0">⚠️</span>
            <Small className="text-yellow-400 font-mono text-[9px]">
              Copy and save this key. It will not be shown again.
            </Small>
          </div>
          <CliCard apiKey={keyState.apiKey} />
        </div>
      )}

      {keyState.status === "has_key" && !confirmAction && (
        <div className="p-3 rounded-lg bg-[#1a1a1a] border border-[#2a2a2a] space-y-3">
          <div className="space-y-1">
            <div className="flex items-center gap-2">
              <Small className="text-gray-500 font-mono text-[10px]">Key:</Small>
              <Small className="text-gray-300 font-mono text-[10px]">{keyState.prefix}...</Small>
            </div>
            {keyState.createdAt && (
              <div className="flex items-center gap-2">
                <Small className="text-gray-500 font-mono text-[10px]">Created:</Small>
                <Small className="text-gray-300 font-mono text-[10px]">
                  {new Date(keyState.createdAt).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}
                </Small>
              </div>
            )}
            <div className="flex items-center gap-2">
              <Small className="text-gray-500 font-mono text-[10px]">Status:</Small>
              <span className="flex items-center gap-1">
                <span className={`w-1.5 h-1.5 rounded-full ${keyState.isActive ? "bg-[#00ff00]" : "bg-red-500"}`} />
                <Small className={`font-mono text-[10px] ${keyState.isActive ? "text-[#00ff00]" : "text-red-400"}`}>
                  {keyState.isActive ? "Active" : "Revoked"}
                </Small>
              </span>
            </div>
          </div>
          <div className="flex gap-2">
            <button
              onClick={() => setConfirmAction("regenerate")}
              className="flex-1 py-1.5 rounded font-mono text-[10px] bg-[#00ff00]/10 text-[#00ff00] hover:bg-[#00ff00]/20 transition-colors border border-[#00ff00]/20"
            >
              Regenerate Key
            </button>
            <button
              onClick={() => setConfirmAction("revoke")}
              className="flex-1 py-1.5 rounded font-mono text-[10px] bg-red-500/10 text-red-400 hover:bg-red-500/20 transition-colors border border-red-500/20"
            >
              Revoke Key
            </button>
          </div>
          <Small className="text-gray-600 font-mono text-[9px] block">
            Regenerating creates a new key and invalidates the current one.
          </Small>
          <CliCard apiKey={`${keyState.prefix}...`} />
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────────────────────
// My Passwords Section — manage saved encryption passwords (members only)
// ─────────────────────────────────────────────────────────────────────────────

interface SavedPassword {
  id: string;
  label: string;
  createdAt: number;
  updatedAt?: number;
  itemCount?: number;
}

function PasswordsSection({ userAddress, userFid }: { userAddress?: string; userFid?: number }) {
  const [passwords, setPasswords] = useState<SavedPassword[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [errorMsg, setErrorMsg] = useState<string | null>(null);

  // Per-entry reveal state: id → plaintext | null
  const [revealed, setRevealed] = useState<Record<string, string | null>>({});
  const [revealing, setRevealing] = useState<Record<string, boolean>>({});

  // Per-entry copy feedback
  const [copied, setCopied] = useState<Record<string, boolean>>({});

  // Per-entry edit-label state
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editLabel, setEditLabel] = useState("");

  // Confirm-delete state
  const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null);

  // ── build identity helpers ────────────────────────────────────────────────
  // Body-based identity for POST/PUT/DELETE (agents + web)
  const identityBody: Record<string, unknown> = {};
  if (userFid) identityBody.fid = userFid;
  if (userAddress) identityBody.address = userAddress;

  // Query-param identity for GET requests (GET has no body — web pattern matches
  // /api/membership, /api/reading-queue, etc.)
  const identityParams = new URLSearchParams();
  if (userFid) identityParams.set("fid", String(userFid));
  if (userAddress) identityParams.set("address", userAddress);
  const idQuery = identityParams.toString() ? `?${identityParams.toString()}` : "";

  // ── fetch list ────────────────────────────────────────────────────────────
  useEffect(() => {
    if (!userFid && !userAddress) {
      setPasswords([]);
      setIsLoading(false);
      return;
    }
    setIsLoading(true);
    setErrorMsg(null);

    fetch(`/api/passwords${idQuery}`, {
      method: "GET",
    })
      .then(r => r.json())
      .then((data: { passwords?: SavedPassword[] }) => {
        setPasswords(data.passwords || []);
        setIsLoading(false);
      })
      .catch(() => {
        setErrorMsg("Failed to load saved passwords.");
        setIsLoading(false);
      });
  }, [userFid, userAddress, idQuery]);

  // ── reveal password ───────────────────────────────────────────────────────
  const handleReveal = async (id: string) => {
    // If already revealed, hide it
    if (revealed[id] !== undefined) {
      setRevealed(prev => {
        const next = { ...prev };
        delete next[id];
        return next;
      });
      return;
    }

    setRevealing(prev => ({ ...prev, [id]: true }));
    try {
      const res = await fetch(`/api/passwords/${id}${idQuery}`);
      if (!res.ok) throw new Error("Failed to retrieve password");
      const data: { password: string } = await res.json();
      setRevealed(prev => ({ ...prev, [id]: data.password }));
    } catch {
      setErrorMsg("Failed to reveal password. Please try again.");
    } finally {
      setRevealing(prev => ({ ...prev, [id]: false }));
    }
  };

  // ── copy to clipboard ─────────────────────────────────────────────────────
  const handleCopy = async (id: string) => {
    let text = revealed[id];
    if (!text) {
      // Fetch silently if not yet revealed
      try {
        const res = await fetch(`/api/passwords/${id}${idQuery}`);
        if (!res.ok) throw new Error();
        const data: { password: string } = await res.json();
        text = data.password;
      } catch {
        setErrorMsg("Failed to copy password.");
        return;
      }
    }
    try {
      await navigator.clipboard.writeText(text);
    } catch {
      // Fallback for older browsers
      const el = document.createElement("textarea");
      el.value = text;
      document.body.appendChild(el);
      el.select();
      document.execCommand("copy");
      document.body.removeChild(el);
    }
    setCopied(prev => ({ ...prev, [id]: true }));
    setTimeout(() => setCopied(prev => ({ ...prev, [id]: false })), 1500);
  };

  // ── save label edit ───────────────────────────────────────────────────────
  const handleSaveLabel = async (id: string) => {
    const trimmed = editLabel.trim();
    if (!trimmed) return;
    setErrorMsg(null);
    try {
      const res = await fetch(`/api/passwords/${id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ ...identityBody, label: trimmed }),
      });
      if (!res.ok) throw new Error();
      setPasswords(prev => prev.map(p => p.id === id ? { ...p, label: trimmed } : p));
      setEditingId(null);
    } catch {
      setErrorMsg("Failed to update label.");
    }
  };

  // ── delete ────────────────────────────────────────────────────────────────
  const handleDelete = async (id: string) => {
    setErrorMsg(null);
    try {
      const res = await fetch(`/api/passwords/${id}`, {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(identityBody),
      });
      if (!res.ok) throw new Error();
      setPasswords(prev => prev.filter(p => p.id !== id));
      setConfirmDeleteId(null);
      // Clean up local state for deleted entry
      setRevealed(prev => { const n = { ...prev }; delete n[id]; return n; });
      setCopied(prev => { const n = { ...prev }; delete n[id]; return n; });
    } catch {
      setErrorMsg("Failed to delete password.");
    }
  };

  return (
    <div className="pb-3 border-b border-[#00ff00]/10 space-y-3">
      {/* Section header */}
      <div className="flex items-center gap-2">
        <LockIcon size={14} className="text-[#00ff00]" />
        <Small className="text-[#00ff00] font-mono text-[11px] uppercase tracking-wider">
          My Passwords
        </Small>
      </div>

      <Small className="text-gray-500 font-mono text-[10px] block">
        Saved encryption passwords for your encrypted library items.
      </Small>

      {/* No-recovery warning */}
      <div className="p-2 bg-yellow-500/10 border border-yellow-500/20 rounded-lg">
        <Small className="text-yellow-500/80 font-mono text-[10px] leading-relaxed block">
          ⚠ No password recovery. If you lose a password and delete your saved copy, encrypted items become permanently unreadable. Net Protocol is first-write-wins — you cannot re-encrypt existing items.
        </Small>
      </div>

      {/* Error */}
      {errorMsg && (
        <div className="p-2 bg-red-500/10 border border-red-500/30 rounded-lg">
          <Small className="text-red-400 font-mono text-xs">{errorMsg}</Small>
        </div>
      )}

      {/* Loading */}
      {isLoading ? (
        <div className="flex justify-center py-4">
          <div className="w-4 h-4 border-2 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
        </div>
      ) : passwords.length === 0 ? (
        <div className="p-3 rounded-lg bg-[#1a1a1a] border border-[#2a2a2a] text-center">
          <Small className="text-gray-500 font-mono text-[11px] block">No saved passwords yet.</Small>
          <Small className="text-gray-600 font-mono text-[10px] block mt-1">
            Passwords are saved when you encrypt an item during upload.
          </Small>
        </div>
      ) : (
        <div className="space-y-2">
          {passwords.map(pw => (
            <div key={pw.id} className="p-3 rounded-lg bg-[#1a1a1a] border border-[#2a2a2a] space-y-2">
              {/* Label row */}
              <div className="flex items-center justify-between gap-2">
                {editingId === pw.id ? (
                  <input
                    type="text"
                    value={editLabel}
                    onChange={e => setEditLabel(e.target.value)}
                    onKeyDown={e => { if (e.key === "Enter") handleSaveLabel(pw.id); if (e.key === "Escape") setEditingId(null); }}
                    autoFocus
                    className="flex-1 px-2 py-1 rounded bg-black border border-[#00ff00]/40 text-white font-mono text-xs focus:outline-none focus:border-[#00ff00]"
                  />
                ) : (
                  <P className="text-white font-mono text-xs font-semibold truncate flex-1">{pw.label}</P>
                )}

                <div className="flex items-center gap-1 flex-shrink-0">
                  {editingId === pw.id ? (
                    <>
                      <button
                        onClick={() => handleSaveLabel(pw.id)}
                        className="px-2 py-1 rounded bg-[#00ff00]/20 text-[#00ff00] font-mono text-[10px] hover:bg-[#00ff00]/30"
                      >
                        Save
                      </button>
                      <button
                        onClick={() => setEditingId(null)}
                        className="px-2 py-1 rounded bg-[#2a2a2a] text-gray-400 font-mono text-[10px] hover:text-white"
                      >
                        Cancel
                      </button>
                    </>
                  ) : (
                    <button
                      onClick={() => { setEditingId(pw.id); setEditLabel(pw.label); }}
                      className="px-2 py-1 rounded bg-[#2a2a2a] text-gray-500 font-mono text-[9px] hover:text-[#00ff00] hover:bg-[#00ff00]/10"
                    >
                      Edit
                    </button>
                  )}
                </div>
              </div>

              {/* Meta */}
              <div className="flex items-center gap-3">
                <Small className="text-gray-600 font-mono text-[9px]">
                  Saved {new Date(pw.createdAt).toLocaleDateString()}
                </Small>
                {(pw.itemCount ?? 0) > 0 && (
                  <Small className="text-gray-600 font-mono text-[9px]">
                    {pw.itemCount} item{(pw.itemCount ?? 0) !== 1 ? "s" : ""}
                  </Small>
                )}
              </div>

              {/* Password reveal row */}
              <div className="flex items-center gap-2">
                <div className="flex-1 px-2 py-1.5 rounded bg-black/50 border border-[#2a2a2a] font-mono text-xs text-gray-300 overflow-hidden truncate">
                  {revealed[pw.id] !== undefined
                    ? revealed[pw.id]
                    : "••••••••••••"}
                </div>
                <button
                  onClick={() => handleReveal(pw.id)}
                  disabled={revealing[pw.id]}
                  className="px-2 py-1.5 rounded bg-[#2a2a2a] text-gray-400 font-mono text-[9px] hover:text-white flex-shrink-0 min-w-[44px] text-center disabled:opacity-40"
                >
                  {revealing[pw.id] ? "…" : revealed[pw.id] !== undefined ? "Hide" : "Show"}
                </button>
                <button
                  onClick={() => handleCopy(pw.id)}
                  className={`px-2 py-1.5 rounded font-mono text-[9px] flex-shrink-0 min-w-[44px] text-center transition-colors ${
                    copied[pw.id]
                      ? "bg-[#00ff00]/20 text-[#00ff00]"
                      : "bg-[#2a2a2a] text-gray-400 hover:text-[#00ff00] hover:bg-[#00ff00]/10"
                  }`}
                >
                  {copied[pw.id] ? <CheckIcon size={10} /> : <ClipboardIcon size={10} />}
                </button>
              </div>

              {/* Delete */}
              {confirmDeleteId === pw.id ? (
                <div className="flex items-center gap-2 pt-1">
                  <Small className="text-red-400 font-mono text-[10px] flex-1">
                    Delete &quot;{pw.label}&quot;? Encrypted items still need it.
                  </Small>
                  <button
                    onClick={() => handleDelete(pw.id)}
                    className="px-2 py-1 rounded bg-red-500/20 text-red-400 font-mono text-[9px] hover:bg-red-500/30"
                  >
                    Delete
                  </button>
                  <button
                    onClick={() => setConfirmDeleteId(null)}
                    className="px-2 py-1 rounded bg-[#2a2a2a] text-gray-500 font-mono text-[9px] hover:text-white"
                  >
                    Cancel
                  </button>
                </div>
              ) : (
                <button
                  onClick={() => setConfirmDeleteId(pw.id)}
                  className="text-[9px] font-mono text-gray-600 hover:text-red-400 transition-colors"
                >
                  Delete
                </button>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// Unlimited Pass Section - shown within Member Resources
// NFT art URLs — CF Worker proxy (must match unlimited-storage-pass-modal.tsx)
// Raw storedon.net CDN is not used here because it corrupts binary PNG files.
const PASS_EARLY_ART = "https://netlibrary.app/img/ulp-early";
const PASS_EARLY_ISH_ART = "https://netlibrary.app/img/ulp-earlyish";
const PASS_CONTRACT_ADDRESS = "0xCe559A2A6b64504bE00aa7aA85C5C31EA93a16BB";

interface PassDetails {
  hasPass: boolean;
  tokenId?: number;
  tier?: string;
  mintTx?: string;
}

function UnlimitedPassSection() {
  const { address } = useAccount();
  const { openStoragePassModal } = useStoragePassModal();
  const [passDetails, setPassDetails] = useState<PassDetails>({ hasPass: false });
  const [isLoading, setIsLoading] = useState(true);
  const [copiedArt, setCopiedArt] = useState(false);

  useEffect(() => {
    async function checkPass() {
      if (!address) {
        setIsLoading(false);
        return;
      }

      try {
        const response = await fetch(`/api/membership/stack-pass?address=${address}`);
        const data = await response.json();
        setPassDetails({
          hasPass: data.hasStackPass || false,
          tokenId: data.unlimitedPassTokenId,
          tier: data.unlimitedPassTier,
          mintTx: data.unlimitedPassMintTx,
        });
      } catch (err) {
        console.error("Failed to check pass:", err);
      } finally {
        setIsLoading(false);
      }
    }
    checkPass();
  }, [address]);

  const artUrl =
    passDetails.tokenId && passDetails.tokenId <= 1000
      ? PASS_EARLY_ART
      : passDetails.tier === "we are so early"
      ? PASS_EARLY_ART
      : PASS_EARLY_ISH_ART;

  const copyArtLink = async () => {
    try {
      await navigator.clipboard.writeText(artUrl);
    } catch {
      const ta = document.createElement("textarea");
      ta.value = artUrl;
      document.body.appendChild(ta);
      ta.select();
      document.execCommand("copy");
      document.body.removeChild(ta);
    }
    setCopiedArt(true);
    setTimeout(() => setCopiedArt(false), 2000);
  };

  return (
    <div className="pt-3 border-t border-[#00ff00]/10 space-y-3">
      <div className="flex items-center gap-2">
        <span className="text-sm">♾️</span>
        <Small className="text-[#00ff00] font-mono text-[11px] uppercase tracking-wider">
          Unlimited Pass
        </Small>
      </div>

      {isLoading ? (
        <div className="p-4 rounded-lg bg-[#1a1a1a] border border-[#2a2a2a]">
          <div className="w-4 h-4 mx-auto border-2 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
        </div>
      ) : passDetails.hasPass ? (
        <div className="space-y-3">
          {/* NFT Art — saveable on mobile via long-press */}
          <div className="rounded-xl overflow-hidden border border-[#00ff00]/20 bg-[#111]">
            <img
              src={artUrl}
              alt={`Unlimited Pass NFT${passDetails.tokenId ? ` #${passDetails.tokenId}` : ""}`}
              className="w-full object-cover"
              style={{ maxHeight: 280 }}
              draggable
            />
            <div className="px-3 py-2 flex items-center justify-between">
              <div>
                <Small className="text-[#00ff00] font-mono font-bold block">
                  {passDetails.tokenId
                    ? `Unlimited Pass #${passDetails.tokenId}`
                    : "Unlimited Pass"}
                </Small>
                {passDetails.tier && (
                  <Small className="text-gray-500 font-mono text-[9px]">
                    {passDetails.tier === "we are so early"
                      ? '"we are so early"'
                      : '"early-ish"'}
                  </Small>
                )}
              </div>
              <span className="text-[#00ff00] text-lg">✓</span>
            </div>
          </div>

          {/* Pass details */}
          <div className="p-3 rounded-lg bg-[#1a1a1a] border border-[#2a2a2a] space-y-2">
            {passDetails.tokenId && (
              <div className="flex items-center justify-between">
                <Small className="text-gray-500 font-mono">Token ID</Small>
                <Small className="text-white font-mono">#{passDetails.tokenId}</Small>
              </div>
            )}
            {passDetails.tier && (
              <div className="flex items-center justify-between">
                <Small className="text-gray-500 font-mono">Tier</Small>
                <Small className="text-white font-mono">{passDetails.tier}</Small>
              </div>
            )}
            {passDetails.mintTx && (
              <div className="flex items-center justify-between">
                <Small className="text-gray-500 font-mono">Mint Tx</Small>
                <a
                  href={`https://basescan.org/tx/${passDetails.mintTx}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-[#00ff00] font-mono text-[10px] underline"
                >
                  {passDetails.mintTx.slice(0, 8)}...{passDetails.mintTx.slice(-4)} ↗
                </a>
              </div>
            )}
            <div className="flex items-center justify-between">
              <Small className="text-gray-500 font-mono">Contract</Small>
              <a
                href={`https://basescan.org/token/${PASS_CONTRACT_ADDRESS}`}
                target="_blank"
                rel="noopener noreferrer"
                className="text-[#00ff00] font-mono text-[10px] underline"
              >
                {PASS_CONTRACT_ADDRESS.slice(0, 8)}... ↗
              </a>
            </div>
          </div>

          {/* Art CDN link — copyable */}
          <div className="p-2.5 rounded-lg bg-[#0d0d0d] border border-[#2a2a2a] space-y-1.5">
            <Small className="text-gray-500 font-mono text-[9px] uppercase block">Art CDN</Small>
            <div className="flex gap-2 items-start">
              <code className="flex-1 text-[9px] font-mono text-[#00ff00]/60 break-all leading-relaxed">
                {artUrl}
              </code>
              <button
                onClick={copyArtLink}
                className="shrink-0 px-2 py-1 rounded bg-[#00ff00]/10 text-[#00ff00] text-[9px] font-mono hover:bg-[#00ff00]/20 transition-colors"
              >
                {copiedArt ? "✓" : "Copy"}
              </button>
            </div>
          </div>

          {/* Hazza.name perk */}
          <div className="p-3 rounded-lg bg-purple-500/5 border border-purple-500/20 space-y-2">
            <div className="flex items-center gap-2">
              <span className="text-purple-400 text-sm">🌐</span>
              <Small className="text-purple-300 font-mono font-semibold text-[11px]">
                Free hazza.name Registration
              </Small>
            </div>
            <Small className="text-gray-400 font-mono text-[10px] leading-relaxed block">
              Every Unlimited Pass holder gets 1 free name registration on{" "}
              <a
                href="https://hazza.name"
                target="_blank"
                rel="noopener noreferrer"
                className="text-purple-400 underline"
              >
                hazza.name
              </a>
              {" "}— a decentralized onchain name registry on Base. Your hazza.name resolves
              to your wallet address and works across web3 apps.
            </Small>
            <a
              href="https://hazza.name"
              target="_blank"
              rel="noopener noreferrer"
              className="block w-full py-2 text-center rounded-lg bg-purple-500/20 text-purple-300 font-mono text-xs hover:bg-purple-500/30 transition-colors border border-purple-500/30"
            >
              Claim Your Free hazza.name →
            </a>
          </div>
        </div>
      ) : (
        <div className="p-4 rounded-lg bg-[#1a1a1a] border border-[#2a2a2a]">
          <div className="flex items-start gap-3 mb-3">
            <div className="w-10 h-10 rounded-full bg-[#00ff00]/10 flex items-center justify-center flex-shrink-0">
              <span className="text-lg">♾️</span>
            </div>
            <div>
              <P className="text-white font-mono text-sm font-semibold">Unlimited Pass</P>
              <Small className="text-gray-500 font-mono">${STORAGE_PASS_PRICE_USD} USDC · One-time NFT mint</Small>
            </div>
          </div>

          <div className="space-y-2 mb-3">
            <div className="flex items-center gap-2">
              <span className="text-[#00ff00] text-xs">✓</span>
              <Small className="text-gray-400 font-mono">Unlimited onchain storage</Small>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-[#00ff00] text-xs">✓</span>
              <Small className="text-gray-400 font-mono">1 free hazza.name registration</Small>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-[#00ff00] text-xs">✓</span>
              <Small className="text-gray-400 font-mono">Unlimited items in stacks</Small>
            </div>
            <div className="flex items-center gap-2">
              <span className="text-purple-400 text-xs">★</span>
              <Small className="text-gray-400 font-mono">Free membership (first 1000 minters)</Small>
            </div>
          </div>

          <button
            onClick={openStoragePassModal}
            className="w-full py-2.5 rounded-lg font-mono text-sm bg-[#00ff00]/10 text-[#00ff00] hover:bg-[#00ff00]/20 transition-colors border border-[#00ff00]/30"
          >
            Mint Unlimited Pass
          </button>
        </div>
      )}
    </div>
  );
}
src/features/app/components/add-funds-modal.tsx
"use client";

/**
 * Add Funds Modal - x402 USDC Relay Funding (v3)
 *
 * Shows funding options matching Net Protocol's production UI.
 * Fixed presets: $0.10, $0.25, $5.00 USDC (no custom amounts)
 *
 * With proper x402 integration:
 * - User selects amount and clicks Fund
 * - Hook calls SDK's fundBackendWallet() which handles x402 flow automatically
 * - SDK intercepts 402 response, signs EIP-3009 authorization
 * - Facilitator executes USDC transfer (user doesn't pay gas for USDC transfer!)
 * - Backend wallet is funded with ETH for storage transactions
 *
 * Also includes "Recover Funds" feature to verify any unprocessed payments.
 */

import { useState, useCallback, useEffect } from "react";
import { Small, H4, P } from "@neynar/ui";
import { SearchIcon, CheckCircleIcon } from "@/components/icons/net-library-icons";

interface AddFundsModalProps {
  isOpen: boolean;
  onClose: () => void;
  requiredAmount?: string; // Upload cost (optional - not shown when simply adding funds)
  currentBalance: string; // Current Upload Wallet balance
  onBalanceRefresh?: () => void;
  onFundWallet?: (amount: number) => Promise<boolean>;
  onFundingSuccess?: () => void; // Called after successful funding - use to trigger upload
  onRecoverFunds?: () => Promise<{ recovered: number; total: number } | null>; // Recover unverified payments
  /** If true, we're adding funds standalone (not during upload) - hide upload cost info */
  isStandaloneAddFunds?: boolean;
}

// Fixed preset amounts matching Net Protocol's production UI
const PRESET_AMOUNTS = [0.10, 0.25, 5.00] as const;

export function AddFundsModal({
  isOpen,
  onClose,
  requiredAmount,
  currentBalance,
  onBalanceRefresh,
  onFundWallet,
  onFundingSuccess,
  onRecoverFunds,
  isStandaloneAddFunds = false,
}: AddFundsModalProps) {
  const [isCheckingBalance, setIsCheckingBalance] = useState(false);
  const [isFunding, setIsFunding] = useState(false);
  const [isRecovering, setIsRecovering] = useState(false);
  const [fundingError, setFundingError] = useState<string | null>(null);
  const [recoveryResult, setRecoveryResult] = useState<{ recovered: number; total: number } | null>(null);
  const [selectedPreset, setSelectedPreset] = useState<number>(PRESET_AMOUNTS[0]);

  const uploadCost = requiredAmount ? Number(requiredAmount) : 0;
  const balance = Number(currentBalance);
  const shortfall = uploadCost > 0 ? Math.max(0, uploadCost - balance) : 0;
  // For standalone add funds, we don't check against upload cost - just if balance is above minimum
  const hasSufficientFunds = isStandaloneAddFunds ? balance >= 0.1 : balance >= uploadCost;

  // Reset selection when modal opens
  useEffect(() => {
    if (isOpen) {
      setSelectedPreset(PRESET_AMOUNTS[0]);
      setFundingError(null);
      setRecoveryResult(null);
    }
  }, [isOpen]);

  const handleCheckBalance = useCallback(async () => {
    setIsCheckingBalance(true);
    setFundingError(null);
    await onBalanceRefresh?.();
    setIsCheckingBalance(false);
  }, [onBalanceRefresh]);

  const handleFundWallet = useCallback(async () => {
    if (!onFundWallet) return;

    console.log("[AddFundsModal] handleFundWallet called with preset:", selectedPreset);

    setIsFunding(true);
    setFundingError(null);
    try {
      console.log("[AddFundsModal] Calling onFundWallet with amount:", selectedPreset);
      const success = await onFundWallet(selectedPreset);
      console.log("[AddFundsModal] onFundWallet returned:", success);
      if (success) {
        await onBalanceRefresh?.();
        // Trigger upload after successful funding
        console.log("[AddFundsModal] Funding succeeded, triggering onFundingSuccess callback");
        onFundingSuccess?.();
      } else {
        setFundingError("Funding failed. Please try again.");
      }
    } catch (error) {
      console.error("[AddFundsModal] onFundWallet error:", error);
      setFundingError(error instanceof Error ? error.message : "Funding failed");
    } finally {
      setIsFunding(false);
    }
  }, [onFundWallet, onBalanceRefresh, onFundingSuccess, selectedPreset]);

  const handleRecoverFunds = useCallback(async () => {
    if (!onRecoverFunds) return;

    setIsRecovering(true);
    setFundingError(null);
    setRecoveryResult(null);

    try {
      const result = await onRecoverFunds();
      if (result) {
        setRecoveryResult(result);
        if (result.recovered > 0) {
          await onBalanceRefresh?.();
        }
      }
    } catch (error) {
      console.error("[AddFundsModal] Recovery error:", error);
      setFundingError(error instanceof Error ? error.message : "Recovery failed");
    } finally {
      setIsRecovering(false);
    }
  }, [onRecoverFunds, onBalanceRefresh]);

  const handlePresetClick = (amount: number) => {
    setSelectedPreset(amount);
    setFundingError(null);
  };

  // Format amount for display (show cents for small amounts)
  const formatAmount = (amount: number) => {
    if (amount < 1) {
      return `${(amount * 100).toFixed(0)}¢`;
    }
    return `$${amount.toFixed(2)}`;
  };

  if (!isOpen) return null;

  // Success state - balance is now sufficient
  if (hasSufficientFunds && !isStandaloneAddFunds) {
    return (
      <div className="fixed inset-0 bg-black/90 flex items-center justify-center z-50 p-4" onClick={onClose}>
        <div className="bg-[#0a0a0a] border border-green-500/30 rounded-lg p-4 w-full max-w-xs" onClick={(e) => e.stopPropagation()}>
          <div className="text-center">
            <div className="mb-2 flex justify-center"><CheckCircleIcon size={40} className="text-green-400" /></div>
            <P className="text-green-400 font-mono font-bold">Ready to Upload!</P>
            <Small className="text-gray-400 font-mono block mt-1 mb-4">
              Balance: ${balance.toFixed(4)}
            </Small>
            <button
              onClick={onClose}
              className="w-full py-3 rounded-lg bg-[#00ff00] text-black font-mono text-sm font-bold hover:bg-[#00dd00] transition-all"
            >
              Continue
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="fixed inset-0 bg-black/90 flex items-center justify-center z-50 p-4" onClick={onClose}>
      <div
        className="bg-[#0a0a0a] border border-purple-500/30 rounded-lg p-4 w-full max-w-xs"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between mb-3">
          <H4 className="text-purple-400 font-mono text-sm">Add Funds</H4>
          <button
            onClick={onClose}
            className="w-6 h-6 rounded-full bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white text-xs"
          >
            ✕
          </button>
        </div>

        {/* Info section */}
        <div className="bg-black/50 border border-purple-500/20 rounded-lg p-3 mb-3">
          {/* Only show upload cost when we're funding during an upload, not standalone */}
          {!isStandaloneAddFunds && uploadCost > 0 && (
            <Small className="text-gray-400 font-mono block mb-2">
              This upload costs <span className="text-white">~${uploadCost.toFixed(4)}</span>
            </Small>
          )}
          <Small className="text-gray-400 font-mono block mb-2">
            Your balance: <span className={balance < 0.1 ? "text-red-400" : "text-[#9ca3af]"}>${balance.toFixed(4)}</span>
          </Small>
          {!isStandaloneAddFunds && shortfall > 0 && (
            <div className="border-t border-purple-500/20 pt-2 mt-2">
              <Small className="text-purple-300 font-mono">
                Minimum needed: ${shortfall.toFixed(4)}
              </Small>
            </div>
          )}
        </div>

        {/* Amount Selection - Fixed presets only */}
        {onFundWallet && (
          <div className="space-y-3 mb-3">
            {/* Preset Amounts - 3 buttons matching Net Protocol */}
            <div>
              <Small className="text-gray-400 font-mono block mb-2">Choose amount:</Small>
              <div className="grid grid-cols-3 gap-2">
                {PRESET_AMOUNTS.map((amt) => (
                  <button
                    key={amt}
                    type="button"
                    onClick={() => handlePresetClick(amt)}
                    disabled={isFunding}
                    className={`py-3 rounded font-mono text-sm transition-all ${
                      selectedPreset === amt
                        ? "bg-purple-500 text-white border border-purple-400"
                        : "bg-[#1a1a1a] border border-purple-500/20 text-purple-400 hover:bg-purple-500/10"
                    } disabled:opacity-50`}
                  >
                    {formatAmount(amt)}
                  </button>
                ))}
              </div>
            </div>

            {/* Selected Amount Display */}
            <div className="text-center py-3 px-4 bg-purple-500/10 border border-purple-500/20 rounded-lg">
              <Small className="text-gray-400 font-mono block text-center">You will fund:</Small>
              <P className="text-purple-400 font-mono font-bold text-xl text-center mt-1">
                ${selectedPreset.toFixed(2)} USDC
              </P>
            </div>

            {/* Fund Button */}
            <button
              type="button"
              onClick={(e) => {
                e.preventDefault();
                e.stopPropagation();
                handleFundWallet();
              }}
              disabled={isFunding}
              className="w-full py-3 rounded-lg bg-purple-500 text-white font-mono text-sm font-bold hover:bg-purple-600 disabled:opacity-50 transition-all active:scale-95"
            >
              {isFunding ? (
                <span className="flex items-center justify-center gap-2">
                  <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  Funding...
                </span>
              ) : (
                "Fund Upload Wallet"
              )}
            </button>
          </div>
        )}

        {/* Error display */}
        {fundingError && (
          <div className="bg-red-500/10 border border-red-500/30 rounded-lg p-2 mb-3">
            <Small className="text-red-400 font-mono text-[10px]">{fundingError}</Small>
          </div>
        )}

        {/* Recovery result */}
        {recoveryResult && (
          <div className={`${recoveryResult.recovered > 0 ? 'bg-green-500/10 border-green-500/30' : 'bg-yellow-500/10 border-yellow-500/30'} border rounded-lg p-2 mb-3`}>
            <Small className={`${recoveryResult.recovered > 0 ? 'text-green-400' : 'text-yellow-400'} font-mono text-[10px]`}>
              {recoveryResult.recovered > 0
                ? <><CheckCircleIcon size={12} className="inline mr-1" /> Recovered {recoveryResult.recovered} of {recoveryResult.total} payment(s)!</>
                : `No unverified payments found.`}
            </Small>
          </div>
        )}

        {/* Helper links */}
        <div className="flex gap-2 mb-3">
          <a
            href="https://app.uniswap.org/swap?chain=base&outputCurrency=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
            target="_blank"
            rel="noopener noreferrer"
            className="flex-1 py-2 rounded bg-[#1a1a1a] text-center text-gray-400 font-mono text-[10px] hover:text-white hover:bg-[#222] transition-all"
          >
            Get USDC ↗
          </a>
          <button
            onClick={handleCheckBalance}
            disabled={isCheckingBalance}
            className="flex-1 py-2 rounded bg-[#1a1a1a] text-gray-400 font-mono text-[10px] hover:text-white hover:bg-[#222] disabled:opacity-50 transition-all"
          >
            {isCheckingBalance ? "..." : "Refresh"}
          </button>
        </div>

        {/* Recover Funds button - for unverified payments */}
        {onRecoverFunds && (
          <button
            onClick={handleRecoverFunds}
            disabled={isRecovering || isFunding}
            className="w-full py-2 rounded bg-[#1a1a1a] border border-yellow-500/20 text-yellow-400 font-mono text-[10px] hover:bg-yellow-500/10 disabled:opacity-50 transition-all mb-3"
          >
            {isRecovering ? (
              <span className="flex items-center justify-center gap-2">
                <span className="w-3 h-3 border-2 border-yellow-400/30 border-t-yellow-400 rounded-full animate-spin" />
                Checking...
              </span>
            ) : (
              <><SearchIcon size={14} className="inline mr-1" /> Recover Unverified Payments</>
            )}
          </button>
        )}

        {/* How it works */}
        <details className="mb-3">
          <summary className="text-gray-500 font-mono text-[10px] cursor-pointer hover:text-gray-300">
            How does this work?
          </summary>
          <div className="mt-2 p-2 bg-black/30 rounded text-gray-400 font-mono text-[10px] leading-relaxed">
            Your Upload Wallet pays for storage transactions automatically. Fund it once with USDC, then upload without interruptions. Each file costs ~$0.01-0.10. Only you can use your Upload Wallet.
          </div>
        </details>

        {/* Cancel */}
        <button
          onClick={onClose}
          className="w-full py-2 text-gray-500 font-mono text-xs hover:text-gray-300 transition-colors"
        >
          Cancel
        </button>
      </div>
    </div>
  );
}
src/features/app/components/add-to-stack-modal.tsx
"use client";

import { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { useAccount } from "wagmi";
import { Card, CardContent, P, Small } from "@neynar/ui";
import { useUserStacks } from "@/hooks/use-stacks";
import { LinkIcon } from "@/components/icons/net-library-icons";
import { CoverImage } from "./cover-image";
import type { Stack, Book } from "@/features/app/types";

// Get effective cover URL - prefer coverUrl, fallback to cdnUrl for image/video content
function getEffectiveCoverUrl(item: { coverUrl?: string; cdnUrl?: string; mediaType?: string }): string | undefined {
  if (item.coverUrl) return item.coverUrl;
  if (item.cdnUrl && item.mediaType && ["image", "video"].includes(item.mediaType)) return item.cdnUrl;
  return undefined;
}

interface AddToStackModalProps {
  isOpen: boolean;
  onClose: () => void;
  book: Book;
  onSuccess?: () => void;
  onCreateStack?: () => void;
}

export function AddToStackModal({
  isOpen,
  onClose,
  book,
  onSuccess,
  onCreateStack,
}: AddToStackModalProps) {
  const { address } = useAccount();
  const { stacks, isLoading, refresh } = useUserStacks();
  const [selectedStackId, setSelectedStackId] = useState<string | null>(null);
  const [isAdding, setIsAdding] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [mounted, setMounted] = useState(false);

  // Track client-side mount for portal
  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (isOpen) {
      setSelectedStackId(null);
      setError(null);
      setSuccessMessage(null);
      refresh();
    }
  }, [isOpen, refresh]);

  if (!isOpen || !mounted) return null;

  const handleAddToStack = async (stack: Stack) => {
    if (!book.contentKey || !address) {
      setError("Cannot add item - missing content key or wallet");
      return;
    }

    setIsAdding(true);
    setSelectedStackId(stack.id);
    setError(null);
    setSuccessMessage(null);

    try {
      const response = await fetch("/api/stacks", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          stackId: stack.id,
          action: "add-item",
          owner: address,
          contentKey: book.contentKey,
        }),
      });

      const result = await response.json();

      if (result.success) {
        setSuccessMessage(`Added to "${stack.name}"!`);
        onSuccess?.();
        setTimeout(() => {
          onClose();
        }, 1500);
      } else if (result.requiresUnlock) {
        setError(`Stack is full (${stack.itemCount}/20). Unlock for $${result.cost} USDC for unlimited items.`);
      } else {
        setError(result.error || "Failed to add item");
      }
    } catch (err) {
      console.error("[AddToStackModal] Error:", err);
      setError("An error occurred. Please try again.");
    } finally {
      setIsAdding(false);
      setSelectedStackId(null);
    }
  };

  const modalContent = (
    <div
      className="fixed inset-0 bg-black/90 z-[9999] flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div onClick={(e) => e.stopPropagation()} className="w-full max-w-sm">
        <Card className="bg-[#0a0a0a] border border-[#00ff00]/30 overflow-hidden">
          <CardContent className="p-4 space-y-3">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2 flex-1 min-w-0">
                <div className="w-6 h-8 rounded bg-[#1a1a1a] shrink-0 overflow-hidden">
                  <CoverImage
                    src={getEffectiveCoverUrl(book)}
                    alt={book.title}
                    className="w-full h-full object-cover"
                    fallbackClassName="w-full h-full flex items-center justify-center"
                    fallbackLogoSize="w-4 h-4"
                  />
                </div>
                <div className="min-w-0">
                  <P className="text-xs font-mono text-gray-400 truncate">Add to stack:</P>
                  <P className="text-sm font-mono text-white truncate">{book.title}</P>
                </div>
              </div>
              <button
                onClick={onClose}
                className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors shrink-0 ml-2"
              >
                ✕
              </button>
            </div>

            {successMessage && (
              <div className="p-2 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg">
                <P className="text-[#00ff00] font-mono text-sm text-center">
                  ✓ {successMessage}
                </P>
              </div>
            )}

            {error && (
              <div className="p-2 bg-red-500/10 border border-red-500/30 rounded-lg">
                <P className="text-red-400 font-mono text-sm">{error}</P>
              </div>
            )}

            <div className="space-y-2 max-h-64 overflow-y-auto">
              {!address ? (
                <div className="text-center py-6">
                  <LinkIcon size={32} className="text-gray-500 mx-auto mb-3" />
                  <P className="text-gray-400 font-mono">Connect wallet to add to stacks</P>
                </div>
              ) : isLoading ? (
                <div className="text-center py-6">
                  <div className="text-3xl mb-3 animate-pulse">📂</div>
                  <P className="text-[#00ff00] font-mono">Loading your stacks...</P>
                </div>
              ) : stacks.length === 0 ? (
                <div className="text-center py-6">
                  <div className="text-3xl mb-3">📂</div>
                  <P className="text-gray-400 font-mono">No stacks yet</P>
                  <Small className="text-gray-500 font-mono block mt-1">
                    Create a stack to start organizing items
                  </Small>
                  {onCreateStack && (
                    <button
                      onClick={() => {
                        onClose();
                        onCreateStack();
                      }}
                      className="mt-4 px-4 py-2 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg text-[#00ff00] font-mono text-sm hover:bg-[#00ff00]/20 transition-colors"
                    >
                      + Create Stack
                    </button>
                  )}
                </div>
              ) : (
                [...stacks]
                  .sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0))
                  .map((stack) => {
                    const isFull = !stack.unlocked && stack.itemCount >= 20;
                    const isSelected = selectedStackId === stack.id;

                    return (
                      <button
                        key={stack.id}
                        onClick={() => !isFull && handleAddToStack(stack)}
                        disabled={isAdding || isFull}
                        className={`w-full p-3 rounded-lg border transition-all text-left ${
                          isFull
                            ? "bg-[#0a0a0a] border-[#1a1a1a] opacity-50 cursor-not-allowed"
                            : isSelected
                            ? "bg-[#00ff00]/20 border-[#00ff00]/50"
                            : "bg-[#0a0a0a] border-[#1a1a1a] hover:border-[#00ff00]/50"
                        }`}
                      >
                        <div className="flex items-center gap-3">
                          <div className="flex-1 min-w-0">
                            <P className="text-sm font-mono text-white truncate">{stack.name}</P>
                            <Small className={`font-mono ${
                              isFull
                                ? "text-red-400"
                                : !stack.unlocked && stack.itemCount >= 15
                                ? "text-yellow-400"
                                : "text-gray-500"
                            }`}>
                              {stack.itemCount}/{stack.unlocked ? "∞" : "20"} items
                              {isFull && " (full)"}
                            </Small>
                          </div>
                          <div className="shrink-0">
                            {isSelected && isAdding ? (
                              <div className="w-6 h-6 border-2 border-[#00ff00] border-t-transparent rounded-full animate-spin" />
                            ) : isFull ? (
                              <span className="text-xs text-red-400 font-mono font-bold">FULL</span>
                            ) : (
                              <span className="text-[#00ff00] text-lg">+</span>
                            )}
                          </div>
                        </div>
                      </button>
                    );
                  })
              )}
            </div>

            {address && stacks.length > 0 && onCreateStack && (
              <button
                onClick={() => {
                  onClose();
                  onCreateStack();
                }}
                className="w-full py-3 bg-[#1a1a1a] border border-[#333] rounded-lg text-gray-400 font-mono text-sm hover:border-[#00ff00]/50 hover:text-[#00ff00] transition-colors"
              >
                + Create New Stack
              </button>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  );

  return createPortal(modalContent, document.body);
}
src/features/app/components/airdrop-modal.tsx
"use client";

import { useState, useEffect, useCallback, useRef } from "react";
import { H4, P, Small } from "@neynar/ui";
import { WalletIcon, WarningIcon, BanIcon, CheckCircleIcon, FarcasterIcon, BaseIcon, WebIcon } from "@/components/icons/net-library-icons";
import { useAccount, useBalance, useWriteContract, useWaitForTransactionReceipt, useSendTransaction, useCapabilities, useSendCalls, useCallsStatus } from "wagmi";
import { parseUnits, formatUnits, encodeFunctionData, type Address } from "viem";
import { base } from "viem/chains";
import type { MemberEntry } from "@/lib/net-protocol";
import { useUserProfile } from "@/hooks/use-user-profile";

// ERC20 ABI for transfer
const ERC20_ABI = [
  {
    name: "transfer",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "to", type: "address" },
      { name: "amount", type: "uint256" },
    ],
    outputs: [{ type: "bool" }],
  },
] as const;

// Fallback ETH price if fetch fails
const FALLBACK_ETH_USD_PRICE = 2500;

// Token info from wallet
interface WalletToken {
  symbol: string;
  name: string;
  address: Address | null; // null for native ETH
  decimals: number;
  balance: bigint;
  balanceFormatted: string;
  logoUrl?: string;
  usdValue?: number; // Total USD value of the balance
  usdPrice?: number; // Price per token in USD
}

interface AirdropModalProps {
  isOpen: boolean;
  onClose: () => void;
  isMember: boolean;
  members: MemberEntry[];
}

type RecipientMode = "all" | "early" | "select";

export function AirdropModal({ isOpen, onClose, isMember, members }: AirdropModalProps) {
  const { address, isConnected, chainId } = useAccount();
  const { profile: userProfile } = useUserProfile();
  const [tokens, setTokens] = useState<WalletToken[]>([]);
  const [isLoadingTokens, setIsLoadingTokens] = useState(true);
  const [selectedTokenAddress, setSelectedTokenAddress] = useState<Address | null | undefined>(undefined);
  const [amountPerMember, setAmountPerMember] = useState("");
  const [isTokenDropdownOpen, setIsTokenDropdownOpen] = useState(false);
  const [isAirdropping, setIsAirdropping] = useState(false);
  const [ethUsdPrice, setEthUsdPrice] = useState(FALLBACK_ETH_USD_PRICE);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // EIP-5792 Batch transaction support
  const { data: capabilities } = useCapabilities();
  // Check both numeric and hex chainId formats for atomicBatch support
  const numericChainId = chainId ?? base.id;
  const hexChainId = `0x${numericChainId.toString(16)}`;

  // Debug log capabilities
  useEffect(() => {
    if (capabilities) {
      console.log("[AirdropModal] Wallet capabilities:", JSON.stringify(capabilities, null, 2));
      console.log("[AirdropModal] Checking chainId:", numericChainId, "hex:", hexChainId);
    }
  }, [capabilities, numericChainId, hexChainId]);

  // Farcaster wallets (Coinbase Smart Wallet) support batch transactions natively
  // So we assume batch is supported when using the Farcaster SDK wallet
  const isFarcasterWallet = !!userProfile?.fid && isConnected;

  const capabilitiesSupportBatch =
    capabilities?.[numericChainId]?.atomicBatch?.supported === true ||
    capabilities?.[hexChainId as unknown as number]?.atomicBatch?.supported === true ||
    // Also check for atomic_batch (some wallets use underscore)
    (capabilities?.[numericChainId] as Record<string, { supported?: boolean }>)?.atomic_batch?.supported === true ||
    (capabilities?.[hexChainId as unknown as number] as Record<string, { supported?: boolean }>)?.atomic_batch?.supported === true;

  // Always support batch for Farcaster wallets (Coinbase Smart Wallet)
  const supportsBatch = capabilitiesSupportBatch || isFarcasterWallet;
  const { sendCallsAsync } = useSendCalls();
  const [currentBatchId, setCurrentBatchId] = useState<string | undefined>();

  // Recipient selection state (declared early for batch status tracking)
  // Now tracks by address (lowercase) since users can have multiple member IDs
  const [recipientMode, setRecipientMode] = useState<RecipientMode>("all");
  const [selectedAddresses, setSelectedAddresses] = useState<Set<string>>(new Set());

  // Grouped member for airdrop display - shows all member numbers per user
  interface GroupedAirdropMember {
    address: string; // Canonical address for airdrops
    fid: number | undefined;
    username: string | undefined;
    memberNumbers: number[]; // All member IDs for this user
    primaryMemberId: number; // Lowest member ID (for sorting)
    canonicalPlatform: "farcaster" | "base-app" | "web" | undefined; // Platform of first signup
    unlimitedPassTier?: string; // "we are so early" | "early-ish" | undefined
  }

  // Get all members excluding self, grouped by address (one entry per unique user)
  // This prevents users with multiple memberships from receiving tokens multiple times
  const allEligibleMembers = (() => {
    const grouped = new Map<string, GroupedAirdropMember>();
    // Sort by memberId first so lowest ID becomes primary
    const sorted = [...members].sort((a, b) => a.memberId - b.memberId);

    for (const m of sorted) {
      if (!m.address) continue;
      const addr = m.address.toLowerCase();

      // Exclude self by connected wallet address
      if (addr === address?.toLowerCase()) continue;

      // Exclude self by FID (handles Base App users whose connected wallet
      // differs from their Farcaster-linked membership wallet)
      if (userProfile?.fid && m.fid === userProfile.fid) continue;

      if (grouped.has(addr)) {
        // Add member number to existing group
        grouped.get(addr)!.memberNumbers.push(m.memberId);
      } else {
        // Create new group - first membership determines canonical platform
        // Legacy members (no signupPlatform) default to Farcaster since Base App came later
        const inferredPlatform = m.signupPlatform || "farcaster";
        grouped.set(addr, {
          address: m.address,
          fid: m.fid,
          // Prefer farcasterUsername (the handle, e.g. "cherylfromnet") over
          // username (which may be a display name like "Cheryl")
          username: m.farcasterUsername || m.username,
          memberNumbers: [m.memberId],
          primaryMemberId: m.memberId,
          canonicalPlatform: inferredPlatform,
          unlimitedPassTier: m.unlimitedPassTier,
        });
      }
    }

    // Return sorted by primary member ID
    return Array.from(grouped.values()).sort((a, b) => a.primaryMemberId - b.primaryMemberId);
  })();

  // Get actual recipients based on mode (needed for batch status tracking)
  // Now uses address-based selection for simplicity
  const eligibleMembers = recipientMode === "all"
    ? allEligibleMembers
    : recipientMode === "early"
    ? allEligibleMembers.filter(m => m.unlimitedPassTier === "we are so early")
    : allEligibleMembers.filter(m => m.address && selectedAddresses.has(m.address.toLowerCase()));

  // Track batch status
  const { data: callsStatus } = useCallsStatus({
    id: currentBatchId as string,
    query: {
      enabled: !!currentBatchId,
      refetchInterval: (data) => {
        if (data.state.data?.status === "success" || data.state.data?.status === "failure") {
          return false;
        }
        return 2000;
      },
    },
  });

  // Handle batch transaction completion
  useEffect(() => {
    if (!currentBatchId || !isAirdropping) return;

    console.log("[AirdropModal] callsStatus updated:", callsStatus?.status);

    if (callsStatus?.status === "success") {
      console.log("[AirdropModal] Batch transaction succeeded!");
      setCompletedTransfers(eligibleMembers.length);
      setIsAirdropping(false);
      setSuccess(true);
      setCurrentBatchId(undefined);
    } else if (callsStatus?.status === "failure") {
      console.log("[AirdropModal] Batch transaction failed");
      setError("Batch transaction failed");
      setIsAirdropping(false);
      setCurrentBatchId(undefined);
    }
  }, [callsStatus?.status, currentBatchId, isAirdropping, eligibleMembers.length]);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsTokenDropdownOpen(false);
      }
    };

    if (isTokenDropdownOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      return () => document.removeEventListener("mousedown", handleClickOutside);
    }
  }, [isTokenDropdownOpen]);
  const [currentRecipient, setCurrentRecipient] = useState(0);
  const [completedTransfers, setCompletedTransfers] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  // Get native ETH balance
  const { data: ethBalance } = useBalance({
    address: address,
    chainId: base.id,
  });

  // Write contract for ERC20 transfers
  const { writeContract, data: txHash, isPending: isWritePending, reset: resetWrite } = useWriteContract();

  // Send transaction for ETH transfers
  const { sendTransaction, data: ethTxHash, isPending: isEthPending, reset: resetEthSend } = useSendTransaction();

  // Wait for transaction receipt (ERC20)
  const { isLoading: isConfirming, isSuccess: isConfirmed } = useWaitForTransactionReceipt({
    hash: txHash,
  });

  // Wait for ETH transaction receipt
  const { isLoading: isEthConfirming, isSuccess: isEthConfirmed } = useWaitForTransactionReceipt({
    hash: ethTxHash,
  });

  // Fetch current ETH price from CoinGecko
  const fetchEthPrice = useCallback(async () => {
    try {
      console.log("[AirdropModal] Fetching current ETH price...");
      const response = await fetch(
        "https://api.coingecko.com/api/v3/simple/price?ids=ethereum&vs_currencies=usd",
        { cache: "no-store" }
      );

      if (response.ok) {
        const data = await response.json();
        const price = data?.ethereum?.usd;
        if (price && typeof price === "number") {
          console.log("[AirdropModal] ETH price fetched:", price);
          setEthUsdPrice(price);
          return price;
        }
      }
      console.log("[AirdropModal] Using fallback ETH price:", FALLBACK_ETH_USD_PRICE);
      return FALLBACK_ETH_USD_PRICE;
    } catch (err) {
      console.error("[AirdropModal] Failed to fetch ETH price:", err);
      return FALLBACK_ETH_USD_PRICE;
    }
  }, []);

  // Fetch user's token balances from API
  const fetchWalletTokens = useCallback(async (currentEthPrice: number) => {
    if (!address) {
      console.log("[AirdropModal] No wallet address available");
      setTokens([]);
      setIsLoadingTokens(false);
      return;
    }

    console.log("[AirdropModal] Fetching tokens for connected wallet address:", address, "ETH price:", currentEthPrice);
    setIsLoadingTokens(true);

    try {
      // Fetch ERC20 tokens from our API - only check the connected Farcaster wallet address
      const apiUrl = `/api/wallet-tokens?address=${address}`;
      console.log("[AirdropModal] Calling API:", apiUrl);
      const response = await fetch(apiUrl);
      console.log("[AirdropModal] API response status:", response.status);
      const data = await response.json();

      console.log("[AirdropModal] Wallet tokens response:", JSON.stringify(data, null, 2));

      // Start with ETH if we have a balance
      const allTokens: WalletToken[] = [];

      if (ethBalance && ethBalance.value > 0n) {
        const ethBalanceFormatted = formatUnits(ethBalance.value, 18);
        const ethUsdValue = parseFloat(ethBalanceFormatted) * currentEthPrice;
        // Only add ETH if worth at least $0.01
        if (ethUsdValue >= 0.01) {
          allTokens.push({
            symbol: "ETH",
            name: "Ethereum",
            address: null,
            decimals: 18,
            balance: ethBalance.value,
            balanceFormatted: ethBalanceFormatted,
            usdValue: ethUsdValue,
            usdPrice: currentEthPrice,
          });
        }
      }

      // Add ERC20 tokens from API
      console.log("[AirdropModal] API data.tokens:", data.tokens, "count:", data.count);
      if (data.tokens && Array.isArray(data.tokens)) {
        console.log("[AirdropModal] Processing", data.tokens.length, "ERC20 tokens from API");
        for (const token of data.tokens) {
          console.log("[AirdropModal] Adding token:", token.symbol, token.balanceFormatted, "USD:", token.usdValue);
          // Convert address string to proper type and add to list
          allTokens.push({
            symbol: token.symbol,
            name: token.name,
            address: token.address as Address,
            decimals: token.decimals,
            balance: BigInt(token.balance),
            balanceFormatted: token.balanceFormatted,
            logoUrl: token.logoUrl,
            usdValue: token.usdValue,
            usdPrice: token.usdPrice,
          });
        }
      } else {
        console.log("[AirdropModal] No tokens in API response or invalid format");
      }

      // Sort all tokens by USD value (highest first)
      allTokens.sort((a, b) => {
        // Both have USD values - sort by value
        if (a.usdValue !== undefined && b.usdValue !== undefined) {
          return b.usdValue - a.usdValue;
        }
        // Only a has USD value - a comes first
        if (a.usdValue !== undefined) return -1;
        // Only b has USD value - b comes first
        if (b.usdValue !== undefined) return 1;
        // Neither has USD value - sort by balance
        const aBalance = parseFloat(a.balanceFormatted);
        const bBalance = parseFloat(b.balanceFormatted);
        return bBalance - aBalance;
      });

      console.log("[AirdropModal] Combined tokens (sorted by USD value):", allTokens.length, allTokens.map(t => `${t.symbol}:$${t.usdValue?.toFixed(2) || 'N/A'}`));
      setTokens(allTokens);
    } catch (err) {
      console.error("[AirdropModal] Failed to fetch tokens:", err);
      // Fallback to ETH only if worth at least $0.01
      if (ethBalance && ethBalance.value > 0n) {
        const ethBalanceFormatted = formatUnits(ethBalance.value, 18);
        const ethUsdValue = parseFloat(ethBalanceFormatted) * currentEthPrice;
        if (ethUsdValue >= 0.01) {
          setTokens([{
            symbol: "ETH",
            name: "Ethereum",
            address: null,
            decimals: 18,
            balance: ethBalance.value,
            balanceFormatted: ethBalanceFormatted,
            usdValue: ethUsdValue,
            usdPrice: currentEthPrice,
          }]);
        }
      }
    } finally {
      setIsLoadingTokens(false);
    }
  }, [address, ethBalance]);

  // Track if we've already fetched tokens for this modal open
  const [hasFetchedTokens, setHasFetchedTokens] = useState(false);

  // Reset hasFetchedTokens when modal closes
  useEffect(() => {
    if (!isOpen) {
      setHasFetchedTokens(false);
    }
  }, [isOpen]);

  // Fetch ETH price and tokens when modal opens
  useEffect(() => {
    if (isOpen && address && !hasFetchedTokens) {
      setHasFetchedTokens(true);
      // First fetch ETH price, then fetch tokens with that price
      fetchEthPrice().then((price) => {
        fetchWalletTokens(price);
      });
    }
  }, [isOpen, address, hasFetchedTokens, fetchEthPrice, fetchWalletTokens]);

  const selectedToken = tokens.find(t =>
    selectedTokenAddress === undefined ? false :
    selectedTokenAddress === null ? t.address === null :
    t.address?.toLowerCase() === selectedTokenAddress?.toLowerCase()
  );

  const totalRecipients = eligibleMembers.length;
  const amountPerMemberNum = parseFloat(amountPerMember) || 0;
  const totalAmount = amountPerMemberNum * totalRecipients;

  // Check if user has enough balance
  const hasEnoughBalance = selectedToken
    ? parseFloat(selectedToken.balanceFormatted) >= totalAmount
    : false;

  // Can proceed with airdrop
  const canAirdrop = selectedToken && amountPerMemberNum > 0 && hasEnoughBalance && !isAirdropping && totalRecipients > 0;

  // Toggle member selection (by address)
  const toggleMemberSelection = (memberAddress: string) => {
    const addr = memberAddress.toLowerCase();
    setSelectedAddresses(prev => {
      const newSet = new Set(prev);
      if (newSet.has(addr)) {
        newSet.delete(addr);
      } else {
        newSet.add(addr);
      }
      return newSet;
    });
  };

  // Select all members
  const selectAllMembers = () => {
    setSelectedAddresses(new Set(allEligibleMembers.filter(m => m.address).map(m => m.address!.toLowerCase())));
  };

  // Deselect all members
  const deselectAllMembers = () => {
    setSelectedAddresses(new Set());
  };

  // Handle transaction confirmation (ERC20)
  useEffect(() => {
    if (isConfirmed && isAirdropping && selectedToken?.address !== null) {
      handleTransferComplete();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isConfirmed]);

  // Handle ETH transaction confirmation
  useEffect(() => {
    if (isEthConfirmed && isAirdropping && selectedToken?.address === null) {
      handleTransferComplete();
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isEthConfirmed]);

  const handleTransferComplete = () => {
    setCompletedTransfers(prev => prev + 1);

    // Send next transfer or finish
    if (currentRecipient < eligibleMembers.length - 1) {
      setCurrentRecipient(prev => prev + 1);
      sendTransfer(currentRecipient + 1);
    } else {
      // All done!
      setIsAirdropping(false);
      setSuccess(true);
    }
  };

  const sendTransfer = async (recipientIndex: number) => {
    const recipient = eligibleMembers[recipientIndex];
    if (!recipient || !selectedToken) return;

    const amountInWei = parseUnits(amountPerMember, selectedToken.decimals);

    try {
      if (selectedToken.address === null) {
        // ETH transfer
        sendTransaction({
          to: recipient.address as Address,
          value: amountInWei,
          chainId: base.id,
        });
      } else {
        // ERC20 transfer
        writeContract({
          address: selectedToken.address,
          abi: ERC20_ABI,
          functionName: "transfer",
          args: [recipient.address as Address, amountInWei],
          chainId: base.id,
        });
      }
    } catch (err) {
      console.error("[AirdropModal] Transfer error:", err);
      setError(err instanceof Error ? err.message : "Transfer failed");
      setIsAirdropping(false);
    }
  };

  // Batch airdrop using EIP-5792 (single signature for all transfers!)
  const handleBatchAirdrop = async () => {
    console.log("[AirdropModal] handleBatchAirdrop called");
    console.log("[AirdropModal] eligibleMembers count:", eligibleMembers.length);
    console.log("[AirdropModal] all members count:", members.length);
    console.log("[AirdropModal] allEligibleMembers count:", allEligibleMembers.length);
    console.log("[AirdropModal] recipientMode:", recipientMode);

    if (!canAirdrop || !selectedToken) return;

    setIsAirdropping(true);
    setCurrentRecipient(0);
    setCompletedTransfers(0);
    setError(null);
    setSuccess(false);

    try {
      const amountInWei = parseUnits(amountPerMember, selectedToken.decimals);

      if (selectedToken.address === null) {
        // ETH batch transfer - each call goes to a different member
        const calls = eligibleMembers.map((member) => ({
          to: member.address as `0x${string}`,
          value: amountInWei,
        }));

        console.log("[AirdropModal] ETH batch calls:", calls.length, "recipients:", calls.map(c => c.to));

        const result = await sendCallsAsync({
          calls,
          chainId: base.id,
        });

        const batchId = typeof result === 'string' ? result : result.id;
        console.log("[AirdropModal] Batch ETH transfer started, batchId:", batchId);
        setCurrentBatchId(batchId);

      } else {
        // ERC20 batch transfer - each call goes to token contract with different recipient in data
        const calls = eligibleMembers.map((member) => ({
          to: selectedToken.address as `0x${string}`,
          data: encodeFunctionData({
            abi: ERC20_ABI,
            functionName: "transfer",
            args: [member.address as Address, amountInWei],
          }),
        }));

        console.log("[AirdropModal] ==================== BATCH ERC20 TRANSFER ====================");
        console.log("[AirdropModal] Total calls:", calls.length);
        console.log("[AirdropModal] Token contract:", selectedToken.address);
        console.log("[AirdropModal] Amount per recipient:", amountPerMember, selectedToken.symbol);
        console.log("[AirdropModal] Recipients:");
        eligibleMembers.forEach((m, i) => {
          console.log(`[AirdropModal]   ${i + 1}. ${m.username || 'unknown'} - ${m.address}`);
        });
        console.log("[AirdropModal] ===============================================================");

        const result = await sendCallsAsync({
          calls,
          chainId: base.id,
        });

        const batchId = typeof result === 'string' ? result : result.id;
        console.log("[AirdropModal] Batch ERC20 transfer started, batchId:", batchId);
        setCurrentBatchId(batchId);
      }

      // Don't wait in a loop - the useEffect watching callsStatus will handle completion
      // Just show progress animation
      console.log("[AirdropModal] Batch submitted, waiting for callsStatus hook to update...");

    } catch (err) {
      console.error("[AirdropModal] Batch airdrop error:", err);
      // Check if user rejected
      if (err instanceof Error && (err.name === 'UserRejectedRequestError' || err.message.includes('user rejected') || err.message.includes('User rejected'))) {
        setIsAirdropping(false);
        setCurrentBatchId(undefined);
        return;
      }
      setError(err instanceof Error ? err.message : "Batch airdrop failed");
      setIsAirdropping(false);
      setCurrentBatchId(undefined);
    }
  };

  const handleStartAirdrop = () => {
    if (!canAirdrop) return;

    // Use batch mode if wallet supports it and we have multiple recipients
    if (supportsBatch && eligibleMembers.length > 1) {
      handleBatchAirdrop();
      return;
    }

    // Fallback to sequential mode
    setIsAirdropping(true);
    setCurrentRecipient(0);
    setCompletedTransfers(0);
    setError(null);
    setSuccess(false);
    resetWrite();
    resetEthSend();

    // Start first transfer
    sendTransfer(0);
  };

  const handleClose = () => {
    if (isAirdropping) return; // Don't close while airdropping
    setSelectedTokenAddress(undefined);
    setAmountPerMember("");
    setError(null);
    setSuccess(false);
    setIsAirdropping(false);
    setCurrentRecipient(0);
    setCompletedTransfers(0);
    setRecipientMode("all");
    setSelectedAddresses(new Set());
    setCurrentBatchId(undefined);
    onClose();
  };

  if (!isOpen) return null;

  // Not a member - show error
  if (!isMember) {
    return (
      <div
        className="fixed inset-0 bg-black/90 z-[60] flex items-center justify-center p-4"
        onClick={handleClose}
      >
        <div
          className="bg-[#0a0a0a] border border-red-500/30 rounded-xl max-w-sm w-full p-6"
          onClick={(e) => e.stopPropagation()}
        >
          <div className="text-center">
            <div className="mb-4 flex justify-center"><BanIcon size={48} className="text-red-400" /></div>
            <H4 className="text-red-400 font-mono mb-2">Members Only</H4>
            <P className="text-gray-400 font-mono text-sm mb-6">
              The airdrop feature is only available to Net Library members. Join the library to unlock this feature!
            </P>
            <button
              onClick={handleClose}
              className="w-full py-3 rounded-lg bg-[#1a1a1a] text-white font-mono hover:bg-[#222] transition-colors"
            >
              Got it
            </button>
          </div>
        </div>
      </div>
    );
  }

  // Success state - show receipt with all recipients
  if (success) {
    return (
      <div
        className="fixed inset-0 bg-black/90 z-[60] flex items-center justify-center p-4"
        onClick={handleClose}
      >
        <div
          className="bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl max-w-sm w-full max-h-[80vh] flex flex-col"
          onClick={(e) => e.stopPropagation()}
        >
          {/* Header */}
          <div className="p-6 pb-4 text-center shrink-0">
            <div className="mb-4 flex justify-center"><CheckCircleIcon size={48} className="text-[#00ff00]" /></div>
            <H4 className="text-[#00ff00] font-mono mb-2">Airdrop Complete!</H4>
            <P className="text-gray-400 font-mono text-sm mb-2">
              Successfully sent {amountPerMember} {selectedToken?.symbol} to {completedTransfers} member{completedTransfers !== 1 ? "s" : ""}
            </P>
            <P className="text-[#00ff00] font-mono text-lg">
              Total: {totalAmount.toFixed(selectedToken?.decimals === 6 ? 2 : 4)} {selectedToken?.symbol}
            </P>
          </div>

          {/* Recipients list */}
          <div className="flex-1 overflow-y-auto px-6 min-h-0">
            <Small className="text-gray-500 font-mono mb-2 block">Recipients:</Small>
            <div className="bg-[#111] rounded-lg border border-[#1a1a1a] divide-y divide-[#1a1a1a]">
              {eligibleMembers.map((member) => (
                <div key={member.address} className="px-3 py-2 flex items-center justify-between gap-2">
                  <div className="flex items-center gap-2 min-w-0">
                    {member.canonicalPlatform === "farcaster" ? (
                      <FarcasterIcon size={12} className="text-purple-400" />
                    ) : member.canonicalPlatform === "web" ? (
                      <WebIcon size={12} className="text-yellow-400" />
                    ) : (
                      <BaseIcon size={12} className="text-blue-400" />
                    )}
                    <span className="text-white font-mono text-xs truncate">
                      {member.username ? `@${member.username}` : `${(member.address || '').slice(0, 6)}...${(member.address || '').slice(-4)}`}
                    </span>
                  </div>
                  <span className="text-[#00ff00] font-mono text-xs shrink-0">
                    +{amountPerMember} {selectedToken?.symbol}
                  </span>
                </div>
              ))}
            </div>
          </div>

          {/* Footer */}
          <div className="p-6 pt-4 shrink-0">
            <button
              onClick={handleClose}
              className="w-full py-3 rounded-lg bg-[#00ff00] text-black font-mono font-bold hover:bg-[#00ff00]/90 transition-colors"
            >
              Done
            </button>
          </div>
        </div>
      </div>
    );
  }

  const isPending = isWritePending || isEthPending;
  const isConfirmingTx = isConfirming || isEthConfirming;

  return (
    <div className="fixed inset-0 bg-black z-[60] flex flex-col">
      {/* Header */}
      <div className="shrink-0 px-4 py-3 border-b border-[#00ff00]/30 flex items-center justify-between bg-black">
        <div>
          <H4 className="text-[#00ff00] font-mono">Airdrop Tokens</H4>
          <Small className="text-gray-500 font-mono">
            {recipientMode === "all"
              ? `Send to all ${allEligibleMembers.length} members`
              : recipientMode === "early"
              ? `Send to ${eligibleMembers.length} early holder${eligibleMembers.length !== 1 ? "s" : ""}`
              : `Send to ${selectedAddresses.size} selected member${selectedAddresses.size !== 1 ? "s" : ""}`}
          </Small>
        </div>
        <button
          onClick={handleClose}
          disabled={isAirdropping}
          className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors disabled:opacity-50"
        >
          ✕
        </button>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-4">
        {/* Error message */}
        {error && (
          <div className="mb-4 p-3 rounded-lg bg-red-500/10 border border-red-500/30">
            <P className="text-red-400 font-mono text-sm">{error}</P>
          </div>
        )}

        {/* Airdrop Progress */}
        {isAirdropping && (
          <div className={`mb-6 p-4 rounded-lg ${currentBatchId ? "bg-green-500/10 border-green-500/30" : "bg-[#00ff00]/10 border-[#00ff00]/30"} border`}>
            {currentBatchId ? (
              <>
                <div className="flex items-center justify-center gap-2 mb-2">
                  <span className="text-lg">🚀</span>
                  <P className="text-green-400 font-mono text-center">
                    Batch Transfer in Progress
                  </P>
                </div>
                <Small className="text-gray-400 font-mono text-center block mb-2">
                  All {totalRecipients} transfers in a single transaction!
                </Small>
                <div className="w-full h-2 bg-[#1a1a1a] rounded-full overflow-hidden">
                  <div
                    className="h-full bg-gradient-to-r from-green-500 to-green-400 transition-all duration-300 animate-pulse"
                    style={{ width: `${Math.max(10, (completedTransfers / totalRecipients) * 100)}%` }}
                  />
                </div>
                <Small className="text-green-400/70 font-mono text-center block mt-2">
                  {callsStatus?.status === "pending" ? "Processing on chain..." : "Waiting for confirmation..."}
                </Small>
              </>
            ) : (
              <>
                <P className="text-[#00ff00] font-mono text-center mb-2">
                  Sending airdrop... ({completedTransfers}/{totalRecipients})
                </P>
                <div className="w-full h-2 bg-[#1a1a1a] rounded-full overflow-hidden">
                  <div
                    className="h-full bg-[#00ff00] transition-all duration-300"
                    style={{ width: `${(completedTransfers / totalRecipients) * 100}%` }}
                  />
                </div>
                {(isPending || isConfirmingTx) && (
                  <Small className="text-gray-400 font-mono text-center block mt-2">
                    {isPending ? "Confirm in wallet..." : "Waiting for confirmation..."}
                  </Small>
                )}
              </>
            )}
          </div>
        )}

        {/* Recipient Mode Selection */}
        <div className="mb-6">
          <label className="block text-gray-400 font-mono text-sm mb-2">Recipients</label>
          <div className="grid grid-cols-3 gap-2">
            <button
              onClick={() => setRecipientMode("all")}
              disabled={isAirdropping}
              className={`p-3 rounded-lg border font-mono text-sm transition-colors ${
                recipientMode === "all"
                  ? "border-[#00ff00] bg-[#00ff00]/10 text-[#00ff00]"
                  : "border-[#1a1a1a] bg-[#0a0a0a] text-gray-400 hover:border-[#333]"
              } disabled:opacity-50`}
            >
              <div className="text-lg mb-1">👥</div>
              <div className="font-bold">Send to All</div>
              <div className="text-xs opacity-70">{allEligibleMembers.length} members</div>
            </button>
            <button
              onClick={() => setRecipientMode("early")}
              disabled={isAirdropping}
              className={`p-3 rounded-lg border font-mono text-sm transition-colors ${
                recipientMode === "early"
                  ? "border-purple-400 bg-purple-400/10 text-purple-300"
                  : "border-[#1a1a1a] bg-[#0a0a0a] text-gray-400 hover:border-[#333]"
              } disabled:opacity-50`}
            >
              <div className="text-lg mb-1">✨</div>
              <div className="font-bold">Early Holders</div>
              <div className="text-xs opacity-70">{allEligibleMembers.filter(m => m.unlimitedPassTier === "we are so early").length} holders</div>
            </button>
            <button
              onClick={() => setRecipientMode("select")}
              disabled={isAirdropping}
              className={`p-3 rounded-lg border font-mono text-sm transition-colors ${
                recipientMode === "select"
                  ? "border-[#00ff00] bg-[#00ff00]/10 text-[#00ff00]"
                  : "border-[#1a1a1a] bg-[#0a0a0a] text-gray-400 hover:border-[#333]"
              } disabled:opacity-50`}
            >
              <div className="text-lg mb-1">✓</div>
              <div className="font-bold">Select Members</div>
              <div className="text-xs opacity-70">Choose specific</div>
            </button>
          </div>
        </div>

        {/* Member Selection (only when in select mode) */}
        {recipientMode === "select" && (
          <div className="mb-6">
            <div className="flex items-center justify-between mb-3">
              <label className="text-gray-400 font-mono text-sm">
                Select Members ({selectedAddresses.size}/{allEligibleMembers.length})
              </label>
            </div>

            {/* Select All / Unselect All buttons */}
            <div className="flex gap-2 mb-3">
              <button
                onClick={selectAllMembers}
                disabled={isAirdropping || selectedAddresses.size === allEligibleMembers.length}
                className="flex-1 py-2 px-3 rounded-lg border border-[#00ff00]/30 bg-[#00ff00]/10 text-[#00ff00] font-mono text-sm hover:bg-[#00ff00]/20 transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
              >
                ✓ Select All
              </button>
              <button
                onClick={deselectAllMembers}
                disabled={isAirdropping || selectedAddresses.size === 0}
                className="flex-1 py-2 px-3 rounded-lg border border-gray-600/30 bg-[#1a1a1a] text-gray-400 font-mono text-sm hover:bg-[#222] transition-colors disabled:opacity-30 disabled:cursor-not-allowed"
              >
                ✕ Unselect All
              </button>
            </div>
            <div className="max-h-48 overflow-y-auto bg-[#0a0a0a] border border-[#1a1a1a] rounded-lg">
              {allEligibleMembers.filter(m => m.address).map((member) => {
                const isSelected = selectedAddresses.has(member.address!.toLowerCase());
                return (
                  <button
                    key={member.address}
                    onClick={() => toggleMemberSelection(member.address!)}
                    disabled={isAirdropping}
                    className={`w-full flex items-center gap-3 px-3 py-2.5 border-b border-[#1a1a1a] last:border-b-0 transition-colors ${
                      isSelected ? "bg-[#00ff00]/10" : "hover:bg-[#111]"
                    } disabled:opacity-50`}
                  >
                    {/* Checkbox */}
                    <div className={`w-5 h-5 rounded border-2 flex items-center justify-center shrink-0 ${
                      isSelected
                        ? "border-[#00ff00] bg-[#00ff00]"
                        : "border-gray-600"
                    }`}>
                      {isSelected && (
                        <span className="text-black text-xs font-bold">✓</span>
                      )}
                    </div>

                    {/* Member info: username, FID, member numbers */}
                    <div className="flex items-center gap-2 flex-wrap flex-1 min-w-0">
                      <span className="text-white font-mono text-sm truncate">
                        {member.username ? `@${member.username}` : `${(member.address || '').slice(0, 6)}...${(member.address || '').slice(-4)}`}
                      </span>
                      {member.fid && (
                        <span className="text-[10px] font-mono text-purple-400">
                          FID {member.fid}
                        </span>
                      )}
                      <span className="text-[11px] text-[#00ff00] font-mono">
                        #{member.memberNumbers.join(", #")}
                      </span>
                    </div>

                    {/* Canonical address indicator - purple FC, blue Base, yellow Web */}
                    <div className="shrink-0" title={`Airdrop goes to ${member.canonicalPlatform === "farcaster" ? "Farcaster" : member.canonicalPlatform === "web" ? "Web" : "Base App"} wallet`}>
                      <span className={`text-[11px] font-mono ${member.canonicalPlatform === "farcaster" ? "text-purple-400" : member.canonicalPlatform === "web" ? "text-yellow-400" : "text-blue-400"}`}>✓</span>
                    </div>
                  </button>
                );
              })}
            </div>
            {selectedAddresses.size === 0 && (
              <Small className="text-yellow-500 font-mono mt-2 block">
                Select at least one member to continue
              </Small>
            )}
          </div>
        )}

        {/* Token Selection - Dropdown */}
        <div className="mb-6">
          <div className="flex items-center justify-between mb-2">
            <label className="text-gray-400 font-mono text-sm">Select Token</label>
            {ethUsdPrice !== FALLBACK_ETH_USD_PRICE && (
              <Small className="text-gray-500 font-mono">
                ETH: ${ethUsdPrice.toLocaleString()}
              </Small>
            )}
          </div>
          {isLoadingTokens ? (
            <div className="p-4 rounded-lg bg-[#0a0a0a] border border-[#1a1a1a] text-center">
              <P className="text-gray-500 font-mono text-sm animate-pulse">Loading wallet tokens...</P>
            </div>
          ) : tokens.length === 0 ? (
            <div className="p-4 rounded-lg bg-[#0a0a0a] border border-[#1a1a1a] text-center">
              <P className="text-gray-500 font-mono text-sm">No tokens found in wallet</P>
            </div>
          ) : (
            <div className="relative" ref={dropdownRef}>
              {/* Custom dropdown trigger */}
              <button
                type="button"
                onClick={() => !isAirdropping && setIsTokenDropdownOpen(!isTokenDropdownOpen)}
                disabled={isAirdropping}
                className="w-full p-3 rounded-lg bg-[#0a0a0a] border border-[#1a1a1a] text-white font-mono focus:outline-none focus:border-[#00ff00] disabled:opacity-50 cursor-pointer text-left flex items-center justify-between"
              >
                <span className={selectedToken ? "text-white" : "text-gray-500"}>
                  {selectedToken
                    ? `${selectedToken.symbol} - ${parseFloat(selectedToken.balanceFormatted).toFixed(selectedToken.decimals === 6 ? 2 : 4)} available`
                    : "Select a token..."}
                </span>
                <svg
                  className={`w-5 h-5 text-[#00ff00] transition-transform ${isTokenDropdownOpen ? "rotate-180" : ""}`}
                  fill="none"
                  viewBox="0 0 24 24"
                  stroke="currentColor"
                >
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                </svg>
              </button>

              {/* Custom dropdown menu */}
              {isTokenDropdownOpen && (
                <div className="absolute top-full left-0 right-0 mt-1 bg-[#0a0a0a] border border-[#1a1a1a] rounded-lg overflow-hidden z-10 max-h-40 overflow-y-auto">
                  {tokens.map((token) => (
                    <button
                      key={token.address || "ETH"}
                      type="button"
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        console.log("[AirdropModal] Token selected:", token.symbol, "address:", token.address);
                        setSelectedTokenAddress(token.address);
                        setIsTokenDropdownOpen(false);
                      }}
                      className={`w-full p-3 text-left font-mono text-sm hover:bg-[#1a1a1a] transition-colors flex items-center gap-2 ${
                        (selectedTokenAddress === token.address) ||
                        (selectedTokenAddress === null && token.address === null)
                          ? "bg-[#00ff00]/10 text-[#00ff00]"
                          : "text-white"
                      }`}
                    >
                      {token.logoUrl ? (
                        <img src={token.logoUrl} alt={token.symbol} className="w-5 h-5 rounded-full" />
                      ) : (
                        <div className="w-5 h-5 rounded-full bg-[#00ff00]/20 flex items-center justify-center">
                          <span className="text-[#00ff00] text-xs font-bold">{token.symbol.slice(0, 1)}</span>
                        </div>
                      )}
                      <span>{token.symbol}</span>
                      <div className="ml-auto text-right">
                        <span className="text-gray-500 block">
                          {parseFloat(token.balanceFormatted).toFixed(token.decimals === 6 ? 2 : 4)}
                        </span>
                        {token.usdValue !== undefined && (
                          <span className="text-[#00ff00]/60 text-xs">
                            ${token.usdValue.toFixed(2)}
                          </span>
                        )}
                      </div>
                    </button>
                  ))}
                </div>
              )}
            </div>
          )}

          {/* Selected token info */}
          {selectedToken && (
            <div className="mt-3 p-3 rounded-lg bg-[#00ff00]/5 border border-[#00ff00]/20">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  {selectedToken.logoUrl ? (
                    <img src={selectedToken.logoUrl} alt={selectedToken.symbol} className="w-6 h-6 rounded-full" />
                  ) : (
                    <div className="w-6 h-6 rounded-full bg-[#00ff00]/20 flex items-center justify-center">
                      <span className="text-[#00ff00] text-xs font-bold">{selectedToken.symbol.slice(0, 2)}</span>
                    </div>
                  )}
                  <div>
                    <P className="text-white font-mono text-sm font-bold">{selectedToken.symbol}</P>
                    <Small className="text-gray-500 font-mono">{selectedToken.name}</Small>
                  </div>
                </div>
                <div className="text-right">
                  <P className="text-[#00ff00] font-mono text-sm">
                    {parseFloat(selectedToken.balanceFormatted).toFixed(selectedToken.decimals === 6 ? 2 : 4)}
                  </P>
                  <Small className="text-gray-500 font-mono">Balance</Small>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Amount Input */}
        <div className="mb-6">
          <label className="block text-gray-400 font-mono text-sm mb-2">
            Amount per member
          </label>
          <div className="relative">
            <input
              type="number"
              value={amountPerMember}
              onChange={(e) => setAmountPerMember(e.target.value)}
              placeholder="0.00"
              disabled={!selectedToken || isAirdropping}
              className="w-full p-3 pr-20 rounded-lg bg-[#0a0a0a] border border-[#1a1a1a] text-white font-mono text-lg focus:outline-none focus:border-[#00ff00] disabled:opacity-50"
            />
            {selectedToken && (
              <span className="absolute right-3 top-1/2 -translate-y-1/2 text-gray-500 font-mono">
                {selectedToken.symbol}
              </span>
            )}
          </div>
          {selectedToken && amountPerMemberNum > 0 && totalRecipients > 0 && (
            <div className="mt-2 text-sm font-mono">
              <div className="flex justify-between">
                <Small className="text-gray-500">
                  Total: {totalAmount.toFixed(selectedToken.decimals === 6 ? 2 : 4)} {selectedToken.symbol} → {totalRecipients} recipient{totalRecipients !== 1 ? "s" : ""}
                </Small>
                {hasEnoughBalance && (
                  <Small className="text-[#00ff00]">✓</Small>
                )}
              </div>
              {!hasEnoughBalance && (
                <div className="mt-2 p-3 rounded-lg bg-red-500/10 border border-red-500/30">
                  <P className="text-red-400 font-mono text-sm flex items-center gap-1">
                    <WalletIcon size={14} /> You need {totalAmount.toFixed(selectedToken.decimals === 6 ? 2 : 4)} {selectedToken.symbol} but only have {parseFloat(selectedToken.balanceFormatted).toFixed(selectedToken.decimals === 6 ? 2 : 4)}
                  </P>
                  <Small className="text-red-400/70 font-mono mt-1 block">
                    Try reducing the amount per member or selecting fewer recipients
                  </Small>
                </div>
              )}
            </div>
          )}
        </div>
      </div>

      {/* Footer */}
      <div className="shrink-0 p-4 border-t border-[#00ff00]/30 bg-black">
        {/* Batch mode indicator with recipient preview */}
        {supportsBatch && totalRecipients > 1 && !isAirdropping && (
          <div className="mb-3 p-2 rounded-lg bg-green-500/10 border border-green-500/30">
            <div className="flex items-center justify-center gap-2 mb-1">
              <span className="text-sm">🚀</span>
              <Small className="text-green-400 font-mono text-center">
                Batch mode: 1 signature for all {totalRecipients} transfers!
              </Small>
            </div>
            <Small className="text-green-400/60 font-mono text-center block text-xs">
              Sending to: {eligibleMembers.slice(0, 3).map(m => m.username ? `@${m.username}` : `#${m.primaryMemberId}`).join(", ")}
              {eligibleMembers.length > 3 && ` +${eligibleMembers.length - 3} more`}
            </Small>
          </div>
        )}
        {!supportsBatch && totalRecipients > 1 && !isAirdropping && (
          <div className="mb-3 p-2 rounded-lg bg-yellow-500/10 border border-yellow-500/30">
            <Small className="text-yellow-400/80 font-mono text-center flex items-center justify-center gap-1">
              <WarningIcon size={12} /> Sequential mode: {totalRecipients} signatures required
            </Small>
          </div>
        )}
        <button
          onClick={handleStartAirdrop}
          disabled={!canAirdrop}
          className={`w-full py-4 rounded-lg font-mono font-bold text-lg transition-colors ${
            canAirdrop
              ? supportsBatch && totalRecipients > 1
                ? "bg-green-500 text-black hover:bg-green-400"
                : "bg-[#00ff00] text-black hover:bg-[#00ff00]/90"
              : "bg-[#1a1a1a] text-gray-500 cursor-not-allowed"
          }`}
        >
          {isAirdropping
            ? "AIRDROPPING..."
            : totalRecipients === 0
            ? "SELECT RECIPIENTS"
            : supportsBatch && totalRecipients > 1
            ? `🚀 BATCH AIRDROP TO ${totalRecipients} MEMBERS`
            : `AIRDROP TO ${totalRecipients} MEMBER${totalRecipients !== 1 ? "S" : ""}`}
        </button>
        {!isConnected && (
          <Small className="text-gray-500 font-mono text-center block mt-2">
            Connect wallet to airdrop
          </Small>
        )}
      </div>
    </div>
  );
}
src/features/app/components/batch-cdn-import.tsx
"use client";

import { useState, useCallback } from "react";
import { Card, CardContent, Button, Small, H4 } from "@neynar/ui";
import { LinkIcon, InfoIcon, ImageIcon } from "@/components/icons/net-library-icons";
import type { Category, Stack } from "@/features/app/types";
import { detectContentType, type ContentType } from "./cdn-link-upload";

// Get icon for content type
function getContentTypeIcon(type: ContentType): string {
  switch (type) {
    case "pdf": return "📄";
    case "image": return "🖼️";
    case "audio": return "🎵";
    case "video": return "🎬";
    case "text": return "📝";
    default: return "📦";
  }
}

// Pending CDN link item
interface CdnLinkItem {
  id: string;
  url: string;
  title: string;
  author: string;
  contentType: ContentType;
  categories: string[];
  coverArtUrl?: string;
  coverArtFile?: File;
  coverArtPreview?: string;
  status: "pending" | "uploading" | "complete" | "error";
  error?: string;
}

interface BatchCdnImportProps {
  categories: Category[];
  stacks: Stack[];
  isLoadingStacks: boolean;
  onImport: (items: Array<{
    cdnUrl: string;
    contentType: ContentType;
    title: string;
    author: string;
    selectedCategories: string[];
    selectedStackIds: string[];
    coverArtUrl?: string;
    coverArtFile?: File;
  }>) => Promise<void>;
  onCancel: () => void;
  isImporting: boolean;
}

export function BatchCdnImport({
  categories,
  stacks,
  isLoadingStacks,
  onImport,
  onCancel,
  isImporting,
}: BatchCdnImportProps) {
  const [urlInput, setUrlInput] = useState("");
  const [items, setItems] = useState<CdnLinkItem[]>([]);
  const [selectedStackIds, setSelectedStackIds] = useState<string[]>([]);
  const [showStackDropdown, setShowStackDropdown] = useState(false);
  const [parseError, setParseError] = useState<string | null>(null);

  // Validate a Net Protocol URL - accepts /storage/load/, /storage/raw/, or /chunked-storage/file/
  // Note: /content/{key} is DEPRECATED and returns 404 - reject it
  const isValidNetProtocolUrl = (url: string): boolean => {
    try {
      const parsedUrl = new URL(url);
      if (!parsedUrl.hostname.endsWith("storedon.net")) return false;

      const pathname = parsedUrl.pathname;
      // Pattern 1: /net/{chainId}/storage/load/{operator}/{filename} - PREFERRED user-facing format
      const loadMatch = pathname.match(/\/net\/\d+\/storage\/load\/([^/]+)\/(.+)/);
      if (loadMatch) {
        const [, operator, filename] = loadMatch;
        return operator.startsWith("0x") && filename.length > 0;
      }
      // Pattern 2: /net/{chainId}/storage/raw/{operator}/{key}
      const rawMatch = pathname.match(/\/net\/\d+\/storage\/raw\/([^/]+)\/(.+)/);
      if (rawMatch) {
        const [, , storageKey] = rawMatch;
        return storageKey.startsWith("0x") || /^[a-fA-F0-9]{64}$/.test(storageKey);
      }
      // Pattern 3: /net/{chainId}/chunked-storage/file/{operator}/{key}
      const chunkedMatch = pathname.match(/\/net\/\d+\/chunked-storage\/file\/([^/]+)\/(.+)/);
      if (chunkedMatch) {
        const [, , storageKey] = chunkedMatch;
        return storageKey.startsWith("0x") || /^[a-fA-F0-9]{64}$/.test(storageKey);
      }
      // Note: /content/{key} format is DEPRECATED and returns 404 - reject it
      return false;
    } catch {
      return false;
    }
  };

  // Parse URLs from textarea (one per line)
  const parseUrls = useCallback((text: string) => {
    const lines = text.split("\n").filter(line => line.trim());
    const newItems: CdnLinkItem[] = [];
    const invalidUrls: string[] = [];

    for (const line of lines) {
      const url = line.trim();
      if (!url) continue;

      // Skip if already added
      if (items.some(item => item.url === url)) continue;

      // Validate Net Protocol URL format
      if (!isValidNetProtocolUrl(url)) {
        invalidUrls.push(url.length > 50 ? url.substring(0, 50) + "..." : url);
        continue;
      }

      const contentType = detectContentType(url);
      const fileName = url.split("/").pop()?.split("?")[0] || "Untitled";
      const title = fileName.replace(/\.[^.]+$/, "").replace(/[-_]/g, " ");

      newItems.push({
        id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
        url,
        title,
        author: "",
        contentType,
        categories: [],
        status: "pending",
      });
    }

    if (newItems.length > 0) {
      setItems(prev => [...prev, ...newItems]);
      setUrlInput("");
      if (invalidUrls.length > 0) {
        setParseError(`${newItems.length} valid URL(s) added. ${invalidUrls.length} invalid URL(s) skipped (must be storedon.net with valid path).`);
      } else {
        setParseError(null);
      }
    } else if (text.trim()) {
      setParseError("No valid URLs found. Only storedon.net URLs with /storage/load/, /storage/raw/, or /chunked-storage/file/ paths are supported.");
    }
  }, [items]);

  // Update item metadata
  const updateItem = (id: string, updates: Partial<CdnLinkItem>) => {
    setItems(prev => prev.map(item =>
      item.id === id ? { ...item, ...updates } : item
    ));
  };

  // Remove item
  const removeItem = (id: string) => {
    setItems(prev => prev.filter(item => item.id !== id));
  };

  // Toggle category for item
  const toggleItemCategory = (itemId: string, categoryId: string) => {
    setItems(prev => prev.map(item => {
      if (item.id !== itemId) return item;
      const isSelected = item.categories.includes(categoryId);
      if (isSelected) {
        return { ...item, categories: item.categories.filter(c => c !== categoryId) };
      }
      if (item.categories.length >= 3) return item;
      return { ...item, categories: [...item.categories, categoryId] };
    }));
  };

  // Toggle stack selection
  const toggleStack = (stackId: string) => {
    setSelectedStackIds(prev =>
      prev.includes(stackId)
        ? prev.filter(id => id !== stackId)
        : [...prev, stackId]
    );
  };

  // Handle cover file selection
  const handleCoverFileSelect = (itemId: string, file: File | null) => {
    if (!file) {
      updateItem(itemId, { coverArtFile: undefined, coverArtPreview: undefined });
      return;
    }

    // Validate file type
    if (!file.type.startsWith("image/")) {
      return;
    }

    // Create preview URL
    const previewUrl = URL.createObjectURL(file);
    updateItem(itemId, { coverArtFile: file, coverArtPreview: previewUrl, coverArtUrl: undefined });
  };

  // Handle import
  const handleImport = async () => {
    if (items.length === 0) return;

    await onImport(items.map(item => ({
      cdnUrl: item.url,
      contentType: item.contentType,
      title: item.title,
      author: item.author || "Unknown",
      selectedCategories: item.categories,
      selectedStackIds,
      coverArtUrl: item.coverArtUrl,
      coverArtFile: item.coverArtFile,
    })));
  };

  const hasValidItems = items.length > 0 && items.every(item => item.title.trim());

  return (
    <div className="space-y-4">
      {/* Header with back button */}
      <div className="flex items-center gap-3">
        <button
          onClick={onCancel}
          className="w-10 h-10 rounded-full bg-[#1a1a1a] border border-[#00ff00]/30 flex items-center justify-center text-[#00ff00] hover:bg-[#00ff00]/10 hover:border-[#00ff00] transition-all"
          aria-label="Go back"
        >
          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
          </svg>
        </button>
        <H4 className="text-[#00ff00] font-mono flex items-center gap-2"><LinkIcon size={18} /> Batch CDN Import</H4>
      </div>

      {/* URL Input */}
      <Card className="bg-[#0a0a0a] border border-[#00ff00]/30">
        <CardContent className="p-4">
          <Small className="text-gray-400 font-mono mb-2 block">
            Paste CDN URLs (one per line)
          </Small>
          <textarea
            value={urlInput}
            onChange={(e) => setUrlInput(e.target.value)}
            placeholder="https://storedon.net/net/8453/storage/raw/0x.../0x...&#10;https://storedon.net/net/8453/storage/raw/0x.../0x..."
            className="w-full h-24 px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm resize-none focus:outline-none focus:border-[#00ff00] transition-colors"
          />
          {parseError && (
            <Small className="text-red-400 font-mono mt-1 block">{parseError}</Small>
          )}
          <Button
            onClick={() => parseUrls(urlInput)}
            disabled={!urlInput.trim()}
            className="mt-2 bg-[#00ff00]/20 text-[#00ff00] hover:bg-[#00ff00]/30 font-mono text-xs"
          >
            + Add URLs to Queue
          </Button>
        </CardContent>
      </Card>

      {/* Items list */}
      {items.length > 0 && (
        <div className="space-y-2">
          <div className="flex items-center justify-between px-1">
            <Small className="text-[#00ff00] font-mono">{items.length} item(s) queued</Small>
            <button
              onClick={() => setItems([])}
              className="text-red-400 hover:text-red-300 font-mono text-xs"
            >
              Clear All
            </button>
          </div>

          <div className="space-y-2 max-h-[400px] overflow-y-auto">
            {items.map((item, idx) => (
              <Card key={item.id} className="bg-[#0a0a0a] border border-[#00ff00]/20">
                <CardContent className="p-3">
                  {/* Header */}
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <span className="text-lg">{getContentTypeIcon(item.contentType)}</span>
                      <Small className="text-gray-500 font-mono text-[10px]">#{idx + 1}</Small>
                    </div>
                    <button
                      onClick={() => removeItem(item.id)}
                      className="w-6 h-6 rounded-full bg-red-500/10 text-red-400/70 hover:bg-red-500/20 hover:text-red-400 flex items-center justify-center transition-all text-sm"
                    >
                      ×
                    </button>
                  </div>

                  {/* URL preview */}
                  <Small className="text-gray-500 font-mono text-[10px] truncate block mb-2">
                    {item.url}
                  </Small>

                  {/* Title & Author */}
                  <div className="grid grid-cols-2 gap-2">
                    <input
                      type="text"
                      value={item.title}
                      onChange={(e) => updateItem(item.id, { title: e.target.value })}
                      placeholder="Title *"
                      className="px-2 py-1.5 bg-black border border-[#00ff00]/20 rounded text-white font-mono text-xs focus:outline-none focus:border-[#00ff00]/50"
                    />
                    <input
                      type="text"
                      value={item.author}
                      onChange={(e) => updateItem(item.id, { author: e.target.value })}
                      placeholder="Author"
                      className="px-2 py-1.5 bg-black border border-[#00ff00]/20 rounded text-white font-mono text-xs focus:outline-none focus:border-[#00ff00]/50"
                    />
                  </div>

                  {/* Categories (compact) */}
                  <div className="mt-2">
                    <div className="flex flex-wrap gap-1">
                      {categories.filter(c => c.id !== "all").map(cat => (
                        <button
                          key={cat.id}
                          onClick={() => toggleItemCategory(item.id, cat.id)}
                          className={`px-1.5 py-0.5 rounded text-[10px] font-mono transition-colors ${
                            item.categories.includes(cat.id)
                              ? "bg-[#00ff00]/20 text-[#00ff00]"
                              : "bg-black text-gray-500 hover:text-gray-300"
                          }`}
                        >
                          {cat.emoji}
                        </button>
                      ))}
                    </div>
                  </div>

                  {/* Cover Art (for non-image content) */}
                  {item.contentType !== "image" && (
                    <div className="mt-2 pt-2 border-t border-[#00ff00]/10">
                      <Small className="text-gray-500 font-mono text-[10px] mb-1.5 block">Cover Art (optional)</Small>
                      <div className="flex gap-2 items-start">
                        {/* Cover preview */}
                        <div className="w-12 h-16 rounded bg-[#1a1a1a] overflow-hidden flex items-center justify-center border border-[#00ff00]/10 shrink-0">
                          {item.coverArtPreview || item.coverArtUrl ? (
                            <img
                              src={item.coverArtPreview || item.coverArtUrl}
                              alt="Cover"
                              className="w-full h-full object-cover"
                              onError={(e) => {
                                (e.target as HTMLImageElement).style.display = "none";
                              }}
                            />
                          ) : (
                            <ImageIcon size={20} className="text-gray-600" />
                          )}
                        </div>

                        {/* Input options */}
                        <div className="flex-1 space-y-1.5">
                          {/* URL input */}
                          <input
                            type="url"
                            value={item.coverArtUrl || ""}
                            onChange={(e) => {
                              const url = e.target.value.trim();
                              updateItem(item.id, {
                                coverArtUrl: url || undefined,
                                coverArtFile: undefined,
                                coverArtPreview: undefined
                              });
                            }}
                            placeholder="Image URL..."
                            className="w-full px-2 py-1 bg-black border border-[#00ff00]/20 rounded text-white font-mono text-[10px] focus:outline-none focus:border-[#00ff00]/50"
                          />

                          {/* File upload */}
                          <label className="flex items-center gap-1.5 px-2 py-1 bg-black border border-[#00ff00]/20 rounded cursor-pointer hover:border-[#00ff00]/40 transition-colors">
                            <span className="text-[10px]">📁</span>
                            <span className="text-[10px] font-mono text-gray-400">
                              {item.coverArtFile ? item.coverArtFile.name.slice(0, 15) + "..." : "Upload file"}
                            </span>
                            <input
                              type="file"
                              accept="image/*"
                              className="hidden"
                              onChange={(e) => handleCoverFileSelect(item.id, e.target.files?.[0] || null)}
                            />
                          </label>

                          {/* Clear button */}
                          {(item.coverArtUrl || item.coverArtFile) && (
                            <button
                              onClick={() => updateItem(item.id, {
                                coverArtUrl: undefined,
                                coverArtFile: undefined,
                                coverArtPreview: undefined
                              })}
                              className="text-[9px] font-mono text-red-400/70 hover:text-red-400"
                            >
                              ✕ Clear cover
                            </button>
                          )}
                        </div>
                      </div>
                    </div>
                  )}
                </CardContent>
              </Card>
            ))}
          </div>
        </div>
      )}

      {/* Stacks Selection (shared for all) */}
      {items.length > 0 && (
        <Card className="bg-[#0a0a0a] border border-purple-500/20">
          <CardContent className="p-3">
            <div className="flex items-center justify-between mb-2">
              <Small className="text-purple-400 font-mono">Add all to Stacks</Small>
              {selectedStackIds.length > 0 && (
                <Small className="text-purple-400 font-mono text-[10px]">
                  {selectedStackIds.length} selected
                </Small>
              )}
            </div>
            <button
              onClick={() => setShowStackDropdown(!showStackDropdown)}
              disabled={isLoadingStacks || stacks.length === 0}
              className="w-full px-3 py-2 bg-black border border-purple-500/30 rounded-lg text-left font-mono text-xs flex items-center justify-between hover:border-purple-500/50 transition-colors disabled:opacity-50"
            >
              {isLoadingStacks ? (
                <span className="text-gray-500">Loading...</span>
              ) : stacks.length === 0 ? (
                <span className="text-gray-500">No stacks yet</span>
              ) : selectedStackIds.length === 0 ? (
                <span className="text-gray-500">Optional...</span>
              ) : (
                <span className="text-white">{selectedStackIds.length} stack(s)</span>
              )}
              <span className="text-purple-400">▾</span>
            </button>

            {showStackDropdown && stacks.length > 0 && (
              <div className="mt-1 bg-[#0a0a0a] border border-purple-500/30 rounded-lg max-h-32 overflow-y-auto">
                {stacks.map(stack => (
                  <button
                    key={stack.id}
                    onClick={() => toggleStack(stack.id)}
                    className={`w-full px-3 py-2 text-left font-mono text-xs flex items-center gap-2 transition-colors ${
                      selectedStackIds.includes(stack.id)
                        ? "bg-purple-500/10 text-purple-400"
                        : "text-gray-300 hover:bg-[#1a1a1a]"
                    }`}
                  >
                    <span>📚</span>
                    <span className="truncate">{stack.name}</span>
                    {selectedStackIds.includes(stack.id) && <span className="ml-auto">✓</span>}
                  </button>
                ))}
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* Actions */}
      {items.length > 0 && (
        <div className="flex gap-2">
          <Button
            onClick={onCancel}
            variant="outline"
            className="flex-1 border-[#333] text-gray-400 hover:border-[#00ff00]/30 hover:text-[#00ff00]"
          >
            Cancel
          </Button>
          <Button
            onClick={handleImport}
            disabled={!hasValidItems || isImporting}
            className="flex-1 bg-[#00ff00] text-black hover:bg-[#00dd00] font-mono font-bold disabled:opacity-50"
          >
            {isImporting ? "Importing..." : `Import ${items.length} Item(s)`}
          </Button>
        </div>
      )}

      {/* Info */}
      <Card className="bg-blue-500/10 border border-blue-500/30">
        <CardContent className="p-3">
          <Small className="text-blue-300 font-mono text-[11px] flex items-start gap-2">
            <InfoIcon size={14} className="shrink-0 mt-0.5" />
            <span>Import multiple Net Protocol CDN links at once. Each link creates a library entry with the metadata you provide.</span>
          </Small>
        </CardContent>
      </Card>
    </div>
  );
}
src/features/app/components/book-card.tsx
"use client";

import { Card, CardContent, P, Small } from "@neynar/ui";
import type { Book, Category } from "@/features/app/types";
import { UpvoteButton } from "./upvote-button";
import { LibraryIcon, ShareIcon } from "@/components/icons/net-library-icons";
import { CoverImage } from "./cover-image";

// Content type colors for card borders
// Green = documents, White = media, Pink = social
const CONTENT_TYPE_COLORS = {
  document: { border: "border-[#00ff00]/60", hover: "hover:border-[#00ff00]", glow: "hover:shadow-[0_0_20px_rgba(0,255,0,0.3)]" },
  media: { border: "border-white/50", hover: "hover:border-white/80", glow: "hover:shadow-[0_0_20px_rgba(255,255,255,0.2)]" },
  social: { border: "border-pink-500/60", hover: "hover:border-pink-400", glow: "hover:shadow-[0_0_20px_rgba(236,72,153,0.3)]" },
};

// Get effective cover URL - prefer coverUrl, fallback to cdnUrl for image/video content
// For broken storedon.net chunked-storage URLs, construct a working URL via our book-file API
function getEffectiveCoverUrl(book: {
  coverUrl?: string;
  cdnUrl?: string;
  mediaType?: string;
  contentKey?: string;
  operator?: string;
  storageType?: string;
}): string | undefined {
  // If explicit cover art is set (e.g., KV-hosted cover), use it
  if (book.coverUrl) return book.coverUrl;

  // For image/video content, cdnUrl IS the visual content
  if (book.cdnUrl && book.mediaType && ["image", "video"].includes(book.mediaType)) {
    // Check if it's a broken storedon.net chunked-storage URL
    // These URLs return 404, so use our book-file API instead
    if (book.cdnUrl.includes("/chunked-storage/") && book.contentKey && book.operator) {
      return `/api/book-file?contentKey=${encodeURIComponent(book.contentKey)}&operator=${encodeURIComponent(book.operator)}&storageType=${book.storageType || 'chunked'}`;
    }
    return book.cdnUrl;
  }

  // No cover available
  return undefined;
}

// Detect content type from mediaType or filename
function getContentType(book: { mediaType?: string; title: string; isSocialReceipt?: boolean }): "document" | "media" | "social" {
  // Social receipts are always "social"
  if (book.isSocialReceipt) return "social";

  // Check explicit mediaType first
  if (book.mediaType) {
    if (["audio", "video", "image"].includes(book.mediaType)) return "media";
    if (["pdf", "text"].includes(book.mediaType)) return "document";
  }

  // Fallback: detect from filename extension
  const lowerTitle = (book.title || '').toLowerCase();

  // Media extensions
  if (/\.(mp3|wav|ogg|flac|m4a|aac|mp4|webm|mov|avi|mkv|png|jpg|jpeg|gif|webp|svg)$/.test(lowerTitle)) {
    return "media";
  }

  // Document extensions (default)
  return "document";
}

interface BookCardProps {
  book: Book;
  categories: Category[];
  upvoteCount?: number;
  onSelect: () => void;
  onShare: () => void;
  onUpvoteSuccess?: () => void;
  onUploaderClick?: (uploader: { address: string; username: string; pfpUrl: string; fid?: number }) => void;
  onAddToStack?: () => void; // Callback to open Add to Stack modal
  isDesktop?: boolean; // Enable enhanced desktop hover effects
}

export function BookCard({
  book,
  categories,
  upvoteCount = 0,
  onSelect,
  onShare,
  onUpvoteSuccess,
  onUploaderClick,
  onAddToStack,
  isDesktop = false,
}: BookCardProps) {
  // Get all category info for display
  const bookCategories = (Array.isArray(book.categories) ? book.categories : [])
    .map((catId) => categories.find((c) => c.id === catId))
    .filter(Boolean);

  // Desktop: smaller, denser buttons (36px instead of 40px)
  const buttonSize = isDesktop ? "w-9 h-9" : "w-10 h-10";
  const buttonTextSize = isDesktop ? "text-xs" : "text-sm";
  const buttonLabelSize = isDesktop ? "text-[7px]" : "text-[8px]";

  // Social receipts get a different layout optimized for screenshots
  const isSocialReceipt = book.isSocialReceipt && book.socialPlatform;

  // Determine aspect ratio based on platform
  // Twitter/X, YouTube, LinkedIn: landscape (16:10)
  // Instagram, TikTok, Reddit: square-ish (4:3)
  // Farcaster, Bluesky, Threads: landscape (3:2)
  const getAspectRatio = (platform?: string) => {
    switch (platform) {
      case "instagram":
      case "tiktok":
      case "reddit":
        return "aspect-[4/3]"; // More square for visual-first platforms
      case "farcaster":
      case "bluesky":
      case "threads":
        return "aspect-[3/2]"; // Standard social
      default: // twitter, youtube, linkedin
        return "aspect-[16/10]"; // Wide landscape
    }
  };
  const aspectClass = getAspectRatio(book.socialPlatform);

  // Get content type for color coding
  const contentType = getContentType(book);
  const typeColors = CONTENT_TYPE_COLORS[contentType];

  // Social receipt card - cleaner layout with attribution header
  if (isSocialReceipt) {
    // Platform display name (full word, not abbreviation)
    const platformName = book.socialPlatform === "twitter" ? "Twitter/X" :
      book.socialPlatform ? book.socialPlatform.charAt(0).toUpperCase() + book.socialPlatform.slice(1) : "Social";

    return (
      <Card
        className={`cursor-pointer bg-[#0a0a0a] border ${typeColors.border} ${typeColors.hover} ${typeColors.glow} transition-all`}
        onClick={onSelect}
      >
        <CardContent className="p-0">
          {/* Header: (pfp) @username archived this Platform post by @handle */}
          <div className="flex items-start justify-between px-3 pt-3 pb-2 gap-2">
            {/* Attribution line */}
            <button
              onClick={(e) => {
                e.stopPropagation();
                if (onUploaderClick && book.uploader?.address) {
                  onUploaderClick({
                    address: book.uploader.address,
                    username: book.uploader?.username || "Unknown",
                    pfpUrl: book.uploader?.pfpUrl || "",
                    fid: book.uploader?.fid,
                  });
                }
              }}
              className="flex items-center gap-2 hover:opacity-80 transition-opacity flex-1 min-w-0"
            >
              <img
                src={book.uploader?.pfpUrl || ""}
                alt={book.uploader?.username || "Unknown"}
                className={`w-8 h-8 rounded-full border shrink-0 ${
                  book.isAgentUploaded ? "border-[#B794F4]/50" : "border-pink-500/50"
                }`}
              />
              <div className="text-left min-w-0">
                <div className="flex flex-wrap items-baseline gap-x-1">
                  <span
                    className="font-mono text-xs font-medium"
                    style={{ color: book.isAgentUploaded ? "#B794F4" : "#f472b6" }}
                  >
                    @{book.uploader?.username || "Unknown"}
                    {book.isAgentUploaded && (
                      <span style={{ fontSize: "0.7em", marginLeft: "4px", opacity: 0.8 }}>
                        AGENT
                      </span>
                    )}
                  </span>
                  <span className="text-gray-500 font-mono text-[10px]">archived this</span>
                  <span className="text-gray-400 font-mono text-[10px]">{platformName}</span>
                  <span className="text-gray-500 font-mono text-[10px]">post by</span>
                  <span className="text-gray-300 font-mono text-xs truncate">@{book.author}</span>
                </div>
              </div>
            </button>

            {/* Upvote count - top right */}
            {book.uploader?.address && book.contentKey && (
              <div className="shrink-0">
                <UpvoteButton
                  contentKey={book.contentKey}
                  operatorAddress={book.uploader.address}
                  upvoteCount={upvoteCount}
                  title={book.title}
                  onSuccess={onUpvoteSuccess}
                  compact
                />
              </div>
            )}
          </div>

          {/* Screenshot preview */}
          <div className="px-3">
            <div className={`relative w-full ${aspectClass} bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-lg overflow-hidden border border-pink-500/30`}>
              <CoverImage
                src={getEffectiveCoverUrl(book)}
                alt={book.title}
                className="w-full h-full object-cover"
              />
            </div>
          </div>

          {/* Footer: Action buttons - horizontal with labels */}
          <div className="flex items-center gap-2 px-3 py-2.5">
            {onAddToStack && (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  onAddToStack();
                }}
                className="flex-1 h-9 rounded-lg flex items-center justify-center gap-1.5 bg-[#1a1a1a] border border-pink-500/30 text-gray-400 hover:bg-pink-500/20 hover:text-pink-300 hover:border-pink-500/50 transition-all text-xs font-mono"
                title="Add to stack"
              >
                <LibraryIcon size={14} />
                <span>Add to Stack</span>
              </button>
            )}
            <button
              onClick={(e) => {
                e.stopPropagation();
                onShare();
              }}
              className="flex-1 h-9 rounded-lg flex items-center justify-center gap-1.5 bg-[#1a1a1a] border border-pink-500/30 text-gray-400 hover:bg-pink-500/20 hover:text-pink-300 hover:border-pink-500/50 transition-all text-xs font-mono"
              title="Share archive"
            >
              <ShareIcon size={12} />
              <span>Share Archive</span>
            </button>
          </div>
        </CardContent>
      </Card>
    );
  }

  // Regular book/content card - original layout with color-coded border
  const regularCardClassName = isDesktop
    ? `cursor-pointer bg-[#0a0a0a] border ${typeColors.border} ${typeColors.hover} hover:border-2 ${typeColors.glow} hover:scale-[1.02] hover:bg-[#0f0f0f] transition-all duration-200`
    : `cursor-pointer bg-[#0a0a0a] border ${typeColors.border} ${typeColors.hover} hover:border-2 ${typeColors.glow} transition-all`;

  return (
    <Card
      className={regularCardClassName}
      onClick={onSelect}
    >
      <CardContent className="p-4">
        <div className="flex gap-3">
          {/* Book cover - use coverUrl if available, cdnUrl for media, app logo fallback */}
          <div className="w-20 h-28 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-lg flex items-center justify-center border border-[#00ff00]/20 shrink-0 overflow-hidden">
            <CoverImage
              src={getEffectiveCoverUrl(book)}
              alt={book.title}
              className="w-full h-full object-cover"
            />
          </div>
          <div className="flex-1 min-w-0">
            <P className="font-medium truncate text-white">{book.title}</P>
            <Small className="text-gray-400">{book.author}</Small>
            <Small className="text-gray-500 block">
              {book.size}
            </Small>
            {/* Uploader info */}
            <div className="mt-2">
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  if (onUploaderClick && book.uploader?.address) {
                    onUploaderClick({
                      address: book.uploader.address,
                      username: book.uploader?.username || "Unknown",
                      pfpUrl: book.uploader?.pfpUrl || "",
                      fid: book.uploader?.fid,
                    });
                  }
                }}
                className="flex items-center gap-1.5 hover:opacity-80 transition-opacity"
              >
                <img
                  src={book.uploader?.pfpUrl || ""}
                  alt={book.uploader?.username || "Unknown"}
                  className={`w-4 h-4 rounded-full border transition-all ${
                    book.isAgentUploaded
                      ? "border-[#B794F4]/30 hover:border-[#B794F4] hover:shadow-[0_0_6px_rgba(183,148,244,0.3)]"
                      : "border-[#00ff00]/30 hover:border-[#00ff00] hover:shadow-[0_0_6px_rgba(0,255,0,0.3)]"
                  }`}
                />
                <span
                  className="text-xs font-mono transition-colors"
                  style={{
                    color: book.isAgentUploaded ? "#B794F4" : "#6b7280",
                  }}
                >
                  @{book.uploader?.username || "Unknown"}
                  {book.isAgentUploaded && (
                    <span style={{ fontSize: "0.7em", marginLeft: "4px", opacity: 0.8 }}>
                      AGENT
                    </span>
                  )}
                </span>
              </button>
            </div>
            {/* Partner source attribution */}
            {book.source && (
              <p className="text-[10px] font-mono text-gray-600 mt-1">
                Stored via {book.source}
              </p>
            )}
            {/* Category tags */}
            <div className="flex flex-wrap gap-1 mt-2">
              {bookCategories.map((cat) => (
                <span
                  key={cat?.id}
                  className="px-1.5 py-0.5 rounded text-[10px] bg-[#00ff00]/10 text-[#00ff00]/70 font-mono"
                >
                  {cat?.emoji} {cat?.label}
                </span>
              ))}
            </div>
          </div>
          {/* Actions column */}
          <div className="flex flex-col items-center gap-1 shrink-0">
            {/* Upvote button */}
            {book.uploader?.address && book.contentKey && (
              <UpvoteButton
                contentKey={book.contentKey}
                operatorAddress={book.uploader.address}
                upvoteCount={upvoteCount}
                title={book.title}
                onSuccess={onUpvoteSuccess}
              />
            )}
            {/* Add to Stack button */}
            {onAddToStack && (
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  onAddToStack();
                }}
                className={`${buttonSize} rounded-lg flex flex-col items-center justify-center bg-[#1a1a1a] text-gray-400 hover:bg-[#00ff00] hover:text-black transition-all`}
                title="Add to stack"
              >
                <span className={buttonTextSize}><LibraryIcon size={isDesktop ? 16 : 14} /></span>
                <span className={`${buttonLabelSize} font-mono leading-none`}>stack</span>
              </button>
            )}
            {/* Share button */}
            <button
              onClick={(e) => {
                e.stopPropagation();
                onShare();
              }}
              className={`${buttonSize} rounded-lg flex flex-col items-center justify-center bg-[#1a1a1a] text-gray-400 hover:bg-[#00ff00] hover:text-black transition-all`}
              title="Share book"
            >
              <ShareIcon size={isDesktop ? 16 : 14} />
              <span className={`${buttonLabelSize} font-mono leading-none`}>share</span>
            </button>
          </div>
        </div>
      </CardContent>
    </Card>
  );
}
src/features/app/components/book-detail.tsx
"use client";
// v3 rebuild
import { useState, useEffect, useCallback } from "react";
import { Card, CardContent, Button, P, Small, H3, H4 } from "@neynar/ui";
import type { Book, Category } from "@/features/app/types";
import { useUpvote } from "@/hooks/use-upvotes";
import { CommentsSection } from "./comments-section";
import { CollectionsButton } from "./collections-button";
import { UpvoteModal } from "./upvote-modal";
import { UserLibraryCardModal } from "./user-library-card-modal";
import type { MemberEntry } from "@/lib/net-protocol";
import { BASE_CHAIN_ID, decodeBytes32Key } from "@/lib/net-protocol";
import { CoverImage } from "./cover-image";
import { CloseIcon, LinkIcon, EyeOffIcon, ClipboardIcon, GlobeIcon, ShareIcon } from "@/components/icons/net-library-icons";
import { safeComposeCast, safeOpenUrl, useAppMode } from "@/lib/app-mode";

// Get effective cover URL - prefer coverUrl, fallback to cdnUrl for image/video content
// For broken storedon.net chunked-storage URLs, construct a working URL via our book-file API
function getEffectiveCoverUrl(book: {
  coverUrl?: string;
  cdnUrl?: string;
  mediaType?: string;
  contentKey?: string;
  operator?: string;
  storageType?: string;
}): string | undefined {
  // If explicit cover art is set (e.g., KV-hosted cover), use it
  if (book.coverUrl) return book.coverUrl;

  // For image/video content, cdnUrl IS the visual content
  if (book.cdnUrl && book.mediaType && ["image", "video"].includes(book.mediaType)) {
    // Check if it's a broken storedon.net chunked-storage URL
    // These URLs return 404, so use our book-file API instead
    if (book.cdnUrl.includes("/chunked-storage/") && book.contentKey && book.operator) {
      return `/api/book-file?contentKey=${encodeURIComponent(book.contentKey)}&operator=${encodeURIComponent(book.operator)}&storageType=${book.storageType || 'chunked'}`;
    }
    return book.cdnUrl;
  }

  // No cover available
  return undefined;
}

// Types for upvoter data
interface UpvoterInfo {
  address: string;
  amount: number;
  username?: string;
  pfpUrl?: string;
}

// Cover Art Modal
function CoverArtModal({
  isOpen,
  onClose,
  coverUrl,
  title,
}: {
  isOpen: boolean;
  onClose: () => void;
  coverUrl?: string;
  title: string;
}) {
  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 bg-black/95 z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <button
        onClick={onClose}
        className="absolute top-4 right-4 w-10 h-10 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors z-10"
      >
        <CloseIcon size={18} />
      </button>
      <div
        className="max-w-[90vw] max-h-[80vh] rounded-xl overflow-hidden border-2 border-[#00ff00]/30 shadow-[0_0_30px_rgba(0,255,0,0.2)]"
        onClick={(e) => e.stopPropagation()}
      >
        <CoverImage
          src={coverUrl}
          alt={title}
          className="max-w-full max-h-[80vh] object-contain"
          fallbackClassName="w-64 h-80 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] flex items-center justify-center"
          fallbackLogoSize="w-32 h-32"
        />
      </div>
    </div>
  );
}

// Upvoters List Modal
function UpvotersListModal({
  isOpen,
  onClose,
  upvoters,
  totalUpvotes,
  bookTitle: _bookTitle,
}: {
  isOpen: boolean;
  onClose: () => void;
  upvoters: UpvoterInfo[];
  totalUpvotes: number;
  bookTitle: string;
}) {
  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/95 z-50 flex flex-col">
      {/* Header */}
      <div className="shrink-0 px-4 py-3 border-b border-[#00ff00]/30 flex items-center justify-between bg-black">
        <div>
          <H4 className="text-[#00ff00] font-mono">Upvoters</H4>
          <Small className="text-gray-500 font-mono">{totalUpvotes} total upvotes</Small>
        </div>
        <button
          onClick={onClose}
          className="w-10 h-10 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors"
        >
          ✕
        </button>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-4">
        {upvoters.length === 0 ? (
          <div className="text-center py-12">
            <div className="text-4xl mb-3">▲</div>
            <P className="text-gray-400 font-mono">No upvotes yet</P>
            <Small className="text-gray-500 font-mono">Be the first to upvote this item!</Small>
          </div>
        ) : (
          <div className="space-y-2">
            {upvoters.map((upvoter, index) => (
              <Card
                key={upvoter.address}
                className="bg-[#0a0a0a] border border-[#00ff00]/20"
              >
                <CardContent className="p-3">
                  <div className="flex items-center gap-3">
                    {/* Rank */}
                    <div
                      className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-bold font-mono shrink-0 ${
                        index === 0
                          ? "bg-yellow-500/20 text-yellow-400 border border-yellow-500/30"
                          : index === 1
                          ? "bg-gray-400/20 text-gray-300 border border-gray-400/30"
                          : index === 2
                          ? "bg-orange-500/20 text-orange-400 border border-orange-500/30"
                          : "bg-[#00ff00]/10 text-[#00ff00] border border-[#00ff00]/20"
                      }`}
                    >
                      {index + 1}
                    </div>

                    {/* Avatar */}
                    <img
                      src={upvoter.pfpUrl || `https://api.dicebear.com/7.x/identicon/svg?seed=${upvoter.address}`}
                      alt={upvoter.username || "User"}
                      className="w-10 h-10 rounded-full border border-[#00ff00]/30 object-cover"
                    />

                    {/* Info */}
                    <div className="flex-1 min-w-0">
                      <P className="text-sm font-mono text-white truncate">
                        {upvoter.username || `${(upvoter.address || '').slice(0, 6)}...${(upvoter.address || '').slice(-4)}`}
                      </P>
                    </div>

                    {/* Upvote Count */}
                    <div className="text-right shrink-0">
                      <P className="text-[#00ff00] font-mono text-lg font-bold">▲ {upvoter.amount}</P>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

interface BookDetailProps {
  book: Book;
  categories: Category[];
  upvoteCount?: number;
  currentUserAddress?: string; // For checking if user is the uploader
  userLinkedAddresses?: string[]; // All addresses linked to user's membership (for cross-platform ownership)
  onBack: () => void;
  onRead: () => void;
  onViewOnNetProtocol: () => void;
  /** @deprecated The internal share dropdown now handles sharing directly.
   * This prop is kept for API compatibility but is no longer called. */
  onShare?: () => void;
  onUpvoteSuccess?: () => void;
  onHideFromLibrary?: (contentKey: string, hidden: boolean) => Promise<void>;
  onEditDetails?: () => void; // Callback to open edit modal (for item owners)
}

export function BookDetail({
  book,
  categories,
  upvoteCount = 0,
  currentUserAddress,
  userLinkedAddresses,
  onBack,
  onRead,
  onViewOnNetProtocol,
  // onShare intentionally omitted — internal share dropdown handles sharing directly
  onUpvoteSuccess,
  onHideFromLibrary,
  onEditDetails,
}: BookDetailProps) {
  // Upvote state
  const { upvote, isUpvoting, isConfirmed } = useUpvote();
  const [localUpvotes, setLocalUpvotes] = useState(0);
  const [showUpvoteModal, setShowUpvoteModal] = useState(false);

  // New modal states
  const [showCoverModal, setShowCoverModal] = useState(false);
  const [showUpvotersModal, setShowUpvotersModal] = useState(false);

  // Upvoters data
  const [upvoters, setUpvoters] = useState<UpvoterInfo[]>([]);
  const [_upvotersLoading, setUpvotersLoading] = useState(false);

  // Hide from library state
  const [isHiding, setIsHiding] = useState(false);
  const [showHideConfirm, setShowHideConfirm] = useState(false);

  // CDN Link modal state
  const [showCdnLinkModal, setShowCdnLinkModal] = useState(false);
  const [cdnLinkCopied, setCdnLinkCopied] = useState(false);

  // Share menu state
  const [showShareMenu, setShowShareMenu] = useState(false);
  const appMode = useAppMode();
  const isBaseApp = appMode === "base-app";
  // Get best CDN URL — priority: stored cdnUrl > /storage/load/ (decoded key) > /storage/raw/
  const operatorForCdnLink = book.operator || book.uploader?.address;
  const cdnUrl = (() => {
    if (book.cdnUrl && !book.cdnUrl.includes("/chunked-storage/")) return book.cdnUrl;
    if (!book.contentKey || !operatorForCdnLink) return null;
    // Try decoding bytes32 key — items stored via API with short keys need /storage/load/
    const decoded = decodeBytes32Key(book.contentKey);
    if (decoded) {
      return `https://storedon.net/net/${BASE_CHAIN_ID}/storage/load/${operatorForCdnLink}/${encodeURIComponent(decoded)}`;
    }
    return `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${operatorForCdnLink}/${book.contentKey}`;
  })();

  // Check if current user is the uploader (supports cross-platform identity)
  // A user "owns" content if:
  // 1. Their current address matches the uploader address, OR
  // 2. Any of their linked addresses (from membership) matches the uploader address
  const uploaderAddressLower = book.uploader?.address?.toLowerCase();
  const isUploader = uploaderAddressLower && (
    // Direct match with current wallet
    (currentUserAddress && currentUserAddress.toLowerCase() === uploaderAddressLower) ||
    // Match via linked addresses (cross-platform ownership)
    (userLinkedAddresses && userLinkedAddresses.some(addr => addr.toLowerCase() === uploaderAddressLower))
  );

  // Uploader library card modal state
  const [uploaderMember, setUploaderMember] = useState<(MemberEntry & { pfpUrl?: string; netLink?: { url: string; label: string } | null }) | null>(null);
  const [uploaderAllMemberships, setUploaderAllMemberships] = useState<Array<{
    memberId: number;
    ensSubname: string;
    signupPlatform: "farcaster" | "base-app" | "unknown";
    joinedAt: number;
    fid?: number;
    username?: string;
    address: string;
    matchType: "primary" | "fid" | "linked";
  }> | null>(null);
  const [showUploaderModal, setShowUploaderModal] = useState(false);

  // Fetch upvoters for this specific content item
  const fetchUpvoters = useCallback(async () => {
    if (!book.contentKey) return;

    setUpvotersLoading(true);
    try {
      // Fetch all upvote events
      const response = await fetch("/api/upvote-events");
      if (!response.ok) throw new Error("Failed to fetch upvote events");

      const data = await response.json();
      const allUpvoters = data.topUpvoters || [];

      // Find upvoters for this specific content
      // Normalize content key: lowercase, ensure 0x prefix for consistent comparison
      const normalizeKey = (key: string): string => {
        const cleaned = (key || '').toLowerCase().trim();
        return cleaned.startsWith('0x') ? cleaned : `0x${cleaned}`;
      };

      const contentKeyNormalized = normalizeKey(book.contentKey || '');

      // Aggregate upvotes by upvoter for this content
      const upvoterMap = new Map<string, number>();

      for (const upvoter of allUpvoters) {
        if (!upvoter.address) continue;
        for (const item of upvoter.itemsUpvoted || []) {
          if (!item.storageKey) continue;
          const itemKeyNormalized = normalizeKey(item.storageKey);

          // Exact match first (most reliable)
          if (itemKeyNormalized === contentKeyNormalized) {
            const current = upvoterMap.get(upvoter.address) || 0;
            upvoterMap.set(upvoter.address, current + item.amount);
          }
          // Fallback: check if one contains the other (for partial key matches in storage)
          else if (contentKeyNormalized.length > 10 && itemKeyNormalized.length > 10) {
            // Only use substring matching if both keys are substantial length
            const contentCore = contentKeyNormalized.slice(2); // Remove 0x
            const itemCore = itemKeyNormalized.slice(2); // Remove 0x
            if (contentCore.includes(itemCore) || itemCore.includes(contentCore)) {
              const current = upvoterMap.get(upvoter.address) || 0;
              upvoterMap.set(upvoter.address, current + item.amount);
            }
          }
        }
      }

      // Convert to array and sort by amount
      const upvoterAddresses = Array.from(upvoterMap.entries())
        .map(([address, amount]) => ({ address, amount }))
        .sort((a, b) => b.amount - a.amount);

      if (upvoterAddresses.length === 0) {
        setUpvoters([]);
        return;
      }

      // Resolve usernames for upvoters
      const addresses = upvoterAddresses.map(u => u.address);
      const resolveResponse = await fetch("/api/resolve-user", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ addresses }),
      });

      let usernames: Record<string, { username: string; pfpUrl: string }> = {};
      if (resolveResponse.ok) {
        const resolveData = await resolveResponse.json();
        usernames = resolveData.users || {};
      }

      // Merge data
      const resolvedUpvoters: UpvoterInfo[] = upvoterAddresses.map(u => ({
        address: u.address,
        amount: u.amount,
        username: u.address ? usernames[u.address.toLowerCase()]?.username : undefined,
        pfpUrl: u.address ? usernames[u.address.toLowerCase()]?.pfpUrl : undefined,
      }));

      setUpvoters(resolvedUpvoters);
    } catch (err) {
      console.error("Failed to fetch upvoters:", err);
      setUpvoters([]);
    } finally {
      setUpvotersLoading(false);
    }
  }, [book.contentKey]);

  // Fetch upvoters on mount and when upvote count changes
  useEffect(() => {
    fetchUpvoters();
  }, [fetchUpvoters, upvoteCount]);

  const handleUpvote = async (count: number) => {
    if (!book.contentKey || !book.uploader?.address) return;

    const success = await upvote(book.contentKey, book.uploader.address, count);
    if (success) {
      // Optimistically update local count (blockchain will confirm later)
      setLocalUpvotes((prev) => prev + count);
      setShowUpvoteModal(false);
    }
  };

  // When transaction is confirmed, refresh the counts from the blockchain
  useEffect(() => {
    if (isConfirmed) {
      // Give the blockchain a moment to update, then refresh
      const timer = setTimeout(() => {
        onUpvoteSuccess?.();
        fetchUpvoters(); // Refresh upvoters too
      }, 2000);
      return () => clearTimeout(timer);
    }
  }, [isConfirmed, onUpvoteSuccess, fetchUpvoters]);

  const displayUpvotes = upvoteCount + localUpvotes;

  // Handle hide/unhide from library
  const handleHideFromLibrary = async () => {
    if (!book.contentKey || !onHideFromLibrary) return;

    setIsHiding(true);
    try {
      await onHideFromLibrary(book.contentKey, true);
      setShowHideConfirm(false);
      // Go back after hiding since the item is no longer visible
      onBack();
    } catch (err) {
      console.error("Failed to hide item:", err);
    } finally {
      setIsHiding(false);
    }
  };

  // Handle clicking on uploader to show their library card
  // Use the membership API which checks by address, FID, AND linked addresses
  const handleUploaderClick = useCallback(async () => {
    if (!book.uploader?.address) return;

    try {
      // Fetch net link for uploader
      let netLink = null;
      try {
        const linkRes = await fetch(`/api/user-net-link?address=${book.uploader?.address}`);
        if (linkRes.ok) {
          const linkData = await linkRes.json();
          netLink = linkData.link || null;
        }
      } catch {
        // Ignore errors
      }

      // Use the membership API which checks address, FID, and linked addresses
      const fidParam = book.uploader?.fid ? `&fid=${book.uploader.fid}` : "";
      const response = await fetch(`/api/membership?address=${book.uploader?.address}${fidParam}`);

      if (response.ok) {
        const data = await response.json();

        if (data.isMember && data.member) {
          // Found membership via address, FID, or linked address
          setUploaderMember({
            ...data.member,
            pfpUrl: book.uploader?.pfpUrl,
            netLink,
          });
          setUploaderAllMemberships(data.allMemberships || null);
        } else {
          // Uploader is not a member - create placeholder
          setUploaderMember({
            memberId: 0,
            address: book.uploader.address,
            ensSubname: "non-member",
            fid: book.uploader?.fid,
            username: book.uploader?.username,
            joinedAt: Date.now(),
            pfpUrl: book.uploader?.pfpUrl,
            netLink,
          });
          setUploaderAllMemberships(null);
        }
      }
      setShowUploaderModal(true);
    } catch (err) {
      console.error("Failed to fetch uploader info:", err);
    }
  }, [book.uploader]);

  // Get all category info for display
  const bookCategories = (Array.isArray(book.categories) ? book.categories : [])
    .map((catId) => categories.find((c) => c.id === catId))
    .filter(Boolean);

  return (
    <div className="h-dvh flex flex-col overflow-hidden bg-black">
      {/* Header */}
      <header className="shrink-0 px-4 py-3 border-b border-[#00ff00]/30 flex items-center gap-3">
        <button
          onClick={onBack}
          className="w-10 h-10 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222]"
        >
          ←
        </button>
        <H3 className="text-[#00ff00] font-mono tracking-tight truncate flex-1">Details</H3>
        {book.contentKey && (
          <CollectionsButton contentKey={book.contentKey} title={book.title} />
        )}
      </header>

      {/* Content */}
      <main className="flex-1 overflow-y-auto p-4">
        <div className="space-y-4">
          {/* Book cover and info */}
          <Card className="bg-[#0a0a0a] border border-[#00ff00]/60">
            <CardContent className="p-6">
              <div className="flex gap-4">
                <div className="flex flex-col items-center shrink-0">
                  {/* Tappable cover art - use different layout for social receipts */}
                  {book.isSocialReceipt ? (
                    <button
                      onClick={() => setShowCoverModal(true)}
                      className="w-32 aspect-[3/2] bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-lg flex items-center justify-center border border-[#00ff00]/60 overflow-hidden hover:border-[#00ff00] hover:shadow-[0_0_15px_rgba(0,255,0,0.2)] transition-all cursor-pointer"
                    >
                      <CoverImage
                        src={getEffectiveCoverUrl(book)}
                        alt={book.title}
                        className="w-full h-full object-cover"
                      />
                    </button>
                  ) : (
                    <button
                      onClick={() => setShowCoverModal(true)}
                      className="w-24 h-32 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-lg flex items-center justify-center border border-[#00ff00]/60 overflow-hidden hover:border-[#00ff00] hover:shadow-[0_0_15px_rgba(0,255,0,0.2)] transition-all cursor-pointer"
                    >
                      <CoverImage
                        src={getEffectiveCoverUrl(book)}
                        alt={book.title}
                        className="w-full h-full object-cover"
                      />
                    </button>
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <P className="text-xl font-bold text-white font-mono">{book.title}</P>
                  <Small className="text-gray-400 font-mono">{book.author}</Small>
                  <div className="flex flex-wrap items-center gap-1.5 mt-2">
                    {bookCategories.map((cat) => (
                      <span
                        key={cat?.id}
                        className="px-1.5 py-0.5 rounded text-[10px] bg-[#00ff00]/10 text-[#00ff00]/70 font-mono"
                      >
                        {cat?.emoji} {cat?.label}
                      </span>
                    ))}
                  </div>
                  <Small className="text-gray-500 block mt-2 font-mono">
                    {book.size} • Uploaded {book.uploadDate}
                  </Small>
                  {/* Partner source attribution */}
                  {book.source && (
                    <Small className="text-gray-600 font-mono block mt-1">
                      Stored via {book.source}
                    </Small>
                  )}
                  {/* Uploader info - tappable to view library card */}
                  <button
                    onClick={handleUploaderClick}
                    className="flex items-center gap-1.5 mt-2 hover:opacity-80 transition-opacity"
                  >
                    <img
                      src={book.uploader?.pfpUrl || ""}
                      alt={book.uploader?.username || "Unknown"}
                      className={`w-4 h-4 rounded-full border transition-colors ${
                        book.isAgentUploaded
                          ? "border-[#B794F4]/30 hover:border-[#B794F4]"
                          : "border-[#00ff00]/30 hover:border-[#00ff00]"
                      }`}
                    />
                    <Small
                      className="font-mono transition-colors"
                      style={{
                        color: book.isAgentUploaded ? "#B794F4" : "#6b7280",
                      }}
                    >
                      Uploaded by @{book.uploader?.username || "Unknown"}
                      {book.isAgentUploaded && (
                        <span className="ml-1 text-[9px] opacity-70">[agent]</span>
                      )}
                    </Small>
                  </button>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Upvote Display */}
          <Card className="bg-[#0a0a0a] border border-[#00ff00]/60">
            <CardContent className="py-3 px-4">
              <div className="flex items-center gap-3">
                {/* Tappable upvote count + PFPs area */}
                <button
                  onClick={() => setShowUpvotersModal(true)}
                  className="flex-1 flex items-center justify-center gap-3 py-1 rounded-lg hover:bg-[#00ff00]/5 transition-colors"
                >
                  {displayUpvotes > 0 ? (
                    <>
                      <div className="text-2xl font-bold text-[#00ff00] font-mono">▲ {displayUpvotes}</div>
                      {upvoters.length > 0 && (
                        <div className="flex items-center -space-x-2">
                          {upvoters.slice(0, 3).map((upvoter, index) => (
                            <img
                              key={upvoter.address}
                              src={upvoter.pfpUrl || `https://api.dicebear.com/7.x/identicon/svg?seed=${upvoter.address}`}
                              alt={upvoter.username || "Upvoter"}
                              className="w-6 h-6 rounded-full border-2 border-[#0a0a0a] object-cover"
                              style={{ zIndex: 3 - index }}
                            />
                          ))}
                          {upvoters.length > 3 && (
                            <div
                              className="w-6 h-6 rounded-full bg-[#1a1a1a] border-2 border-[#0a0a0a] flex items-center justify-center"
                              style={{ zIndex: 0 }}
                            >
                              <span className="text-[9px] text-gray-400 font-mono">...</span>
                            </div>
                          )}
                        </div>
                      )}
                    </>
                  ) : (
                    <p className="text-sm text-gray-400 font-mono">Be the first to upvote this item</p>
                  )}
                </button>
                <button
                  onClick={() => setShowUpvoteModal(true)}
                  disabled={isUpvoting || !book.contentKey}
                  className={`px-4 py-2 rounded-lg font-mono text-sm font-bold transition-all shrink-0 ${
                    isUpvoting
                      ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/30 cursor-wait"
                      : isConfirmed
                      ? "bg-[#00ff00]/30 text-[#00ff00] border border-[#00ff00]/50"
                      : "bg-[#00ff00] text-black hover:bg-[#00dd00]"
                  }`}
                >
                  {isUpvoting ? "..." : isConfirmed ? "✓" : "▲ UPVOTE"}
                </button>
              </div>
            </CardContent>
          </Card>

          {/* Actions */}
          <div className="space-y-2">
            <Button
              onClick={onRead}
              className="w-full bg-[#00ff00] text-black hover:bg-[#00dd00] font-mono h-12"
            >
              {book.mediaType === "audio" || (book.title || '').toLowerCase().match(/\.(mp3|wav|ogg|flac|m4a)$/)
                ? "🎵 Play Audio"
                : book.mediaType === "video" || (book.title || '').toLowerCase().match(/\.(mp4|webm|mov|avi|mkv)$/)
                  ? "🎬 Play Video"
                  : book.mediaType === "image" || (book.title || '').toLowerCase().match(/\.(png|jpg|jpeg|gif|webp|svg)$/)
                    ? "🖼️ View Image"
                    : "Open Item"}
            </Button>
            <Button
              onClick={onViewOnNetProtocol}
              variant="outline"
              className="w-full border-[#00ff00] text-[#00ff00] hover:bg-[#00ff00]/10 font-mono h-12 flex items-center justify-center gap-2"
            >
              <GlobeIcon size={18} /> View on Net Protocol
            </Button>
            <div className="relative">
              <Button
                onClick={() => setShowShareMenu(!showShareMenu)}
                variant="outline"
                className="w-full border-[#00ff00] text-[#00ff00] hover:bg-[#00ff00]/10 font-mono h-12 flex items-center justify-center gap-2"
              >
                <ShareIcon size={18} /> Share This Item
              </Button>

              {showShareMenu && (
                <>
                  <div className="fixed inset-0 z-40" onClick={() => setShowShareMenu(false)} />
                  <div className="absolute left-0 right-0 top-full mt-2 bg-black border border-[#00ff00]/30 rounded-lg overflow-hidden z-50 shadow-lg">
                    <button
                      onClick={async () => {
                        setShowShareMenu(false);
                        const source = isBaseApp ? "base" : "farcaster";
                        const bookUrl = `${window.location.origin}/share/book/${encodeURIComponent(book.contentKey || '')}?source=${source}`;
                        const castText = `Check out "${book.title}" by ${book.author} on Net Library!\n\nDecentralized onchain media powered by @netprotocol`;
                        await safeComposeCast({
                          text: castText,
                          embeds: [bookUrl],
                        });
                      }}
                      className={`w-full px-4 py-3 text-left text-sm font-mono flex items-center gap-2 transition-colors ${
                        isBaseApp
                          ? "hover:bg-[#0052FF]/20 text-[#0052FF]"
                          : "hover:bg-[#8A63D2]/20 text-[#8A63D2]"
                      }`}
                    >
                      {isBaseApp ? (
                        <svg width="16" height="16" viewBox="0 0 111 111" fill="none">
                          <path d="M54.921 110.034C85.359 110.034 110.034 85.402 110.034 55.017C110.034 24.6319 85.359 0 54.921 0C26.0432 0 2.35281 22.1714 0 50.3923H72.8467V59.6416H0C2.35281 87.8625 26.0432 110.034 54.921 110.034Z" fill="#0052FF"/>
                        </svg>
                      ) : (
                        <svg width="16" height="16" viewBox="0 0 1000 1000" fill="#8A63D2">
                          <path d="M257.778 155.556H742.222V844.445H671.111V528.889H670.414C662.554 441.677 589.258 373.333 500 373.333C410.742 373.333 337.446 441.677 329.586 528.889H328.889V844.445H257.778V155.556Z"/>
                          <path d="M128.889 253.333L157.778 351.111H182.222V746.667C169.949 746.667 160 756.616 160 768.889V795.556H155.556C143.283 795.556 133.333 805.505 133.333 817.778V844.445H382.222V817.778C382.222 805.505 372.273 795.556 360 795.556H355.556V768.889C355.556 756.616 345.606 746.667 333.333 746.667H306.667V253.333H128.889Z"/>
                          <path d="M675.556 746.667C663.283 746.667 653.333 756.616 653.333 768.889V795.556H648.889C636.616 795.556 626.667 805.505 626.667 817.778V844.445H875.556V817.778C875.556 805.505 865.606 795.556 853.333 795.556H848.889V768.889C848.889 756.616 838.94 746.667 826.667 746.667V351.111H851.111L880 253.333H702.222V746.667H675.556Z"/>
                        </svg>
                      )}
                      {isBaseApp ? "Share to Feed" : "Share to Farcaster"}
                    </button>
                    <button
                      onClick={async () => {
                        setShowShareMenu(false);
                        const bookUrl = `${window.location.origin}/share/book/${encodeURIComponent(book.contentKey || '')}?source=web`;
                        const xText = `Check out "${book.title}" by ${book.author} on Net Library!\n\nDecentralized onchain media powered by @netprotocolapp`;
                        const xIntentParams = new URLSearchParams({
                          text: xText,
                          url: bookUrl,
                        });
                        const xIntentUrl = `https://twitter.com/intent/tweet?${xIntentParams.toString()}`;
                        if (isBaseApp) {
                          window.open(xIntentUrl, "_blank", "noopener,noreferrer");
                        } else {
                          await safeOpenUrl(xIntentUrl);
                        }
                      }}
                      className="w-full px-4 py-3 text-left text-sm font-mono flex items-center gap-2 hover:bg-white/10 text-white transition-colors border-t border-gray-800"
                    >
                      <svg width="14" height="14" viewBox="0 0 24 24" fill="white">
                        <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                      </svg>
                      Share to X
                    </button>
                    <button
                      onClick={async () => {
                        setShowShareMenu(false);
                        const bookUrl = `${window.location.origin}/share/book/${encodeURIComponent(book.contentKey || '')}`;
                        try {
                          await navigator.clipboard.writeText(bookUrl);
                          // Could show a toast notification here
                        } catch (err) {
                          console.error("Failed to copy link:", err);
                        }
                      }}
                      className="w-full px-4 py-3 text-left text-sm font-mono flex items-center gap-2 hover:bg-white/10 text-white transition-colors border-t border-gray-800"
                    >
                      <ClipboardIcon size={14} />
                      Copy Link
                    </button>
                  </div>
                </>
              )}
            </div>
            {cdnUrl && (
              <Button
                onClick={() => setShowCdnLinkModal(true)}
                variant="outline"
                className="w-full border-[#00ff00] text-[#00ff00] hover:bg-[#00ff00]/10 font-mono h-12"
              >
                <LinkIcon size={14} className="inline mr-1" /> CDN Link
              </Button>
            )}

            {book.isSocialReceipt && book.sourceUrl && (
              <Button
                onClick={async () => {
                  if (isBaseApp) {
                    window.open(book.sourceUrl!, "_blank", "noopener,noreferrer");
                  } else {
                    await safeOpenUrl(book.sourceUrl!);
                  }
                }}
                variant="outline"
                className="w-full border-[#00ff00]/60 text-[#00ff00]/80 hover:bg-[#00ff00]/10 font-mono h-12 flex items-center justify-center gap-2"
              >
                <GlobeIcon size={16} /> View Original Cast
              </Button>
            )}

            <Button
              onClick={onBack}
              variant="outline"
              className="w-full border-[#00ff00] text-[#00ff00] hover:bg-[#00ff00]/10 font-mono h-12"
            >
              ← Back to Library
            </Button>

            {/* Owner actions - Edit & Hide, only visible to the uploader */}
            {isUploader && (
              <div className="mt-4 space-y-2">
                {onEditDetails && (
                  <button
                    onClick={onEditDetails}
                    className="w-full py-3 rounded-lg bg-purple-500/10 text-purple-400 text-sm font-mono border border-purple-500/30 hover:bg-purple-500/20 transition-colors"
                  >
                    ✎ Edit Item Details
                  </button>
                )}
                {onHideFromLibrary && (
                  <button
                    onClick={() => setShowHideConfirm(true)}
                    className="w-full py-3 rounded-lg bg-red-500/10 text-red-400 text-sm font-mono border border-red-500/30 hover:bg-red-500/20 transition-colors"
                  >
                    <EyeOffIcon size={14} className="inline mr-1" /> Hide from Library
                  </button>
                )}
              </div>
            )}
          </div>

          {/* Comments Section */}
          {book.contentKey && (
            <CommentsSection contentKey={book.contentKey} />
          )}
        </div>
      </main>

      {/* Upvote Modal */}
      <UpvoteModal
        isOpen={showUpvoteModal}
        onClose={() => setShowUpvoteModal(false)}
        onUpvote={handleUpvote}
        isUpvoting={isUpvoting}
        bookTitle={book.title}
        currentUpvotes={displayUpvotes}
      />

      {/* Cover Art Modal */}
      <CoverArtModal
        isOpen={showCoverModal}
        onClose={() => setShowCoverModal(false)}
        coverUrl={getEffectiveCoverUrl(book)}
        title={book.title}
      />

      {/* Upvoters List Modal */}
      <UpvotersListModal
        isOpen={showUpvotersModal}
        onClose={() => setShowUpvotersModal(false)}
        upvoters={upvoters}
        totalUpvotes={displayUpvotes}
        bookTitle={book.title}
      />

      {/* Uploader Library Card Modal */}
      {uploaderMember && (
        <UserLibraryCardModal
          isOpen={showUploaderModal}
          onClose={() => {
            setShowUploaderModal(false);
            setUploaderMember(null);
            setUploaderAllMemberships(null);
          }}
          member={uploaderMember}
          allMemberships={uploaderAllMemberships}
        />
      )}

      {/* Hide Confirmation Modal */}
      {showHideConfirm && (
        <div className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4">
          <Card className="bg-[#0a0a0a] border-2 border-red-500/30 max-w-sm w-full">
            <CardContent className="p-6">
              <div className="text-center mb-6">
                <EyeOffIcon size={40} className="text-red-400 mx-auto mb-3" />
                <H4 className="text-white font-mono mb-2">Hide from Library?</H4>
                <P className="text-gray-400 font-mono text-sm">
                  This will remove <span className="text-white">{book.title}</span> from the Net Library feed.
                </P>
                <Small className="text-gray-500 font-mono block mt-2">
                  The content will still exist on Net Protocol - it just won&apos;t show up in the library anymore.
                </Small>
              </div>
              <div className="flex gap-3">
                <button
                  onClick={() => setShowHideConfirm(false)}
                  disabled={isHiding}
                  className="flex-1 py-3 rounded-lg bg-[#1a1a1a] text-gray-300 font-mono text-sm hover:bg-[#222] transition-colors disabled:opacity-50"
                >
                  Cancel
                </button>
                <button
                  onClick={handleHideFromLibrary}
                  disabled={isHiding}
                  className="flex-1 py-3 rounded-lg bg-red-500/20 text-red-400 font-mono text-sm font-bold border border-red-500/30 hover:bg-red-500/30 transition-colors disabled:opacity-50"
                >
                  {isHiding ? "Hiding..." : "Yes, Hide It"}
                </button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}

      {/* CDN Link Modal */}
      {showCdnLinkModal && cdnUrl && (
        <div
          className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4"
          onClick={() => setShowCdnLinkModal(false)}
        >
          <Card
            className="bg-[#0a0a0a] border-2 border-[#00ff00]/30 max-w-sm w-full"
            onClick={(e) => e.stopPropagation()}
          >
            <CardContent className="p-6">
              <div className="text-center mb-4">
                <LinkIcon size={32} className="text-[#00ff00] mx-auto mb-2" />
                <H4 className="text-[#00ff00] font-mono mb-1">CDN Link</H4>
                <Small className="text-gray-500 font-mono">Direct link to this content</Small>
              </div>

              <div className="bg-black rounded-lg border border-[#00ff00]/20 p-3 mb-4">
                <code className="text-[#00ff00] font-mono text-xs break-all block">
                  {cdnUrl}
                </code>
              </div>

              <button
                onClick={async () => {
                  try {
                    await navigator.clipboard.writeText(cdnUrl);
                    setCdnLinkCopied(true);
                    setTimeout(() => setCdnLinkCopied(false), 2000);
                  } catch {
                    // Fallback
                    const textarea = document.createElement("textarea");
                    textarea.value = cdnUrl;
                    document.body.appendChild(textarea);
                    textarea.select();
                    document.execCommand("copy");
                    document.body.removeChild(textarea);
                    setCdnLinkCopied(true);
                    setTimeout(() => setCdnLinkCopied(false), 2000);
                  }
                }}
                className={`w-full py-3 rounded-lg font-mono text-sm transition-all ${
                  cdnLinkCopied
                    ? "bg-green-500/20 text-green-400 border border-green-500/50"
                    : "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/30 hover:bg-[#00ff00]/30"
                }`}
              >
                {cdnLinkCopied ? "✓ Copied!" : <><ClipboardIcon size={14} className="inline mr-1" /> Copy Link</>}
              </button>

              <button
                onClick={() => setShowCdnLinkModal(false)}
                className="w-full mt-2 py-2 rounded-lg text-gray-400 font-mono text-sm hover:text-white transition-colors"
              >
                Close
              </button>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  );
}
src/features/app/components/book-review.tsx
"use client";

import { useState } from "react";
import { Card, CardContent, P, Small, Button } from "@neynar/ui";
import { PencilIcon } from "@/components/icons/net-library-icons";

interface BookReviewProps {
  contentKey: string;
  onSubmitReview?: (rating: number, reviewText: string) => void;
  existingRating?: number;
  averageRating?: number;
  totalReviews?: number;
  compact?: boolean;
}

// Star rating component - neon green hollow/filled stars
function StarRating({
  rating,
  onRate,
  readonly = false,
  size = "md"
}: {
  rating: number;
  onRate?: (rating: number) => void;
  readonly?: boolean;
  size?: "sm" | "md" | "lg";
}) {
  const [hoverRating, setHoverRating] = useState(0);

  const sizeClasses = {
    sm: { container: "w-4 h-4", stroke: 1.5 },
    md: { container: "w-6 h-6", stroke: 1.5 },
    lg: { container: "w-8 h-8", stroke: 2 }
  };

  const { container, stroke } = sizeClasses[size];
  const activeRating = hoverRating || rating;

  return (
    <div className="flex gap-1">
      {[1, 2, 3, 4, 5].map((star) => {
        const isFilled = star <= activeRating;
        return (
          <button
            key={star}
            onClick={() => !readonly && onRate?.(star)}
            onMouseEnter={() => !readonly && setHoverRating(star)}
            onMouseLeave={() => !readonly && setHoverRating(0)}
            disabled={readonly}
            className={`${container} transition-all ${readonly ? "cursor-default" : "cursor-pointer hover:scale-110"}`}
          >
            <svg
              viewBox="0 0 24 24"
              fill={isFilled ? "#00ff00" : "none"}
              stroke="#00ff00"
              strokeWidth={stroke}
              className="w-full h-full"
            >
              <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
            </svg>
          </button>
        );
      })}
    </div>
  );
}

export function BookReviewSummary({
  averageRating = 0,
  totalReviews = 0
}: {
  averageRating?: number;
  totalReviews?: number;
}) {
  if (totalReviews === 0) {
    return (
      <div className="flex items-center gap-1 text-gray-500">
        <StarRating rating={0} readonly size="sm" />
        <Small className="font-mono">No reviews</Small>
      </div>
    );
  }

  return (
    <div className="flex items-center gap-2 text-[#00ff00]">
      <StarRating rating={Math.round(averageRating)} readonly size="sm" />
      <Small className="font-mono">
        {averageRating.toFixed(1)} ({totalReviews})
      </Small>
    </div>
  );
}

export function BookReviewForm({
  contentKey: _contentKey,
  onSubmitReview,
  existingRating
}: BookReviewProps) {
  const [rating, setRating] = useState(existingRating || 0);
  const [reviewText, setReviewText] = useState("");
  const [isExpanded, setIsExpanded] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submitted, setSubmitted] = useState(false);

  const handleSubmit = async () => {
    if (rating === 0) return;

    setIsSubmitting(true);
    try {
      await onSubmitReview?.(rating, reviewText);
      setSubmitted(true);
      setIsExpanded(false);
      setReviewText("");
      // Reset submitted state after 3 seconds
      setTimeout(() => setSubmitted(false), 3000);
    } finally {
      setIsSubmitting(false);
    }
  };

  // Show success message after submission
  if (submitted) {
    return (
      <div className="flex items-center gap-2 px-3 py-2 rounded bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] text-xs font-mono w-full">
        <span className="text-base">✓</span>
        <span>Review submitted! Thanks for your feedback.</span>
      </div>
    );
  }

  if (!isExpanded) {
    return (
      <button
        onClick={() => setIsExpanded(true)}
        className="flex items-center gap-2 px-3 py-2 rounded bg-[#0a0a0a] border border-[#00ff00]/20 text-[#00ff00] text-xs font-mono hover:border-[#00ff00]/50 hover:bg-[#00ff00]/5 transition-all w-full"
      >
        <PencilIcon size={16} />
        <span>Write a Review</span>
      </button>
    );
  }

  return (
    <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
      <CardContent className="p-3 space-y-3">
        <div className="flex items-center justify-between">
          <Small className="text-[#00ff00] font-mono font-bold">Your Rating</Small>
          <button
            onClick={() => setIsExpanded(false)}
            className="text-gray-500 hover:text-gray-300 text-xs"
          >
            ✕
          </button>
        </div>

        <div className="flex justify-center py-2">
          <StarRating rating={rating} onRate={setRating} size="lg" />
        </div>

        <textarea
          value={reviewText}
          onChange={(e) => setReviewText(e.target.value)}
          placeholder="Share your thoughts (optional)..."
          className="w-full h-20 px-3 py-2 bg-black border border-[#00ff00]/20 rounded text-white font-mono text-sm placeholder:text-gray-600 focus:border-[#00ff00]/50 focus:outline-none resize-none"
          maxLength={500}
        />

        <div className="flex items-center justify-between">
          <Small className="text-gray-500 font-mono">
            {reviewText.length}/500
          </Small>
          <Button
            onClick={handleSubmit}
            disabled={rating === 0 || isSubmitting}
            className="bg-[#00ff00] text-black hover:bg-[#00dd00] font-mono text-sm disabled:opacity-50"
          >
            {isSubmitting ? "Submitting..." : "Submit Review"}
          </Button>
        </div>
      </CardContent>
    </Card>
  );
}

// Review list item
export function ReviewItem({
  username,
  pfpUrl,
  rating,
  reviewText,
  createdAt,
  helpful,
  onHelpful,
  onUserClick
}: {
  username: string;
  pfpUrl?: string;
  rating: number;
  reviewText?: string;
  createdAt: number;
  helpful: number;
  onHelpful?: () => void;
  onUserClick?: () => void;
}) {
  const timeAgo = getTimeAgo(createdAt);

  return (
    <div className="p-3 bg-[#0a0a0a] border border-[#00ff00]/10 rounded-lg space-y-2">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          {pfpUrl && (
            <button
              onClick={onUserClick}
              className="shrink-0 focus:outline-none focus:ring-2 focus:ring-[#00ff00]/50 rounded-full"
            >
              <img
                src={pfpUrl}
                alt={username}
                className="w-5 h-5 rounded-full border border-[#00ff00]/30 hover:border-[#00ff00] hover:shadow-[0_0_6px_rgba(0,255,0,0.3)] transition-all cursor-pointer"
              />
            </button>
          )}
          <Small className="text-[#00ff00] font-mono font-bold">@{username}</Small>
          <StarRating rating={rating} readonly size="sm" />
        </div>
        <Small className="text-gray-500 font-mono">{timeAgo}</Small>
      </div>

      {reviewText && (
        <P className="text-gray-300 font-mono text-sm">{reviewText}</P>
      )}

      <button
        onClick={onHelpful}
        className="flex items-center gap-1 text-xs text-gray-500 hover:text-[#00ff00] transition-colors font-mono"
      >
        👍 Helpful ({helpful})
      </button>
    </div>
  );
}

// Helper function
function getTimeAgo(timestamp: number): string {
  const seconds = Math.floor((Date.now() - timestamp) / 1000);

  if (seconds < 60) return "just now";
  if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
  if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
  if (seconds < 604800) return `${Math.floor(seconds / 86400)}d ago`;

  return new Date(timestamp).toLocaleDateString();
}
src/features/app/components/browse-tab.tsx
"use client";

import { useState, useMemo, useEffect } from "react";
import { useAccount } from "wagmi";
import { Card, CardContent, P, Small, H4 } from "@neynar/ui";
import { SearchBar } from "@/features/app/components/search-bar";
import { MediaTypeFilterBar, matchesMediaFilterWithSocial, type MediaTypeFilter, type SocialPlatformFilter } from "@/features/app/components/media-type-filter";
import { BookCard } from "@/features/app/components/book-card";
import { CoverImage } from "@/features/app/components/cover-image";
import { UserLibraryCardModal } from "@/features/app/components/user-library-card-modal";
import { UserContentPopover } from "@/features/app/components/user-content-popover";
import { CoverBackfill } from "@/features/app/components/cover-backfill";
import { useUpvoteCounts } from "@/hooks/use-upvotes";
import { useStacks, useUserStacks } from "@/hooks/use-stacks";
import { CreateStackModal } from "@/features/app/components/create-stack-modal";
import { AddToStackModal } from "@/features/app/components/add-to-stack-modal";
import { useDesktopMode } from "@/hooks/use-desktop-mode";
import { DesktopContextMenu, getBookContextMenuItems, getStackContextMenuItems } from "@/features/app/components/desktop-context-menu";
import { LibraryIcon, FolderIcon, StarIcon, LightningIcon, PartyIcon, LinkIcon, WarningIcon, RefreshIcon, UploadIcon } from "@/components/icons/net-library-icons";
import { UpvoteButton } from "@/features/app/components/upvote-button";
// StackDetail will be wired up in a future update
import type { Book, Category, Stack } from "@/features/app/types";
import type { MemberEntry } from "@/lib/net-protocol";

// Content type colors for card borders (matching book-card.tsx)
// Green = documents, White = media, Pink = social
function getContentTypeBorder(book: Book): string {
  // Social receipts are always pink
  if (book.isSocialReceipt) return "border-pink-500/50 hover:border-pink-400";

  // Check explicit mediaType
  if (book.mediaType) {
    if (["audio", "video", "image"].includes(book.mediaType)) return "border-white/40 hover:border-white/70";
    if (["pdf", "text"].includes(book.mediaType)) return "border-[#00ff00]/50 hover:border-[#00ff00]";
  }

  // Fallback: detect from filename extension
  const lowerTitle = (book.title || '').toLowerCase();
  if (/\.(mp3|wav|ogg|flac|m4a|aac|mp4|webm|mov|avi|mkv|png|jpg|jpeg|gif|webp|svg)$/.test(lowerTitle)) {
    return "border-white/40 hover:border-white/70";
  }

  // Default: document (green)
  return "border-[#00ff00]/50 hover:border-[#00ff00]";
}

// Sub-navigation type for Stacks tab
type StacksSubNav = "all-items" | "popular-stacks" | "my-stacks";

// Stack Card Component
function StackCard({ stack, rank, isOwner, onClick, isDesktop = false }: { stack: Stack; rank?: number; isOwner?: boolean; onClick?: () => void; isDesktop?: boolean }) {
  // Filesystem stacks get a more prominent neon green border
  const borderClass = stack.isFileSystem
    ? "border-[#00ff00]/30 hover:border-[#00ff00]/50"
    : "border-[#00ff00]/20 hover:border-[#00ff00]/50";

  // Desktop: enhanced hover with scale
  const cardClassName = isDesktop
    ? `bg-[#0a0a0a] border ${borderClass} hover:shadow-[0_0_15px_rgba(0,255,0,0.2)] hover:scale-[1.01] transition-all duration-200 cursor-pointer`
    : `bg-[#0a0a0a] border ${borderClass} transition-all cursor-pointer`;

  // Preview covers (up to 5 small thumbnails)
  const previewCovers = stack.previewCovers?.slice(0, 5) || [];

  // Use visibleItemCount if available (excludes hidden items), fallback to itemCount
  const displayCount = stack.visibleItemCount ?? stack.itemCount ?? 0;

  // Stack limit calculations for progress indicator
  const STACK_LIMIT = 20;
  const currentCount = stack.itemCount || 0;
  const isUnlocked = stack.unlocked;
  const isFull = !isUnlocked && currentCount >= STACK_LIMIT;
  const isNearLimit = !isUnlocked && currentCount >= 15;
  const progressPercent = isUnlocked ? 0 : Math.min(100, (currentCount / STACK_LIMIT) * 100);

  return (
    <Card
      className={cardClassName}
      onClick={onClick}
    >
      <CardContent className="p-3">
        <div className="flex items-start gap-3">
          {/* Rank Badge (for popular stacks) */}
          {rank && (
            <div
              className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold font-mono shrink-0 ${
                rank === 1
                  ? "bg-yellow-500/20 text-yellow-400 border border-yellow-500/30"
                  : rank === 2
                  ? "bg-gray-400/20 text-gray-300 border border-gray-400/30"
                  : rank === 3
                  ? "bg-orange-500/20 text-orange-400 border border-orange-500/30"
                  : "bg-[#00ff00]/10 text-[#00ff00] border border-[#00ff00]/20"
              }`}
            >
              {rank}
            </div>
          )}

          {/* Stack Info - Title, Description, Preview, then User */}
          <div className="flex-1 min-w-0">
            <P className="text-sm font-mono text-white truncate">{stack.name}</P>
            {/* Description (if exists) - under title */}
            {stack.description && (
              <Small className="text-gray-400 font-mono mt-0.5 line-clamp-2">
                {stack.description}
              </Small>
            )}
            {/* Preview covers row - between description and user */}
            {previewCovers.length > 0 && (
              <div className="flex items-center gap-1 mt-2">
                {previewCovers.map((coverUrl, index) => (
                  <div
                    key={index}
                    className="w-7 h-10 rounded bg-gray-800 flex-shrink-0 overflow-hidden"
                  >
                    <CoverImage
                      src={coverUrl}
                      alt=""
                      className="w-full h-full object-cover"
                      fallbackLogoSize="w-4 h-4"
                    />
                  </div>
                ))}
                {displayCount > previewCovers.length && (
                  <div className="w-7 h-10 rounded bg-[#00ff00]/10 flex items-center justify-center flex-shrink-0">
                    <span className="text-[8px] font-mono text-[#00ff00]">+{displayCount - previewCovers.length}</span>
                  </div>
                )}
              </div>
            )}
            {/* User/pfp - under preview */}
            <div className="flex items-center gap-2 mt-1.5">
              {stack.ownerPfpUrl && (
                <img
                  src={stack.ownerPfpUrl}
                  alt={stack.ownerUsername || "owner"}
                  className="w-4 h-4 rounded-full"
                />
              )}
              <Small className="text-gray-500 font-mono text-[10px] truncate">
                {stack.ownerUsername ? `@${stack.ownerUsername}` : (stack.owner || '').slice(0, 6) + "..."}
              </Small>
              <Small className="text-gray-600 font-mono text-[10px]">•</Small>
              <Small className="text-gray-500 font-mono text-[10px]">
                {displayCount} item{displayCount !== 1 ? "s" : ""}
              </Small>
            </div>

            {/* Stack Limit Progress Indicator - Owner only, shows at 15+ items */}
            {isOwner && !isUnlocked && isNearLimit && (
              <div className="mt-2 space-y-1">
                {/* Progress bar */}
                <div className="h-1.5 bg-[#1a1a1a] rounded-full overflow-hidden">
                  <div
                    className={`h-full transition-all duration-300 ${
                      isFull
                        ? "bg-red-500"
                        : currentCount >= 18
                        ? "bg-yellow-500"
                        : "bg-[#00ff00]"
                    }`}
                    style={{ width: `${progressPercent}%` }}
                  />
                </div>
                {/* Limit text with upgrade prompt */}
                <div className="flex items-center justify-between">
                  <Small className={`font-mono text-[9px] ${
                    isFull ? "text-red-400" : currentCount >= 18 ? "text-yellow-400" : "text-[#00ff00]/70"
                  }`}>
                    {isFull ? "Stack full!" : `${currentCount}/${STACK_LIMIT} items`}
                  </Small>
                  {(isFull || currentCount >= 18) && (
                    <Small className="font-mono text-[9px] text-purple-400">
                      Upgrade for ∞
                    </Small>
                  )}
                </div>
              </div>
            )}
          </div>

          {/* Stats / Actions */}
          <div className="flex flex-col items-end shrink-0">
            <UpvoteButton
              contentKey={stack.id}
              operatorAddress={stack.owner}
              upvoteCount={stack.upvotes || 0}
              title={stack.name}
              inline
            />
            {isOwner && (
              <Small className={`font-mono text-[9px] mt-0.5 ${
                isFull ? "text-red-400 font-bold" : isNearLimit ? "text-yellow-400" : "text-gray-500"
              }`}>
                {isUnlocked ? "∞ items" : isFull ? "FULL" : `${currentCount}/${STACK_LIMIT}`}
              </Small>
            )}
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

// Navigation context passed when selecting a book (for back navigation)
export interface BrowseNavigationContext {
  subNav: StacksSubNav;
  mediaFilter: MediaTypeFilter;
}

interface BrowseTabProps {
  books: Book[];
  categories: Category[]; // Keep for backward compatibility, but not used in main filter
  onSelectBook: (book: Book, navigationContext?: BrowseNavigationContext) => void;
  onShare: (book: Book) => void;
  isLoading?: boolean;
  error?: string | null;
  onRefresh?: () => void;
  // Optional: restore navigation state when coming back
  initialSubNav?: StacksSubNav;
  initialMediaFilter?: MediaTypeFilter;
}

// Type for uploader click callback
type UploaderInfo = { address: string; username: string; pfpUrl: string; fid?: number };

// Helper to recursively read files from a dropped folder
function readDirectoryRecursive(entry: FileSystemDirectoryEntry): Promise<File[]> {
  return new Promise((resolve) => {
    const files: File[] = [];
    const reader = entry.createReader();

    function readEntries() {
      reader.readEntries(async (entries) => {
        if (entries.length === 0) {
          resolve(files);
          return;
        }
        for (const e of entries) {
          if (e.isFile) {
            const file = await new Promise<File>((res) => {
              (e as FileSystemFileEntry).file(res);
            });
            // Preserve the relative path
            Object.defineProperty(file, "webkitRelativePath", {
              value: e.fullPath.slice(1), // Remove leading /
              writable: false,
            });
            files.push(file);
          } else if (e.isDirectory) {
            const subFiles = await readDirectoryRecursive(e as FileSystemDirectoryEntry);
            files.push(...subFiles);
          }
        }
        readEntries(); // Continue reading (readEntries returns in batches)
      });
    }
    readEntries();
  });
}

export function BrowseTab({
  books,
  categories,
  onSelectBook,
  onShare,
  isLoading,
  error,
  onRefresh,
  initialSubNav,
  initialMediaFilter,
}: BrowseTabProps) {
  const { address } = useAccount();
  const { isDesktop, canShowMultiColumnGrids } = useDesktopMode();
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedMediaFilter, setSelectedMediaFilter] = useState<MediaTypeFilter>(initialMediaFilter || "all");
  const [selectedUploader, setSelectedUploader] = useState<UploaderInfo | null>(null);
  const [uploaderMember, setUploaderMember] = useState<(MemberEntry & { pfpUrl?: string; netLink?: { url: string; label: string } | null }) | null>(null);

  // Stacks sub-navigation
  const [activeSubNav, setActiveSubNav] = useState<StacksSubNav>(initialSubNav || "all-items");
  const [stacksSortBy, setStacksSortBy] = useState<"upvotes" | "recent" | "items">("upvotes");

  // Sync initial values when props change (e.g., when navigating back from item detail)
  useEffect(() => {
    if (initialSubNav) {
      setActiveSubNav(initialSubNav);
    }
  }, [initialSubNav]);

  useEffect(() => {
    if (initialMediaFilter) {
      setSelectedMediaFilter(initialMediaFilter);
    }
  }, [initialMediaFilter]);

  // Helper to get current navigation context for back navigation
  const getNavigationContext = (): BrowseNavigationContext => ({
    subNav: activeSubNav,
    mediaFilter: selectedMediaFilter,
  });

  // Wrapper to select book with navigation context
  const selectBookWithContext = (book: Book) => {
    onSelectBook(book, getNavigationContext());
  };

  // Pagination state for stacks
  const [stacksPage, setStacksPage] = useState(1);
  const [stacksPageSize, setStacksPageSize] = useState(10);

  // Pagination state for main feed (all items)
  const [feedPage, setFeedPage] = useState(1);
  const [feedPageSize, setFeedPageSize] = useState(10);

  // Reset feed page when search/filter changes
  useEffect(() => {
    setFeedPage(1);
  }, [searchQuery, selectedMediaFilter]);

  // Reset page when sort changes
  useEffect(() => {
    setStacksPage(1);
  }, [stacksSortBy]);

  // Fetch stacks data - now with dynamic sorting and pagination
  const { stacks: allStacks, isLoading: isLoadingStacks, refresh: _refreshStacks, pagination: stacksPagination } = useStacks({
    sortBy: stacksSortBy,
    page: stacksPage,
    pageSize: stacksPageSize,
    enabled: activeSubNav === "popular-stacks"
  });
  const { stacks: myStacks, isLoading: isLoadingMyStacks, createStack, deleteStack: _deleteStack, refresh: refreshMyStacks } = useUserStacks();

  // Create stack modal state
  const [showCreateStackModal, setShowCreateStackModal] = useState(false);

  // Add to stack modal state
  const [showAddToStackModal, setShowAddToStackModal] = useState(false);
  const [bookToAddToStack, setBookToAddToStack] = useState<Book | null>(null);

  // Drag-and-drop folder state for auto-creating filesystem stacks
  const [isDragOver, setIsDragOver] = useState(false);
  const [droppedFiles, setDroppedFiles] = useState<File[] | null>(null);
  const [droppedFolderName, setDroppedFolderName] = useState<string>("");

  // State for all memberships (for users with multiple member numbers)
  const [uploaderAllMemberships, setUploaderAllMemberships] = useState<Array<{
    memberId: number;
    ensSubname: string;
    signupPlatform: "farcaster" | "base-app" | "unknown";
    joinedAt: number;
    fid?: number;
    username?: string;
    address: string;
    matchType: "primary" | "fid" | "linked";
  }> | null>(null);

  // Fetch member info when uploader is selected
  // Use the membership API which checks by address, FID, AND linked addresses
  useEffect(() => {
    if (!selectedUploader) {
      setUploaderMember(null);
      setUploaderAllMemberships(null);
      return;
    }

    // Capture the value to avoid null checks in async function
    const uploader = selectedUploader;

    async function fetchMemberInfo() {
      try {
        // Fetch net link
        let netLink = null;
        try {
          const linkResponse = await fetch(`/api/user-net-link?address=${uploader.address}`);
          if (linkResponse.ok) {
            const linkData = await linkResponse.json();
            netLink = linkData.link || null;
          }
        } catch {
          // Ignore link errors
        }

        // Use the membership API which checks address, FID, and linked addresses
        const fidParam = uploader.fid ? `&fid=${uploader.fid}` : "";
        const response = await fetch(`/api/membership?address=${uploader.address}${fidParam}`);

        if (response.ok) {
          const data = await response.json();

          if (data.isMember && data.member) {
            // Found membership via address, FID, or linked address
            setUploaderMember({
              ...data.member,
              pfpUrl: uploader.pfpUrl,
              netLink,
            });
            setUploaderAllMemberships(data.allMemberships || null);
          } else {
            // Create a placeholder member entry for non-members
            setUploaderMember({
              memberId: 0,
              address: uploader.address,
              ensSubname: "non-member",
              fid: uploader.fid,
              username: uploader.username,
              joinedAt: Date.now(),
              pfpUrl: uploader.pfpUrl,
              netLink,
            });
            setUploaderAllMemberships(null);
          }
        }
      } catch (err) {
        console.error("Failed to fetch member info:", err);
      }
    }

    fetchMemberInfo();
  }, [selectedUploader]);

  // Prepare items for upvote count fetching
  const upvoteItems = useMemo(() =>
    books
      .filter(book => book.contentKey && book.uploader?.address)
      .map(book => ({
        contentKey: book.contentKey!,
        operator: book.uploader!.address!,
      })),
    [books]
  );

  // Fetch upvote counts for all books
  const { getCount: getUpvoteCount, refresh: refreshUpvotes } = useUpvoteCounts(upvoteItems);

  // Track detected media types for items that don't have them
  const [detectedMediaTypes, setDetectedMediaTypes] = useState<Map<string, string>>(new Map());

  // Detect media types for items that don't have them
  useEffect(() => {
    const itemsNeedingDetection = books.filter(
      (book) => !book.mediaType && book.contentKey && !detectedMediaTypes.has(book.contentKey)
    );

    if (itemsNeedingDetection.length === 0) return;

    // Detect in batches to avoid overwhelming the API
    const detectBatch = async () => {
      const batch = itemsNeedingDetection.slice(0, 5); // Process 5 at a time

      const results = await Promise.all(
        batch.map(async (book) => {
          try {
            const response = await fetch(
              `/api/detect-media-type?contentKey=${encodeURIComponent(book.contentKey!)}&operator=${encodeURIComponent(book.uploader?.address || '')}&storageType=${book.storageType || "regular"}`
            );
            const data = await response.json();
            return { contentKey: book.contentKey!, mediaType: data.mediaType || "unknown" };
          } catch {
            return { contentKey: book.contentKey!, mediaType: "unknown" };
          }
        })
      );

      setDetectedMediaTypes((prev) => {
        const next = new Map(prev);
        results.forEach((r) => next.set(r.contentKey, r.mediaType));
        return next;
      });
    };

    detectBatch();
  }, [books, detectedMediaTypes]);

  // Auto-create filesystem stack when folder is dropped
  useEffect(() => {
    if (!droppedFiles || droppedFiles.length === 0 || !address) return;

    const createFilesystemStack = async () => {
      try {
        console.log("[Browse] Auto-creating filesystem stack for folder:", droppedFolderName);

        // Step 1: Create the stack
        const result = await createStack({
          name: droppedFolderName,
          description: `Imported from folder: ${droppedFolderName}`,
          isPrivate: false,
        });

        if (result?.id) {
          // Step 2: Set filesystem mode on the new stack
          await fetch("/api/stacks", {
            method: "PUT",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              stackId: result.id,
              action: "set-filesystem-mode",
              owner: address,
              sourceType: "folder",
            }),
          });

          console.log("[Browse] Stack created, navigating with files:", droppedFiles.length);

          // Step 3: Navigate to the new stack with the dropped files
          // Dispatch event with files attached for the stack detail to pick up
          window.dispatchEvent(
            new CustomEvent("navigate-to-stack-with-files", {
              detail: {
                stack: result,
                files: droppedFiles,
              },
            })
          );

          // Refresh my stacks list
          refreshMyStacks();
        }
      } catch (err) {
        console.error("[Browse] Auto-create stack failed:", err);
      } finally {
        // Clear the dropped files state
        setDroppedFiles(null);
        setDroppedFolderName("");
      }
    };

    createFilesystemStack();
  }, [droppedFiles, droppedFolderName, address, createStack, refreshMyStacks]);

  // Helper to get effective media type (from book or detected)
  const getEffectiveMediaType = (book: Book): string => {
    if (book.mediaType) return book.mediaType;
    if (book.contentKey && detectedMediaTypes.has(book.contentKey)) {
      return detectedMediaTypes.get(book.contentKey)!;
    }
    return "unknown"; // Don't assume PDF - show as unknown until detected
  };

  // Calculate media type counts for the filter bar
  const mediaTypeCounts = useMemo(() => {
    const counts = {
      all: books.length,
      documents: 0,
      documentsPdf: 0,
      documentsText: 0,
      documentsOther: 0,
      media: 0,
      mediaVideo: 0,
      mediaAudio: 0,
      mediaOther: 0,
      social: 0,
      socialFarcaster: 0,
      socialTwitter: 0,
      socialYoutube: 0,
      socialInstagram: 0,
      socialTiktok: 0,
      socialReddit: 0,
      socialBluesky: 0,
      socialThreads: 0,
      socialLinkedin: 0,
    };

    books.forEach((book) => {
      // Check for social receipts first
      if (book.isSocialReceipt && book.socialPlatform) {
        counts.social++;
        // Count by platform
        switch (book.socialPlatform) {
          case "farcaster": counts.socialFarcaster++; break;
          case "twitter": counts.socialTwitter++; break;
          case "youtube": counts.socialYoutube++; break;
          case "instagram": counts.socialInstagram++; break;
          case "tiktok": counts.socialTiktok++; break;
          case "reddit": counts.socialReddit++; break;
          case "bluesky": counts.socialBluesky++; break;
          case "threads": counts.socialThreads++; break;
          case "linkedin": counts.socialLinkedin++; break;
        }
        return; // Social receipts don't count in other categories
      }

      const mediaType = getEffectiveMediaType(book);
      switch (mediaType) {
        case "pdf":
          counts.documents++;
          counts.documentsPdf++;
          break;
        case "text":
          counts.documents++;
          counts.documentsText++;
          break;
        case "video":
          counts.media++;
          counts.mediaVideo++;
          break;
        case "audio":
          counts.media++;
          counts.mediaAudio++;
          break;
        case "image":
          counts.media++;
          counts.mediaOther++;
          break;
        case "unknown":
        default:
          // Unknown items go to documents-other until detected
          counts.documents++;
          counts.documentsOther++;
          break;
      }
    });

    return counts;
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [books, detectedMediaTypes]);

  const filteredBooks = useMemo(() => {
    return books.filter((book) => {
      const matchesSearch =
        (book.title || '').toLowerCase().includes(searchQuery.toLowerCase()) ||
        (book.author || '').toLowerCase().includes(searchQuery.toLowerCase());
      // Use effective media type (detected if not stored)
      const effectiveType = getEffectiveMediaType(book) as "pdf" | "image" | "audio" | "video" | "text" | "unknown";
      // Use extended filter that handles social receipts
      const matchesMediaType = matchesMediaFilterWithSocial(
        effectiveType,
        selectedMediaFilter,
        book.isSocialReceipt,
        book.socialPlatform as SocialPlatformFilter | undefined
      );
      return matchesSearch && matchesMediaType;
    });
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [books, searchQuery, selectedMediaFilter, detectedMediaTypes]);

  // Sort by upvotes (highest first)
  const sortedBooks = useMemo(() => {
    return [...filteredBooks].sort((a, b) => {
      const upvotesA = a.contentKey ? getUpvoteCount(a.contentKey) : 0;
      const upvotesB = b.contentKey ? getUpvoteCount(b.contentKey) : 0;
      return upvotesB - upvotesA;
    });
  }, [filteredBooks, getUpvoteCount]);

  // Paginated books for the feed
  const feedPagination = useMemo(() => {
    const total = sortedBooks.length;
    const totalPages = Math.ceil(total / feedPageSize);
    const startIndex = (feedPage - 1) * feedPageSize;
    const endIndex = startIndex + feedPageSize;
    const paginatedBooks = sortedBooks.slice(startIndex, endIndex);

    return {
      books: paginatedBooks,
      total,
      totalPages,
      page: feedPage,
      pageSize: feedPageSize,
      startIndex: startIndex + 1,
      endIndex: Math.min(endIndex, total),
    };
  }, [sortedBooks, feedPage, feedPageSize]);

  // Get 5 most recently uploaded books (sorted by uploadDate)
  const recentUploads = [...books]
    .filter((b) => !b.hidden)
    .sort((a, b) => {
      // Parse dates like "Dec 15, 2024"
      const dateA = new Date(a.uploadDate);
      const dateB = new Date(b.uploadDate);
      return dateB.getTime() - dateA.getTime();
    })
    .slice(0, 5);

  // Loading state - show skeleton cards for better perceived performance
  if (isLoading) {
    return (
      <div className="space-y-4">
        {/* Search bar skeleton */}
        <div className="h-10 bg-[#1a1a1a] rounded-lg animate-pulse" />

        {/* Filter bar skeleton */}
        <div className="flex gap-2 overflow-x-auto pb-2">
          {[1, 2, 3, 4, 5].map((i) => (
            <div key={i} className="h-8 w-20 bg-[#1a1a1a] rounded-full animate-pulse shrink-0" />
          ))}
        </div>

        {/* Status text */}
        <div className="text-center py-2">
          <Small className="text-gray-500 font-mono">Loading from Net Protocol...</Small>
        </div>

        {/* Skeleton cards grid */}
        <div className={isDesktop ? "grid grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4" : "space-y-3"}>
          {[1, 2, 3, 4, 5, 6].map((i) => (
            <Card key={i} className="bg-[#0a0a0a] border border-[#1a1a1a] animate-pulse">
              <CardContent className="p-3">
                <div className="flex gap-3">
                  {/* Cover placeholder */}
                  <div className="w-16 h-20 bg-[#1a1a1a] rounded shrink-0" />
                  <div className="flex-1 space-y-2">
                    {/* Title */}
                    <div className="h-4 bg-[#1a1a1a] rounded w-3/4" />
                    {/* Author */}
                    <div className="h-3 bg-[#1a1a1a] rounded w-1/2" />
                    {/* Category */}
                    <div className="h-3 bg-[#1a1a1a] rounded w-1/3" />
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div className="flex flex-col items-center justify-center py-20">
        <div className="text-4xl mb-4 text-yellow-400"><WarningIcon size={48} /></div>
        <P className="text-red-400 font-mono mb-2">Failed to load books</P>
        <Small className="text-gray-500 font-mono mb-4">{error}</Small>
        {onRefresh && (
          <button
            onClick={onRefresh}
            className="px-4 py-2 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg text-[#00ff00] font-mono hover:bg-[#00ff00]/20 transition-colors flex items-center gap-2"
          >
            <RefreshIcon size={14} /> Try Again
          </button>
        )}
      </div>
    );
  }

  return (
    <div
      className="space-y-4 relative"
      onDragOver={(e) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragOver(true);
      }}
      onDragLeave={(e) => {
        e.preventDefault();
        e.stopPropagation();
        // Only set false if leaving the container entirely
        if (!e.currentTarget.contains(e.relatedTarget as Node)) {
          setIsDragOver(false);
        }
      }}
      onDrop={async (e) => {
        e.preventDefault();
        e.stopPropagation();
        setIsDragOver(false);

        // Check if dropped items contain a folder
        const items = Array.from(e.dataTransfer.items);
        const fileEntries: File[] = [];
        let folderName = "Dropped Folder";

        for (const item of items) {
          const entry = item.webkitGetAsEntry?.();
          if (entry?.isDirectory) {
            folderName = entry.name;
            // Read all files from the directory recursively
            const files = await readDirectoryRecursive(entry as FileSystemDirectoryEntry);
            fileEntries.push(...files);
            break; // Use first folder found
          }
        }

        if (fileEntries.length === 0) return; // Not a folder drop, ignore

        setDroppedFiles(fileEntries);
        setDroppedFolderName(folderName);
      }}
    >
      {/* Drag overlay - shown when dragging folder over */}
      {isDragOver && (
        <div className="fixed inset-0 bg-black/80 z-50 flex items-center justify-center border-2 border-dashed border-[#00ff00] pointer-events-none">
          <div className="text-center">
            <FolderIcon size={48} className="text-[#00ff00] mx-auto mb-3" />
            <p className="text-[#00ff00] font-mono text-lg">Drop folder to create filesystem stack</p>
          </div>
        </div>
      )}

      {/* Recent Activity - Always visible at top, swipeable */}
      <div>
        <Small className="text-[#00ff00] font-mono mb-2 block">Recent Activity</Small>
        <div className="flex gap-2 overflow-x-auto pb-2 scrollbar-hide">
          {recentUploads.map((book) => (
            <div
              key={book.id}
              onClick={() => selectBookWithContext(book)}
              className={`shrink-0 w-36 p-2 bg-[#0a0a0a] border ${getContentTypeBorder(book)} rounded-lg cursor-pointer transition-colors`}
            >
              <P className="text-xs font-mono text-white truncate">{book.title}</P>
              <div className="flex items-center gap-1.5 mt-1">
                <img
                  src={book.uploader?.pfpUrl || ""}
                  alt={book.uploader?.username || "Unknown"}
                  className={`w-4 h-4 rounded-full border ${book.isAgentUploaded ? "border-[#B794F4]/30" : "border-transparent"}`}
                />
                <Small
                  className="text-[10px] font-mono truncate"
                  style={{ color: book.isAgentUploaded ? "#B794F4" : "#6b7280" }}
                >
                  @{book.uploader?.username || "Unknown"}
                  {book.isAgentUploaded && <span className="ml-0.5 text-[8px] opacity-70">[a]</span>}
                </Small>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Stacks Sub-Navigation */}
      <div className="flex gap-1 bg-[#0a0a0a] p-1 rounded-lg border border-[#1a1a1a]">
        {[
          { id: "all-items" as StacksSubNav, label: "All Items", Icon: LibraryIcon },
          { id: "popular-stacks" as StacksSubNav, label: "All Stacks", Icon: FolderIcon },
          { id: "my-stacks" as StacksSubNav, label: "My Stacks", Icon: StarIcon },
        ].map((tab) => (
          <button
            key={tab.id}
            onClick={() => setActiveSubNav(tab.id)}
            className={`flex-1 px-2 py-2 rounded-md font-mono text-xs transition-all flex items-center justify-center gap-1 ${
              activeSubNav === tab.id
                ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/30"
                : "text-gray-400 hover:text-[#00ff00]/70"
            }`}
          >
            <tab.Icon size={12} />
            {tab.label}
          </button>
        ))}
      </div>

      {/* All Items View (Default) */}
      {activeSubNav === "all-items" && (
        <>
          {/* Cover Backfill - shows if items are missing covers */}
          <CoverBackfill onComplete={onRefresh} />

      {/* Search + New Item + Create Stack row */}
      <div className="flex items-center gap-2">
        <div className="flex-1">
          <SearchBar
            value={searchQuery}
            onChange={setSearchQuery}
            placeholder="Search files..."
          />
        </div>
        <button
          onClick={() => window.dispatchEvent(new CustomEvent("navigate-to-tab", { detail: "upload" }))}
          className="px-3 py-2.5 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg text-[#00ff00] font-mono text-xs hover:bg-[#00ff00]/20 transition-colors whitespace-nowrap shrink-0 flex items-center gap-1.5"
        >
          <UploadIcon size={14} />
          <span>New Item</span>
        </button>
        <button
          onClick={() => setShowCreateStackModal(true)}
          className="px-3 py-2.5 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg text-[#00ff00] font-mono text-xs hover:bg-[#00ff00]/20 transition-colors whitespace-nowrap shrink-0"
        >
          + New Stack
        </button>
      </div>

      <MediaTypeFilterBar
        selectedFilter={selectedMediaFilter}
        onSelect={setSelectedMediaFilter}
        counts={mediaTypeCounts}
      />
      {/* Book list - grid on desktop, single column on mobile */}
      <div className={canShowMultiColumnGrids ? "grid grid-cols-2 gap-3" : "space-y-3"}>
        {feedPagination.books.map((book) => (
          <DesktopContextMenu
            key={book.id}
            items={getBookContextMenuItems({
              onRead: () => selectBookWithContext(book),
              onShare: () => onShare(book),
              onAddToStack: () => {
                setBookToAddToStack(book);
                setShowAddToStackModal(true);
              },
            })}
          >
            <BookCard
              book={book}
              categories={categories}
              upvoteCount={book.contentKey ? getUpvoteCount(book.contentKey) : 0}
              onSelect={() => selectBookWithContext(book)}
              onShare={() => onShare(book)}
              onUpvoteSuccess={refreshUpvotes}
              onUploaderClick={setSelectedUploader}
              onAddToStack={() => {
                setBookToAddToStack(book);
                setShowAddToStackModal(true);
              }}
              isDesktop={isDesktop}
            />
          </DesktopContextMenu>
        ))}
        {sortedBooks.length === 0 && (
          <div className={`text-center py-12 ${canShowMultiColumnGrids ? "col-span-2" : ""}`}>
            <div className="text-4xl mb-3 text-[#00ff00]"><LibraryIcon size={48} /></div>
            <p className="text-gray-400 font-mono">
              {books.length === 0 ? "No books uploaded yet" : "No books found"}
            </p>
            <p className="text-gray-500 text-sm font-mono">
              {books.length === 0
                ? "Be the first to upload to Net Protocol!"
                : "Try adjusting your search or filters"}
            </p>
          </div>
        )}
      </div>

      {/* Feed Pagination Controls */}
      {feedPagination.totalPages > 1 && (
        <div className="flex flex-col gap-3 pt-4 border-t border-[#1a1a1a]">
          {/* Page Info and Per-Page Selector */}
          <div className="flex items-center justify-between">
            <Small className="text-gray-500 font-mono text-[10px]">
              {feedPagination.startIndex}-{feedPagination.endIndex} of {feedPagination.total} items
            </Small>
            <div className="flex items-center gap-2">
              <Small className="text-gray-500 font-mono text-[10px]">Per page:</Small>
              <div className="flex gap-1">
                {[10, 25, 100].map((size) => (
                  <button
                    key={size}
                    onClick={() => {
                      setFeedPageSize(size);
                      setFeedPage(1);
                    }}
                    className={`px-2 py-1 rounded text-[10px] font-mono transition-all ${
                      feedPageSize === size
                        ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/50"
                        : "bg-[#1a1a1a] text-gray-400 border border-transparent hover:border-[#00ff00]/30"
                    }`}
                  >
                    {size}
                  </button>
                ))}
              </div>
            </div>
          </div>

          {/* Page Navigation */}
          <div className="flex items-center justify-center gap-2">
            <button
              onClick={() => setFeedPage(1)}
              disabled={feedPage === 1}
              className="px-2 py-1.5 rounded bg-[#1a1a1a] text-gray-400 font-mono text-xs disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#00ff00]/10 hover:text-[#00ff00] transition-all"
              title="First page"
            >
              ««
            </button>
            <button
              onClick={() => setFeedPage(p => Math.max(1, p - 1))}
              disabled={feedPage === 1}
              className="px-3 py-1.5 rounded bg-[#1a1a1a] text-gray-400 font-mono text-xs disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#00ff00]/10 hover:text-[#00ff00] transition-all"
            >
              ← Prev
            </button>
            <span className="px-3 py-1.5 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded text-[#00ff00] font-mono text-xs">
              {feedPage} / {feedPagination.totalPages}
            </span>
            <button
              onClick={() => setFeedPage(p => Math.min(feedPagination.totalPages, p + 1))}
              disabled={feedPage === feedPagination.totalPages}
              className="px-3 py-1.5 rounded bg-[#1a1a1a] text-gray-400 font-mono text-xs disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#00ff00]/10 hover:text-[#00ff00] transition-all"
            >
              Next →
            </button>
            <button
              onClick={() => setFeedPage(feedPagination.totalPages)}
              disabled={feedPage === feedPagination.totalPages}
              className="px-2 py-1.5 rounded bg-[#1a1a1a] text-gray-400 font-mono text-xs disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#00ff00]/10 hover:text-[#00ff00] transition-all"
              title="Last page"
            >
              »»
            </button>
          </div>
        </div>
      )}

        </>
      )}

      {/* All Stacks View */}
      {activeSubNav === "popular-stacks" && (
        <div className="space-y-4">
          {/* Header with sort options */}
          <div className="flex items-center justify-between">
            <H4 className="text-[#00ff00] font-mono flex items-center gap-2"><FolderIcon size={16} /> All Stacks</H4>
            <button
              onClick={() => setShowCreateStackModal(true)}
              className="px-3 py-1.5 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg text-[#00ff00] font-mono text-xs hover:bg-[#00ff00]/20 transition-colors"
            >
              + New Stack
            </button>
          </div>

          {/* Sort Filter Bar */}
          <div className="flex items-center gap-2">
            <Small className="text-gray-500 font-mono text-[10px] shrink-0">Sort:</Small>
            <div className="flex gap-1 flex-1 overflow-x-auto">
              {[
                { id: "upvotes" as const, label: "Top", title: "Most Upvoted", Icon: LightningIcon },
                { id: "recent" as const, label: "New", title: "Recently Created", Icon: PartyIcon },
                { id: "items" as const, label: "Size", title: "Most Items", Icon: LibraryIcon },
              ].map((sort) => (
                <button
                  key={sort.id}
                  onClick={() => setStacksSortBy(sort.id)}
                  title={sort.title}
                  className={`px-2.5 py-1.5 rounded text-[10px] font-mono whitespace-nowrap transition-all flex items-center gap-1 ${
                    stacksSortBy === sort.id
                      ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/50"
                      : "bg-[#1a1a1a] text-gray-400 border border-transparent hover:border-[#00ff00]/30"
                  }`}
                >
                  <sort.Icon size={10} />
                  {sort.label}
                </button>
              ))}
            </div>
          </div>

          {isLoadingStacks ? (
            <div className="flex flex-col items-center justify-center py-12">
              <div className="text-3xl mb-3 animate-pulse text-[#00ff00]"><FolderIcon size={36} /></div>
              <P className="text-[#00ff00] font-mono">Loading stacks...</P>
            </div>
          ) : allStacks.length === 0 ? (
            <div className="text-center py-12">
              <div className="text-4xl mb-3 text-[#00ff00]"><FolderIcon size={48} /></div>
              <P className="text-gray-400 font-mono">No stacks yet</P>
              <Small className="text-gray-500 font-mono block mt-1">
                Create the first stack to curate your favorite items!
              </Small>
              <button
                onClick={() => setShowCreateStackModal(true)}
                className="mt-4 px-4 py-2 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg text-[#00ff00] font-mono text-sm hover:bg-[#00ff00]/20 transition-colors"
              >
                + New Stack
              </button>
            </div>
          ) : (
            <div className="space-y-3">
              {/* Section header based on sort */}
              <Small className="text-gray-500 font-mono text-[10px] uppercase tracking-wider flex items-center gap-1">
                {stacksSortBy === "upvotes" && <><LightningIcon size={10} /> Most Upvoted Stacks</>}
                {stacksSortBy === "recent" && <><PartyIcon size={10} /> Recently Created</>}
                {stacksSortBy === "items" && <><LibraryIcon size={10} /> Biggest Collections</>}
              </Small>
              {allStacks.map((stack, index) => (
                <DesktopContextMenu
                  key={stack.id}
                  items={getStackContextMenuItems({
                    onView: () => window.dispatchEvent(new CustomEvent("navigate-to-stack", { detail: stack })),
                    onShare: () => {
                      const shareUrl = `${window.location.origin}?stack=${stack.id}`;
                      navigator.clipboard.writeText(shareUrl);
                      alert("Stack link copied to clipboard!");
                    },
                  })}
                >
                  <StackCard
                    stack={stack}
                    rank={stacksSortBy === "upvotes" ? ((stacksPage - 1) * stacksPageSize) + index + 1 : undefined}
                    isDesktop={isDesktop}
                    onClick={() => {
                      window.dispatchEvent(new CustomEvent("navigate-to-stack", { detail: stack }));
                    }}
                  />
                </DesktopContextMenu>
              ))}

              {/* Pagination Controls */}
              {stacksPagination && stacksPagination.totalPages > 1 && (
                <div className="flex flex-col gap-3 pt-4 border-t border-[#1a1a1a]">
                  {/* Page Info and Per-Page Selector */}
                  <div className="flex items-center justify-between">
                    <Small className="text-gray-500 font-mono text-[10px]">
                      Page {stacksPagination.page} of {stacksPagination.totalPages} • {stacksPagination.total} stacks
                    </Small>
                    <div className="flex items-center gap-2">
                      <Small className="text-gray-500 font-mono text-[10px]">Show:</Small>
                      <div className="flex gap-1">
                        {[10, 25, 100].map((size) => (
                          <button
                            key={size}
                            onClick={() => {
                              setStacksPageSize(size);
                              setStacksPage(1); // Reset to first page when changing page size
                            }}
                            className={`px-2 py-1 rounded text-[10px] font-mono transition-all ${
                              stacksPageSize === size
                                ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/50"
                                : "bg-[#1a1a1a] text-gray-400 border border-transparent hover:border-[#00ff00]/30"
                            }`}
                          >
                            {size}
                          </button>
                        ))}
                      </div>
                    </div>
                  </div>

                  {/* Page Navigation */}
                  <div className="flex items-center justify-center gap-2">
                    <button
                      onClick={() => setStacksPage(1)}
                      disabled={stacksPage === 1}
                      className="px-2 py-1.5 rounded bg-[#1a1a1a] text-gray-400 font-mono text-xs disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#00ff00]/10 hover:text-[#00ff00] transition-all"
                      title="First page"
                    >
                      ««
                    </button>
                    <button
                      onClick={() => setStacksPage(p => Math.max(1, p - 1))}
                      disabled={stacksPage === 1}
                      className="px-3 py-1.5 rounded bg-[#1a1a1a] text-gray-400 font-mono text-xs disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#00ff00]/10 hover:text-[#00ff00] transition-all"
                    >
                      ← Prev
                    </button>
                    <span className="px-3 py-1.5 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded text-[#00ff00] font-mono text-xs">
                      {stacksPage}
                    </span>
                    <button
                      onClick={() => setStacksPage(p => Math.min(stacksPagination.totalPages, p + 1))}
                      disabled={stacksPage === stacksPagination.totalPages}
                      className="px-3 py-1.5 rounded bg-[#1a1a1a] text-gray-400 font-mono text-xs disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#00ff00]/10 hover:text-[#00ff00] transition-all"
                    >
                      Next →
                    </button>
                    <button
                      onClick={() => setStacksPage(stacksPagination.totalPages)}
                      disabled={stacksPage === stacksPagination.totalPages}
                      className="px-2 py-1.5 rounded bg-[#1a1a1a] text-gray-400 font-mono text-xs disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#00ff00]/10 hover:text-[#00ff00] transition-all"
                      title="Last page"
                    >
                      »»
                    </button>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
      )}

      {/* My Stacks View */}
      {activeSubNav === "my-stacks" && (
        <div className="space-y-4">
          <div className="flex items-center justify-between">
            <H4 className="text-[#00ff00] font-mono flex items-center gap-2"><FolderIcon size={16} /> My Stacks</H4>
            {address && (
              <button
                onClick={() => setShowCreateStackModal(true)}
                className="px-3 py-1.5 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg text-[#00ff00] font-mono text-xs hover:bg-[#00ff00]/20 transition-colors"
              >
                + New Stack
              </button>
            )}
          </div>

          {!address ? (
            <div className="text-center py-12">
              <div className="text-4xl mb-3 text-[#00ff00]"><LinkIcon size={48} /></div>
              <P className="text-gray-400 font-mono">Connect wallet to view your stacks</P>
              <Small className="text-gray-500 font-mono block mt-1">
                Your stacks will appear here once connected
              </Small>
            </div>
          ) : isLoadingMyStacks ? (
            <div className="flex flex-col items-center justify-center py-12">
              <div className="text-3xl mb-3 animate-pulse text-[#00ff00]"><FolderIcon size={36} /></div>
              <P className="text-[#00ff00] font-mono">Loading your stacks...</P>
            </div>
          ) : myStacks.length === 0 ? (
            <div className="text-center py-12">
              <div className="text-4xl mb-3 text-[#00ff00]"><FolderIcon size={48} /></div>
              <P className="text-gray-400 font-mono">You haven&apos;t created any stacks yet</P>
              <Small className="text-gray-500 font-mono block mt-1">
                Stacks let you curate and share your favorite items
              </Small>
              <button
                onClick={() => setShowCreateStackModal(true)}
                className="mt-4 px-4 py-2 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg text-[#00ff00] font-mono text-sm hover:bg-[#00ff00]/20 transition-colors"
              >
                + New Stack
              </button>
            </div>
          ) : (
            <div className="space-y-3">
              {myStacks.map((stack) => (
                <DesktopContextMenu
                  key={stack.id}
                  items={getStackContextMenuItems({
                    onView: () => window.dispatchEvent(new CustomEvent("navigate-to-stack", { detail: stack })),
                    onEdit: () => window.dispatchEvent(new CustomEvent("navigate-to-stack", { detail: stack })),
                    onShare: () => {
                      const shareUrl = `${window.location.origin}?stack=${stack.id}`;
                      navigator.clipboard.writeText(shareUrl);
                      alert("Stack link copied to clipboard!");
                    },
                    isOwner: true,
                  })}
                >
                  <StackCard
                    stack={stack}
                    isOwner
                    isDesktop={isDesktop}
                    onClick={() => {
                      window.dispatchEvent(new CustomEvent("navigate-to-stack", { detail: stack }));
                    }}
                  />
                </DesktopContextMenu>
              ))}
            </div>
          )}
        </div>
      )}

      {/* Create Stack Modal */}
      <CreateStackModal
        isOpen={showCreateStackModal}
        onClose={() => setShowCreateStackModal(false)}
        onSuccess={(_stack) => {
          refreshMyStacks();
          setActiveSubNav("my-stacks");
        }}
        createStack={createStack}
      />

      {/* Add to Stack Modal */}
      {bookToAddToStack && (
        <AddToStackModal
          isOpen={showAddToStackModal}
          onClose={() => {
            setShowAddToStackModal(false);
            setBookToAddToStack(null);
          }}
          book={bookToAddToStack}
          onSuccess={() => {
            refreshMyStacks();
          }}
          onCreateStack={() => {
            setShowAddToStackModal(false);
            setShowCreateStackModal(true);
          }}
        />
      )}

      {/* Uploader Library Card Modal - show for members */}
      {uploaderMember && (
        <UserLibraryCardModal
          isOpen={!!selectedUploader}
          onClose={() => {
            setSelectedUploader(null);
            setUploaderMember(null);
            setUploaderAllMemberships(null);
          }}
          member={uploaderMember}
          allMemberships={uploaderAllMemberships}
        />
      )}

      {/* User Content Popover - fallback for non-members or while loading */}
      {selectedUploader && !uploaderMember && (
        <UserContentPopover
          isOpen={true}
          onClose={() => {
            setSelectedUploader(null);
          }}
          address={selectedUploader.address}
          username={selectedUploader.username}
          pfpUrl={selectedUploader.pfpUrl}
          fid={selectedUploader.fid}
        />
      )}
    </div>
  );
}
src/features/app/components/category-filter.tsx
"use client";

import type { Category } from "@/features/app/types";
import { FlameIcon } from "@/components/icons/net-library-icons";

interface CategoryFilterProps {
  categories: Category[];
  selectedCategory: string;
  onSelect: (categoryId: string) => void;
  showTrendingIndicator?: boolean;
}

export function CategoryFilter({ categories, selectedCategory, onSelect, showTrendingIndicator = true }: CategoryFilterProps) {
  return (
    <div className="flex gap-2 overflow-x-auto pb-2 scrollbar-hide">
      {categories.map((cat, index) => {
        // Show fire emoji for top 3 trending categories (excluding "All")
        const isTrending = showTrendingIndicator && cat.id !== "all" && index > 0 && index <= 3;

        return (
          <button
            key={cat.id}
            onClick={() => onSelect(cat.id)}
            className={`shrink-0 px-3 py-1.5 rounded-full text-xs font-mono transition-all flex items-center gap-1 ${
              selectedCategory === cat.id
                ? "bg-[#00ff00] text-black"
                : "bg-[#1a1a1a] text-gray-400 hover:bg-[#222] hover:text-[#00ff00]"
            }`}
          >
            {cat.emoji} {cat.label}
            {isTrending && <FlameIcon size={10} className="text-orange-400" />}
          </button>
        );
      })}
    </div>
  );
}
src/features/app/components/cdn-link-upload.tsx
"use client";

import { useState, useEffect } from "react";
import { Card, CardContent, Button, P, Small, H4 } from "@neynar/ui";
import { WarningIcon, InfoIcon, DocumentIcon, ImageIcon, AudioIcon, VideoIcon, NoteIcon, PackageIcon, LibraryIcon, LockIcon } from "@/components/icons/net-library-icons";
import type { Category, Stack } from "@/features/app/types";

// Detect content type from URL and headers
export type ContentType = "pdf" | "image" | "audio" | "video" | "text" | "unknown";

export function detectContentType(url: string, contentTypeHeader?: string): ContentType {
  const urlLower = url.toLowerCase();

  // Check URL extension first
  if (urlLower.match(/\.(pdf)(\?|$)/)) return "pdf";
  if (urlLower.match(/\.(png|jpg|jpeg|gif|webp|svg|bmp|ico)(\?|$)/)) return "image";
  if (urlLower.match(/\.(mp3|wav|ogg|flac|m4a|aac|wma)(\?|$)/)) return "audio";
  if (urlLower.match(/\.(mp4|webm|mov|avi|mkv|m4v|wmv)(\?|$)/)) return "video";
  if (urlLower.match(/\.(txt|md|html|htm|json|xml|csv)(\?|$)/)) return "text";

  // Check content-type header if available
  if (contentTypeHeader) {
    const ct = contentTypeHeader.toLowerCase();
    if (ct.includes("pdf")) return "pdf";
    if (ct.includes("image")) return "image";
    if (ct.includes("audio")) return "audio";
    if (ct.includes("video")) return "video";
    if (ct.includes("text") || ct.includes("json") || ct.includes("xml")) return "text";
  }

  return "unknown";
}

// Content type icon component
function ContentTypeIcon({ type, size = 16 }: { type: ContentType; size?: number }) {
  switch (type) {
    case "pdf": return <DocumentIcon size={size} />;
    case "image": return <ImageIcon size={size} />;
    case "audio": return <AudioIcon size={size} />;
    case "video": return <VideoIcon size={size} />;
    case "text": return <NoteIcon size={size} />;
    default: return <PackageIcon size={size} />;
  }
}

// Get label for content type
function getContentTypeLabel(type: ContentType): string {
  switch (type) {
    case "pdf": return "PDF Document";
    case "image": return "Image";
    case "audio": return "Audio";
    case "video": return "Video";
    case "text": return "Text/Document";
    default: return "Unknown";
  }
}

interface CdnLinkUploadProps {
  categories: Category[];
  stacks: Stack[];
  isLoadingStacks: boolean;
  onUpload: (data: {
    cdnUrl: string;
    contentType: ContentType;
    title: string;
    author: string;
    selectedCategories: string[];
    selectedStackIds: string[];
    publicationYear?: string;
    publisher?: string;
    isbn?: string;
    coverArtUrl?: string;
  }) => Promise<void>;
  isUploading: boolean;
}

export function CdnLinkUpload({
  categories,
  stacks,
  isLoadingStacks,
  onUpload,
  isUploading,
}: CdnLinkUploadProps) {
  const [cdnUrl, setCdnUrl] = useState("");
  const [isValidating, setIsValidating] = useState(false);
  const [validationError, setValidationError] = useState<string | null>(null);
  const [detectedType, setDetectedType] = useState<ContentType | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);

  // Metadata
  const [title, setTitle] = useState("");
  const [author, setAuthor] = useState("");
  const [publicationYear, setPublicationYear] = useState("");
  const [publisher, setPublisher] = useState("");
  const [isbn, setIsbn] = useState("");
  const [coverArtUrl, setCoverArtUrl] = useState("");
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [selectedStackIds, setSelectedStackIds] = useState<string[]>([]);
  const [showCategoryDropdown, setShowCategoryDropdown] = useState(false);
  const [showStackDropdown, setShowStackDropdown] = useState(false);

  // Validate CDN URL - must be a valid Net Protocol URL
  // Accepts: /storage/raw/, /chunked-storage/file/, or /content/ patterns
  // Server will look up operator for /content/ URLs from discovery index
  const validateUrl = async (url: string) => {
    if (!url.trim()) {
      setValidationError(null);
      setDetectedType(null);
      setPreviewUrl(null);
      return;
    }

    setIsValidating(true);
    setValidationError(null);

    try {
      const parsedUrl = new URL(url);

      // Must be a storedon.net URL
      if (!parsedUrl.hostname.endsWith("storedon.net")) {
        setValidationError("Only storedon.net URLs are supported");
        setDetectedType(null);
        setPreviewUrl(null);
        setIsValidating(false);
        return;
      }

      const pathname = parsedUrl.pathname;

      // Check for valid URL patterns
      // Pattern 1: /net/{chainId}/storage/load/{operator}/{filename} - PREFERRED user-facing format
      const loadStorageMatch = pathname.match(/\/net\/\d+\/storage\/load\/([^/]+)\/(.+)/);
      // Pattern 2: /net/{chainId}/storage/raw/{operator}/{key} - API format
      const rawStorageMatch = pathname.match(/\/net\/\d+\/storage\/raw\/([^/]+)\/(.+)/);
      // Pattern 3: /net/{chainId}/chunked-storage/file/{operator}/{key}
      const chunkedStorageMatch = pathname.match(/\/net\/\d+\/chunked-storage\/file\/([^/]+)\/(.+)/);
      // Pattern 4: /content/{key} - DEPRECATED, returns 404
      const contentMatch = pathname.match(/\/content\/(.+)/);

      // Reject deprecated /content/ URLs explicitly
      if (contentMatch) {
        setValidationError(
          "The /content/{key} URL format is deprecated. Please use /storage/load/{operator}/{filename} format instead."
        );
        setDetectedType(null);
        setPreviewUrl(null);
        setIsValidating(false);
        return;
      }

      let isValidPattern = false;
      if (loadStorageMatch) {
        // /storage/load/ URLs just need a filename - no hex key validation needed
        const [, operator, filename] = loadStorageMatch;
        isValidPattern = operator.startsWith("0x") && filename.length > 0;
      } else if (rawStorageMatch) {
        const [, , storageKey] = rawStorageMatch;
        isValidPattern = storageKey.startsWith("0x") || /^[a-fA-F0-9]{64}$/.test(storageKey);
      } else if (chunkedStorageMatch) {
        const [, , storageKey] = chunkedStorageMatch;
        isValidPattern = storageKey.startsWith("0x") || /^[a-fA-F0-9]{64}$/.test(storageKey);
      }

      if (!isValidPattern) {
        setValidationError(
          "Invalid URL format. Use: /storage/load/{operator}/{filename} (preferred), /storage/raw/{operator}/{key}, or /chunked-storage/file/{operator}/{key}"
        );
        setDetectedType(null);
        setPreviewUrl(null);
        setIsValidating(false);
        return;
      }

      // URL is valid - detect content type
      const type = detectContentType(url);
      setDetectedType(type);
      setPreviewUrl(url);

      // For images, we can preview directly
      if (type === "image") {
        // Try loading the image to verify it works
        const img = new Image();
        img.onload = () => {
          setIsValidating(false);
        };
        img.onerror = () => {
          setValidationError("Could not load image from URL");
          setIsValidating(false);
        };
        img.src = url;
        return;
      }

      setIsValidating(false);
    } catch {
      setValidationError("Please enter a valid URL");
      setDetectedType(null);
      setIsValidating(false);
    }
  };

  // Debounce URL validation
  useEffect(() => {
    const timer = setTimeout(() => {
      validateUrl(cdnUrl);
    }, 500);
    return () => clearTimeout(timer);
  }, [cdnUrl]);

  // Toggle category selection
  const toggleCategory = (categoryId: string) => {
    setSelectedCategories(prev => {
      if (prev.includes(categoryId)) {
        return prev.filter(id => id !== categoryId);
      }
      if (prev.length >= 3) return prev;
      return [...prev, categoryId];
    });
  };

  // Toggle stack selection
  const toggleStack = (stackId: string) => {
    setSelectedStackIds(prev =>
      prev.includes(stackId)
        ? prev.filter(id => id !== stackId)
        : [...prev, stackId]
    );
  };

  // Handle upload
  const handleUpload = async () => {
    if (!cdnUrl.trim() || !title.trim() || !detectedType) return;

    await onUpload({
      cdnUrl: cdnUrl.trim(),
      contentType: detectedType,
      title: title.trim(),
      author: author.trim() || "Unknown",
      selectedCategories,
      selectedStackIds,
      publicationYear: publicationYear.trim() || undefined,
      publisher: publisher.trim() || undefined,
      isbn: isbn.trim() || undefined,
      coverArtUrl: coverArtUrl.trim() || undefined,
    });
  };

  const isValid = cdnUrl.trim() && title.trim() && detectedType && !validationError;

  return (
    <div className="space-y-4">
      {/* URL Input */}
      <Card className="bg-[#0a0a0a] border border-[#00ff00]/30">
        <CardContent className="p-4">
          <H4 className="text-[#00ff00] font-mono mb-3">Import from Net Protocol</H4>

          <P className="text-gray-400 text-sm font-mono mb-4">
            Paste a Net Protocol CDN link to add existing onchain content to your library.
          </P>

          <div className="space-y-3">
            <div>
              <Small className="text-gray-400 font-mono mb-1 block">CDN URL *</Small>
              <input
                type="url"
                value={cdnUrl}
                onChange={(e) => setCdnUrl(e.target.value)}
                placeholder="https://storedon.net/net/8453/storage/load/0x.../filename"
                className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00] transition-colors"
              />
              {isValidating && (
                <Small className="text-yellow-400 font-mono mt-1 block">
                  Validating URL...
                </Small>
              )}
              {validationError && (
                <Small className="text-red-400 font-mono mt-1 flex items-center gap-1">
                  <WarningIcon size={12} /> {validationError}
                </Small>
              )}
            </div>

            {/* Content Type Detection */}
            {detectedType && !validationError && (
              <div className="p-3 bg-black border border-[#00ff00]/20 rounded-lg">
                <div className="flex items-center gap-2 mb-2">
                  <ContentTypeIcon type={detectedType} size={28} />
                  <div>
                    <P className="text-white font-mono text-sm font-bold">
                      {getContentTypeLabel(detectedType)}
                    </P>
                    <Small className="text-gray-500 font-mono">Detected content type</Small>
                  </div>
                </div>

                {/* Preview for images */}
                {detectedType === "image" && previewUrl && (
                  <div className="mt-3 rounded-lg overflow-hidden border border-[#00ff00]/20 max-h-48">
                    <img
                      src={previewUrl}
                      alt="Preview"
                      className="w-full h-full object-contain bg-black"
                      onError={() => setValidationError("Could not load image")}
                    />
                  </div>
                )}

                {/* Preview for audio */}
                {detectedType === "audio" && previewUrl && (
                  <div className="mt-3">
                    <audio
                      controls
                      className="w-full"
                      style={{ height: 40 }}
                    >
                      <source src={previewUrl} />
                      Your browser does not support audio playback.
                    </audio>
                  </div>
                )}

                {/* Preview for video */}
                {detectedType === "video" && previewUrl && (
                  <div className="mt-3 rounded-lg overflow-hidden border border-[#00ff00]/20 max-h-48">
                    <video
                      controls
                      className="w-full max-h-48"
                      preload="metadata"
                    >
                      <source src={previewUrl} />
                      Your browser does not support video playback.
                    </video>
                  </div>
                )}
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Metadata */}
      <Card className="bg-[#0a0a0a] border border-[#00ff00]/20">
        <CardContent className="p-4 space-y-3">
          <H4 className="text-[#00ff00] font-mono text-sm">Details</H4>

          {/* Title */}
          <div>
            <Small className="text-gray-400 font-mono mb-1 block">Title *</Small>
            <input
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="What is this?"
              className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00] transition-colors"
            />
          </div>

          {/* Author */}
          <div>
            <Small className="text-gray-400 font-mono mb-1 block">Author / Creator</Small>
            <input
              type="text"
              value={author}
              onChange={(e) => setAuthor(e.target.value)}
              placeholder="Who made this?"
              className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00] transition-colors"
            />
          </div>

          {/* Cover Art URL (for non-image content) */}
          {detectedType && detectedType !== "image" && (
            <div>
              <Small className="text-gray-400 font-mono mb-1 block">Cover Art URL (optional)</Small>
              <input
                type="url"
                value={coverArtUrl}
                onChange={(e) => setCoverArtUrl(e.target.value)}
                placeholder="https://... (image URL for thumbnail)"
                className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00] transition-colors"
              />
              {coverArtUrl && (
                <div className="mt-2 w-20 h-28 rounded border border-[#00ff00]/20 overflow-hidden">
                  <img
                    src={coverArtUrl}
                    alt="Cover preview"
                    className="w-full h-full object-cover"
                    onError={(e) => {
                      (e.target as HTMLImageElement).style.display = "none";
                    }}
                  />
                </div>
              )}
            </div>
          )}

          {/* Year & Publisher */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <Small className="text-gray-400 font-mono mb-1 block">Year</Small>
              <input
                type="text"
                value={publicationYear}
                onChange={(e) => setPublicationYear(e.target.value)}
                placeholder="2024"
                className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00] transition-colors"
              />
            </div>
            <div>
              <Small className="text-gray-400 font-mono mb-1 block">Publisher</Small>
              <input
                type="text"
                value={publisher}
                onChange={(e) => setPublisher(e.target.value)}
                placeholder="Publisher name"
                className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00] transition-colors"
              />
            </div>
          </div>

          {/* ISBN/DOI */}
          <div>
            <Small className="text-gray-400 font-mono mb-1 block">ISBN / DOI / Identifier</Small>
            <input
              type="text"
              value={isbn}
              onChange={(e) => setIsbn(e.target.value)}
              placeholder="Optional identifier"
              className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00] transition-colors"
            />
          </div>

          {/* Categories */}
          <div className="relative">
            <Small className="text-gray-400 font-mono mb-1 block">Categories (up to 3)</Small>
            <button
              onClick={() => setShowCategoryDropdown(!showCategoryDropdown)}
              className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-left font-mono text-sm flex items-center justify-between hover:border-[#00ff00]/50 transition-colors"
            >
              {selectedCategories.length === 0 ? (
                <span className="text-gray-500">Select categories...</span>
              ) : (
                <span className="text-white">
                  {selectedCategories.map(id => {
                    const cat = categories.find(c => c.id === id);
                    return cat ? `${cat.emoji} ${cat.label}` : id;
                  }).join(", ")}
                </span>
              )}
              <span className="text-[#00ff00]">▾</span>
            </button>

            {showCategoryDropdown && (
              <div className="absolute top-full left-0 right-0 mt-1 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg max-h-48 overflow-y-auto z-20">
                {categories.map(cat => (
                  <button
                    key={cat.id}
                    onClick={() => toggleCategory(cat.id)}
                    className={`w-full px-3 py-2 text-left font-mono text-sm flex items-center gap-2 transition-colors ${
                      selectedCategories.includes(cat.id)
                        ? "bg-[#00ff00]/10 text-[#00ff00]"
                        : "text-gray-300 hover:bg-[#1a1a1a]"
                    }`}
                  >
                    <span>{cat.emoji}</span>
                    <span>{cat.label}</span>
                    {selectedCategories.includes(cat.id) && <span className="ml-auto">✓</span>}
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Stacks */}
          <div className="relative">
            <Small className="text-gray-400 font-mono mb-1 block">Add to Stacks</Small>
            <button
              onClick={() => setShowStackDropdown(!showStackDropdown)}
              disabled={isLoadingStacks || stacks.length === 0}
              className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-left font-mono text-sm flex items-center justify-between hover:border-[#00ff00]/50 transition-colors disabled:opacity-50"
            >
              {isLoadingStacks ? (
                <span className="text-gray-500">Loading stacks...</span>
              ) : stacks.length === 0 ? (
                <span className="text-gray-500">No stacks yet</span>
              ) : selectedStackIds.length === 0 ? (
                <span className="text-gray-500">Select stacks (optional)...</span>
              ) : (
                <span className="text-white">
                  {selectedStackIds.length} stack{selectedStackIds.length !== 1 ? "s" : ""} selected
                </span>
              )}
              <span className="text-[#00ff00]">▾</span>
            </button>

            {showStackDropdown && stacks.length > 0 && (
              <>
                {/* Backdrop to close on click outside */}
                <div
                  className="fixed inset-0 z-10"
                  onClick={() => setShowStackDropdown(false)}
                />
                <div className="absolute top-full left-0 right-0 mt-1 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg overflow-hidden z-20">
                  <div className="max-h-40 overflow-y-auto">
                    {stacks.map(stack => (
                      <button
                        key={stack.id}
                        onClick={() => toggleStack(stack.id)}
                        className={`w-full px-3 py-2 text-left font-mono text-sm flex items-center gap-2 transition-colors ${
                          selectedStackIds.includes(stack.id)
                            ? "bg-purple-500/10 text-purple-400"
                            : "text-gray-300 hover:bg-[#1a1a1a]"
                        }`}
                      >
                        <LibraryIcon size={14} className="text-purple-400" />
                        <span className="truncate">{stack.name}</span>
                        {selectedStackIds.includes(stack.id) && <span className="ml-auto">✓</span>}
                        {stack.isPrivate && <LockIcon size={12} className="text-gray-500" />}
                      </button>
                    ))}
                  </div>
                  {/* Done button for mobile */}
                  <button
                    type="button"
                    onClick={() => setShowStackDropdown(false)}
                    className="w-full px-3 py-2 text-center font-mono text-sm text-[#00ff00] bg-[#00ff00]/10 border-t border-[#00ff00]/20 hover:bg-[#00ff00]/20 transition-colors"
                  >
                    Done
                  </button>
                </div>
              </>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Upload Button */}
      <Button
        onClick={handleUpload}
        disabled={!isValid || isUploading}
        className="w-full bg-[#00ff00] text-black font-mono font-bold py-3 hover:bg-[#00ff00]/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
      >
        {isUploading ? "Adding to Library..." : "Add to My Library"}
      </Button>

      {/* Info Box */}
      <Card className="bg-blue-500/10 border border-blue-500/30">
        <CardContent className="p-3">
          <Small className="text-blue-300 font-mono flex items-start gap-2">
            <InfoIcon size={14} className="shrink-0 mt-0.5" />
            <span>This creates a reference to existing onchain content. The content itself is already stored on Net Protocol - we are just adding metadata so it appears in your library.</span>
          </Small>
        </CardContent>
      </Card>
    </div>
  );
}
src/features/app/components/changelog-section.tsx
"use client";

import { useState } from "react";
import { Card, CardContent, P, Small, H4 } from "@neynar/ui";
import { useChangelog, type ChangelogEntry, type ChangeEntry } from "@/hooks/use-changelog";

const TYPE_BADGES: Record<ChangeEntry["type"], { emoji: string; color: string }> = {
  feature: { emoji: "🆕", color: "text-green-400" },
  fix: { emoji: "🐛", color: "text-red-400" },
  improvement: { emoji: "✨", color: "text-yellow-400" },
  breaking: { emoji: "⚠️", color: "text-orange-400" },
  docs: { emoji: "📝", color: "text-blue-400" },
  internal: { emoji: "🔧", color: "text-gray-400" },
};

const CATEGORY_LABELS: Record<ChangeEntry["category"], string> = {
  ui: "UI",
  api: "API",
  database: "Database",
  achievements: "Achievements",
  uploads: "Uploads",
  social: "Social",
  membership: "Membership",
  other: "Other",
};

function ChangelogEntryCard({ entry, isExpanded, onToggle }: {
  entry: ChangelogEntry;
  isExpanded: boolean;
  onToggle: () => void;
}) {
  const date = new Date(entry.publishedAt).toLocaleDateString("en-US", {
    year: "numeric",
    month: "short",
    day: "numeric",
  });

  const featureCount = entry.changes.filter(c => c.type === "feature").length;
  const fixCount = entry.changes.filter(c => c.type === "fix").length;
  const improvementCount = entry.changes.filter(c => c.type === "improvement").length;

  return (
    <Card className="bg-[#0a0a0a] border border-[#00ff00]/20">
      <CardContent className="p-3">
        <button
          onClick={onToggle}
          className="w-full text-left"
        >
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <span className="text-[#00ff00] font-mono font-bold">v{entry.version}</span>
              <Small className="text-gray-500 font-mono">{date}</Small>
            </div>
            <div className="flex items-center gap-2">
              {featureCount > 0 && (
                <span className="text-xs bg-green-500/20 text-green-400 px-1.5 py-0.5 rounded font-mono">
                  +{featureCount}
                </span>
              )}
              {fixCount > 0 && (
                <span className="text-xs bg-red-500/20 text-red-400 px-1.5 py-0.5 rounded font-mono">
                  🐛{fixCount}
                </span>
              )}
              {improvementCount > 0 && (
                <span className="text-xs bg-yellow-500/20 text-yellow-400 px-1.5 py-0.5 rounded font-mono">
                  ✨{improvementCount}
                </span>
              )}
              <span className={`text-gray-400 transition-transform ${isExpanded ? "rotate-180" : ""}`}>
                ▼
              </span>
            </div>
          </div>
          <P className="text-gray-300 font-mono text-sm mt-1">{entry.summary}</P>
        </button>

        {isExpanded && (
          <div className="mt-3 pt-3 border-t border-[#00ff00]/10 space-y-2">
            {entry.changes.map((change, i) => {
              const badge = TYPE_BADGES[change.type];
              return (
                <div key={i} className="flex items-start gap-2">
                  <span className={badge.color}>{badge.emoji}</span>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="text-white font-mono text-sm font-medium">{change.title}</span>
                      <span className="text-[10px] bg-gray-800 text-gray-400 px-1.5 py-0.5 rounded font-mono uppercase">
                        {CATEGORY_LABELS[change.category]}
                      </span>
                    </div>
                    <Small className="text-gray-400 font-mono block">{change.description}</Small>
                    {change.technical && (
                      <Small className="text-gray-500 font-mono text-[10px] block mt-0.5 italic">
                        Tech: {change.technical}
                      </Small>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </CardContent>
    </Card>
  );
}

export function ChangelogSection({ maxEntries = 5 }: { maxEntries?: number }) {
  const { entries, currentVersion, isLoading } = useChangelog(maxEntries);
  const [expandedVersion, setExpandedVersion] = useState<string | null>(null);

  if (isLoading) {
    return (
      <Card className="bg-[#0a0a0a] border border-[#00ff00]/20">
        <CardContent className="p-4">
          <div className="animate-pulse space-y-3">
            <div className="h-5 bg-gray-800 rounded w-1/3" />
            <div className="h-4 bg-gray-800 rounded w-2/3" />
          </div>
        </CardContent>
      </Card>
    );
  }

  if (entries.length === 0) {
    return (
      <Card className="bg-[#0a0a0a] border border-[#00ff00]/20">
        <CardContent className="p-4 text-center">
          <P className="text-gray-500 font-mono">No changelog entries yet</P>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="bg-[#0a0a0a] border border-[#00ff00]/20">
      <CardContent className="p-4">
        <div className="flex items-center justify-between mb-3">
          <H4 className="text-[#00ff00] font-mono">📋 Changelog</H4>
          <Small className="text-gray-500 font-mono">Current: v{currentVersion}</Small>
        </div>

        <div className="max-h-[400px] overflow-y-auto space-y-2 pr-1 scrollbar-thin scrollbar-thumb-[#00ff00]/30 scrollbar-track-transparent">
          {entries.map((entry) => (
            <ChangelogEntryCard
              key={entry.version}
              entry={entry}
              isExpanded={expandedVersion === entry.version}
              onToggle={() => setExpandedVersion(
                expandedVersion === entry.version ? null : entry.version
              )}
            />
          ))}
        </div>
      </CardContent>
    </Card>
  );
}
src/features/app/components/collections-button.tsx
"use client";

import { useState } from "react";
import { Small } from "@neynar/ui";
import { useCollections } from "@/hooks/use-collections";
import { useAccount } from "wagmi";

interface CollectionsButtonProps {
  contentKey: string;
  title?: string;
  className?: string;
}

export function CollectionsButton({ contentKey, className = "" }: CollectionsButtonProps) {
  const { address } = useAccount();
  const {
    collections,
    isLoading,
    createCollection,
    addBook,
    removeBook,
    refresh,
  } = useCollections(address);

  const [isOpen, setIsOpen] = useState(false);
  const [showCreateForm, setShowCreateForm] = useState(false);
  const [newCollectionName, setNewCollectionName] = useState("");
  const [isCreating, setIsCreating] = useState(false);

  // Check if item is in any collection
  const collectionsContainingItem = collections.filter((c) =>
    c.bookIds.includes(contentKey)
  );

  const handleCreateCollection = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!newCollectionName.trim()) return;

    setIsCreating(true);
    const collection = await createCollection(newCollectionName.trim());
    setIsCreating(false);

    if (collection) {
      setNewCollectionName("");
      setShowCreateForm(false);
      // Automatically add item to new collection
      await addBook(collection.id, contentKey);
      refresh();
    }
  };

  const handleToggleCollection = async (collectionId: string) => {
    const collection = collections.find((c) => c.id === collectionId);
    if (!collection) return;

    const isInCollection = collection.bookIds.includes(contentKey);

    if (isInCollection) {
      await removeBook(collectionId, contentKey);
    } else {
      await addBook(collectionId, contentKey);
    }
    refresh();
  };

  if (!address) return null;

  return (
    <div className="relative">
      {/* Button */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className={`flex items-center gap-1 px-2 py-1 rounded-lg border transition-colors ${
          collectionsContainingItem.length > 0
            ? "bg-[#00ff00]/20 border-[#00ff00]/50 text-[#00ff00]"
            : "bg-[#0a0a0a] border-[#1a1a1a] text-gray-400 hover:border-[#00ff00]/30 hover:text-[#00ff00]"
        } ${className}`}
      >
        <span className="text-sm">📁</span>
        {collectionsContainingItem.length > 0 && (
          <span className="text-[10px] font-mono">{collectionsContainingItem.length}</span>
        )}
      </button>

      {/* Dropdown */}
      {isOpen && (
        <>
          {/* Backdrop */}
          <div
            className="fixed inset-0 z-40"
            onClick={() => {
              setIsOpen(false);
              setShowCreateForm(false);
            }}
          />

          {/* Dropdown Panel */}
          <div className="absolute right-0 top-full mt-1 w-56 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg shadow-lg z-50 overflow-hidden">
            <div className="px-3 py-2 border-b border-[#00ff00]/20">
              <Small className="text-[#00ff00] font-mono font-bold">Add to Collection</Small>
            </div>

            <div className="max-h-48 overflow-y-auto">
              {isLoading ? (
                <div className="p-3 text-center">
                  <Small className="text-gray-500 font-mono">Loading...</Small>
                </div>
              ) : collections.length === 0 && !showCreateForm ? (
                <div className="p-3 text-center">
                  <Small className="text-gray-500 font-mono">No collections yet</Small>
                </div>
              ) : (
                <div className="py-1">
                  {collections.map((collection) => {
                    const isInCollection = collection.bookIds.includes(contentKey);
                    return (
                      <button
                        key={collection.id}
                        onClick={() => handleToggleCollection(collection.id)}
                        className={`w-full px-3 py-2 text-left flex items-center justify-between hover:bg-[#1a1a1a] transition-colors ${
                          isInCollection ? "bg-[#00ff00]/10" : ""
                        }`}
                      >
                        <div className="flex items-center gap-2 min-w-0">
                          <span className="text-sm shrink-0">{collection.emoji || "📁"}</span>
                          <span className="text-xs text-white font-mono truncate">
                            {collection.name}
                          </span>
                          <span className="text-[10px] text-gray-500 font-mono shrink-0">
                            ({collection.bookIds.length})
                          </span>
                        </div>
                        {isInCollection && (
                          <span className="text-[#00ff00] text-sm shrink-0">✓</span>
                        )}
                      </button>
                    );
                  })}
                </div>
              )}
            </div>

            {/* Create New Collection */}
            <div className="border-t border-[#00ff00]/20">
              {showCreateForm ? (
                <form onSubmit={handleCreateCollection} className="p-2 space-y-2">
                  <input
                    type="text"
                    value={newCollectionName}
                    onChange={(e) => setNewCollectionName(e.target.value)}
                    placeholder="Collection name..."
                    className="w-full px-2 py-1.5 rounded bg-black border border-[#00ff00]/30 text-white font-mono text-xs placeholder:text-gray-600 focus:border-[#00ff00] focus:outline-none"
                    autoFocus
                    disabled={isCreating}
                  />
                  <div className="flex gap-1">
                    <button
                      type="button"
                      onClick={() => {
                        setShowCreateForm(false);
                        setNewCollectionName("");
                      }}
                      className="flex-1 px-2 py-1 rounded bg-[#1a1a1a] text-gray-400 font-mono text-xs hover:bg-[#222]"
                      disabled={isCreating}
                    >
                      Cancel
                    </button>
                    <button
                      type="submit"
                      disabled={isCreating || !newCollectionName.trim()}
                      className="flex-1 px-2 py-1 rounded bg-[#00ff00] text-black font-mono text-xs font-bold hover:bg-[#00dd00] disabled:opacity-50"
                    >
                      {isCreating ? "..." : "Create"}
                    </button>
                  </div>
                </form>
              ) : (
                <button
                  onClick={() => setShowCreateForm(true)}
                  className="w-full px-3 py-2 text-left text-xs font-mono text-[#00ff00] hover:bg-[#1a1a1a] transition-colors"
                >
                  + New Collection
                </button>
              )}
            </div>
          </div>
        </>
      )}
    </div>
  );
}
src/features/app/components/comment-upvote-modal.tsx
"use client";

import { useState, useMemo } from "react";
import { Button, P, Small, H4 } from "@neynar/ui";
import { COMMENT_UPVOTE_COST_ETH } from "@/hooks/use-comment-upvotes";

// Current ETH price in USD (could be fetched from an API in the future)
const ETH_PRICE_USD = 2500;

interface CommentUpvoteModalProps {
  isOpen: boolean;
  onClose: () => void;
  onUpvote: (count: number) => void;
  isUpvoting: boolean;
  commenterName: string;
  currentUpvotes: number;
}

type InputMode = "count" | "eth" | "usdc";

const PRESET_AMOUNTS = [1, 10, 100, 1000];

export function CommentUpvoteModal({
  isOpen,
  onClose,
  onUpvote,
  isUpvoting,
  commenterName,
  currentUpvotes,
}: CommentUpvoteModalProps) {
  const [selectedPreset, setSelectedPreset] = useState<number | "custom">(1);
  const [customAmount, setCustomAmount] = useState("");
  const [inputMode, setInputMode] = useState<InputMode>("count");

  // Calculate upvote count based on input mode
  const upvoteCount = useMemo(() => {
    if (selectedPreset !== "custom") {
      return selectedPreset;
    }

    const value = parseFloat(customAmount) || 0;
    if (value <= 0) return 0;

    switch (inputMode) {
      case "count":
        return Math.floor(value);
      case "eth":
        // ETH amount / cost per upvote
        return Math.floor(value / COMMENT_UPVOTE_COST_ETH);
      case "usdc": {
        // Convert USDC to ETH, then to upvotes
        const ethValue = value / ETH_PRICE_USD;
        return Math.floor(ethValue / COMMENT_UPVOTE_COST_ETH);
      }
      default:
        return 0;
    }
  }, [selectedPreset, customAmount, inputMode]);

  // Calculate total cost in ETH
  const totalCostEth = upvoteCount * COMMENT_UPVOTE_COST_ETH;
  const totalCostUsd = totalCostEth * ETH_PRICE_USD;

  const handleSubmit = () => {
    if (upvoteCount > 0) {
      onUpvote(upvoteCount);
    }
  };

  const handlePresetClick = (amount: number) => {
    setSelectedPreset(amount);
    setCustomAmount("");
  };

  const handleCustomClick = () => {
    setSelectedPreset("custom");
    setInputMode("count");
    setCustomAmount("");
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="bg-[#0a0a0a] border-2 border-[#00ff00]/30 rounded-xl w-full max-w-sm overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 py-3 border-b border-[#00ff00]/20 flex items-center justify-between">
          <H4 className="text-[#00ff00] font-mono">▲ Upvote Comment</H4>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors"
          >
            ✕
          </button>
        </div>

        {/* Content */}
        <div className="p-4 space-y-4">
          {/* Explanation banner */}
          <div className="bg-purple-500/10 border border-purple-500/30 rounded-lg p-3">
            <div className="flex items-start gap-2">
              <span className="text-purple-400 text-lg">💬</span>
              <div>
                <P className="text-purple-300 font-mono text-xs font-bold">Tip This Comment</P>
                <Small className="text-purple-300/70 font-mono text-[10px] leading-tight block mt-0.5">
                  Upvotes are onchain tips to the commenter via Score Protocol. High-upvoted comments rise to the top!
                </Small>
              </div>
            </div>
          </div>

          {/* Comment info */}
          <div className="text-center">
            <P className="text-white font-mono text-sm truncate">Comment by {commenterName}</P>
            <Small className="text-gray-500 font-mono">Currently: {currentUpvotes} upvotes</Small>
          </div>

          {/* Preset amounts */}
          <div className="grid grid-cols-4 gap-2">
            {PRESET_AMOUNTS.map((amount) => (
              <button
                key={amount}
                onClick={() => handlePresetClick(amount)}
                className={`py-3 rounded-lg font-mono text-sm font-bold transition-all ${
                  selectedPreset === amount
                    ? "bg-[#00ff00] text-black"
                    : "bg-[#1a1a1a] text-white border border-[#333] hover:border-[#00ff00]/50"
                }`}
              >
                {amount}
              </button>
            ))}
          </div>

          {/* Custom amount button */}
          <button
            onClick={handleCustomClick}
            className={`w-full py-3 rounded-lg font-mono text-sm font-bold transition-all ${
              selectedPreset === "custom"
                ? "bg-[#00ff00] text-black"
                : "bg-[#1a1a1a] text-white border border-[#333] hover:border-[#00ff00]/50"
            }`}
          >
            Custom Amount
          </button>

          {/* Custom input section */}
          {selectedPreset === "custom" && (
            <div className="space-y-3">
              {/* Input mode selector */}
              <div className="flex gap-1 bg-[#1a1a1a] rounded-lg p-1">
                {[
                  { mode: "count" as InputMode, label: "# Upvotes" },
                  { mode: "eth" as InputMode, label: "ETH" },
                  { mode: "usdc" as InputMode, label: "USDC" },
                ].map(({ mode, label }) => (
                  <button
                    key={mode}
                    onClick={() => {
                      setInputMode(mode);
                      setCustomAmount("");
                    }}
                    className={`flex-1 py-2 rounded-md font-mono text-xs transition-all ${
                      inputMode === mode
                        ? "bg-[#00ff00]/20 text-[#00ff00]"
                        : "text-gray-400 hover:text-white"
                    }`}
                  >
                    {label}
                  </button>
                ))}
              </div>

              {/* Input field */}
              <div className="relative">
                <input
                  type="number"
                  value={customAmount}
                  onChange={(e) => setCustomAmount(e.target.value)}
                  placeholder={
                    inputMode === "count"
                      ? "Enter number of upvotes"
                      : inputMode === "eth"
                      ? "Enter ETH amount"
                      : "Enter USDC amount"
                  }
                  className="w-full px-4 py-3 bg-[#1a1a1a] border border-[#333] rounded-lg text-white font-mono text-sm placeholder-gray-500 focus:outline-none focus:border-[#00ff00]/50"
                  min="0"
                  step={inputMode === "count" ? "1" : "0.0001"}
                />
                {inputMode !== "count" && customAmount && upvoteCount > 0 && (
                  <div className="absolute right-3 top-1/2 -translate-y-1/2">
                    <Small className="text-[#00ff00] font-mono">
                      = {upvoteCount} upvote{upvoteCount !== 1 ? "s" : ""}
                    </Small>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Cost summary */}
          {upvoteCount > 0 && (
            <div className="bg-[#1a1a1a] rounded-lg p-3 space-y-1">
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">Upvotes</Small>
                <Small className="text-white font-mono font-bold">{upvoteCount}</Small>
              </div>
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">Cost</Small>
                <Small className="text-[#00ff00] font-mono font-bold">
                  {totalCostEth.toFixed(6)} ETH
                </Small>
              </div>
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">≈ USD</Small>
                <Small className="text-gray-400 font-mono">
                  ${totalCostUsd.toFixed(2)}
                </Small>
              </div>
            </div>
          )}

          {/* Submit button */}
          <Button
            onClick={handleSubmit}
            disabled={isUpvoting || upvoteCount === 0}
            className={`w-full h-12 font-mono font-bold ${
              isUpvoting
                ? "bg-[#00ff00]/20 text-[#00ff00] cursor-wait"
                : upvoteCount === 0
                ? "bg-gray-600 text-gray-400 cursor-not-allowed"
                : "bg-[#00ff00] text-black hover:bg-[#00dd00]"
            }`}
          >
            {isUpvoting ? (
              "Processing..."
            ) : upvoteCount === 0 ? (
              "Select Amount"
            ) : (
              `▲ Upvote ${upvoteCount}x`
            )}
          </Button>

          {/* Info */}
          <Small className="text-gray-500 font-mono text-center block text-[10px]">
            Each upvote costs {COMMENT_UPVOTE_COST_ETH} ETH (~${(COMMENT_UPVOTE_COST_ETH * ETH_PRICE_USD).toFixed(4)})
          </Small>
        </div>
      </div>
    </div>
  );
}
src/features/app/components/comments-section.tsx
"use client";
// Onchain comments via Net Protocol - v4 with threading and upvotes
import { useState, useEffect, useMemo, useCallback } from "react";
import { Card, CardContent, Small, P } from "@neynar/ui";
import { useOnchainComments, type OnchainComment } from "@/hooks/use-onchain-comments";
import { useCommentUpvote, useCommentUpvoteCounts, COMMENT_UPVOTE_COST_ETH } from "@/hooks/use-comment-upvotes";
import { useAccount } from "wagmi";
import { useUserProfile } from "@/hooks/use-user-profile";
import { UserLibraryCardModal } from "./user-library-card-modal";
import { CommentUpvoteModal } from "./comment-upvote-modal";
import type { MemberEntry } from "@/lib/net-protocol";
import { safeOpenUrl } from "@/lib/app-mode";
import { FlameIcon } from "@/components/icons/net-library-icons";

// URL regex for detecting links in comment text
const URL_REGEX = /(https?:\/\/[^\s<]+[^\s<.,;:!?"'\])}>])/gi;

// Component to render text with clickable links
function LinkedText({ text }: { text: string }) {
  const parts = useMemo(() => {
    const segments: { type: "text" | "link"; content: string }[] = [];
    let lastIndex = 0;
    let match;

    // Reset regex state
    URL_REGEX.lastIndex = 0;

    while ((match = URL_REGEX.exec(text)) !== null) {
      if (match.index > lastIndex) {
        segments.push({ type: "text", content: text.slice(lastIndex, match.index) });
      }
      segments.push({ type: "link", content: match[0] });
      lastIndex = match.index + match[0].length;
    }

    if (lastIndex < text.length) {
      segments.push({ type: "text", content: text.slice(lastIndex) });
    }

    return segments;
  }, [text]);

  if (parts.length === 0 || (parts.length === 1 && parts[0].type === "text")) {
    return <span>{text}</span>;
  }

  return (
    <>
      {parts.map((part, i) =>
        part.type === "link" ? (
          <button
            key={i}
            onClick={() => safeOpenUrl(part.content)}
            className="text-[#00ff00] hover:underline focus:outline-none break-all"
          >
            {part.content.length > 40 ? `${part.content.slice(0, 37)}...` : part.content}
          </button>
        ) : (
          <span key={i}>{part.content}</span>
        )
      )}
    </>
  );
}

interface CommentsSectionProps {
  contentKey: string;
}

interface MemberLookup {
  [address: string]: MemberEntry | null;
}

// Info modal explaining onchain comments
function OnchainInfoModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 bg-black/80 z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg max-w-sm w-full p-4 space-y-3"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between">
          <span className="text-[#00ff00] font-mono font-bold">Onchain Comments</span>
          <button
            onClick={onClose}
            className="text-gray-500 hover:text-white transition-colors text-xl leading-none"
          >
            ×
          </button>
        </div>

        <div className="space-y-2 text-sm font-mono text-gray-300">
          <p>
            Comments on Net Library are stored <span className="text-[#00ff00]">permanently onchain</span> via Net Protocol on Base.
          </p>
          <p>
            This means your comments:
          </p>
          <ul className="list-disc list-inside space-y-1 text-gray-400">
            <li>Can never be deleted or censored</li>
            <li>Are publicly verifiable on the blockchain</li>
            <li>Will exist forever, even if this app disappears</li>
            <li>Are owned by you, tied to your wallet</li>
          </ul>
          <p className="text-gray-500 text-xs pt-2">
            Posting requires a small gas fee on Base (~$0.01).
          </p>
        </div>

        <a
          href="https://netprotocol.app"
          target="_blank"
          rel="noopener noreferrer"
          className="block text-center text-xs font-mono text-[#00ff00]/70 hover:text-[#00ff00] transition-colors"
        >
          Learn more about Net Protocol →
        </a>
      </div>
    </div>
  );
}

export function CommentsSection({ contentKey }: CommentsSectionProps) {
  const { address } = useAccount();
  const { profile: userProfile } = useUserProfile();
  const {
    comments,
    allCommentIds,
    totalCount,
    isLoading,
    postComment,
    isPosting,
    isConfirmed,
    postError,
  } = useOnchainComments(contentKey);

  // Comment upvotes via Score Protocol
  const { upvoteComment, isUpvoting: isUpvotingComment, isConfirmed: upvoteConfirmed } = useCommentUpvote();
  const { getCount: getUpvoteCount, refresh: refreshUpvotes, isLoading: loadingUpvotes } = useCommentUpvoteCounts(allCommentIds);

  // Sort comments by upvotes (desc) then timestamp (newest first for ties)
  // This re-sorts whenever upvote counts change
  // Also recursively sorts replies within each thread
  const sortedComments = useMemo(() => {
    if (comments.length === 0) return [];

    // Recursive function to sort replies within each comment
    const sortReplies = (comment: OnchainComment): OnchainComment => {
      if (!comment.replies || comment.replies.length === 0) {
        return comment;
      }

      // Sort replies by upvotes then timestamp
      const sortedReplies = [...comment.replies]
        .sort((a, b) => {
          const upvoteA = getUpvoteCount(a.id);
          const upvoteB = getUpvoteCount(b.id);
          const upvoteDiff = upvoteB - upvoteA;
          if (upvoteDiff !== 0) return upvoteDiff;
          return b.timestamp - a.timestamp;
        })
        .map(sortReplies); // Recursively sort nested replies

      return { ...comment, replies: sortedReplies };
    };

    // Sort top-level by upvotes then timestamp
    const sorted = [...comments]
      .sort((a, b) => {
        const upvoteA = getUpvoteCount(a.id);
        const upvoteB = getUpvoteCount(b.id);
        const upvoteDiff = upvoteB - upvoteA;
        if (upvoteDiff !== 0) return upvoteDiff;
        return b.timestamp - a.timestamp; // Newest first for ties
      })
      .map(sortReplies); // Sort replies within each thread

    return sorted;
  }, [comments, getUpvoteCount]);

  // Pagination state - show 20 top-level comments at a time
  const [visibleCount, setVisibleCount] = useState(20);
  const paginatedComments = useMemo(() => {
    return sortedComments.slice(0, visibleCount);
  }, [sortedComments, visibleCount]);
  const hasMoreComments = sortedComments.length > visibleCount;

  const [newComment, setNewComment] = useState("");
  const [showSuccess, setShowSuccess] = useState(false);
  const [showInfoModal, setShowInfoModal] = useState(false);
  const [replyingTo, setReplyingTo] = useState<OnchainComment | null>(null);

  // Comment upvote modal state
  const [upvoteModalComment, setUpvoteModalComment] = useState<OnchainComment | null>(null);

  // Member lookup and library card modal state
  const [memberLookup, setMemberLookup] = useState<MemberLookup>({});
  const [selectedMember, setSelectedMember] = useState<(MemberEntry & { pfpUrl?: string }) | null>(null);
  const [showLibraryCard, setShowLibraryCard] = useState(false);

  // Fetch member registry to check membership status
  useEffect(() => {
    async function fetchMembers() {
      try {
        const response = await fetch("/api/member-registry");
        if (!response.ok) return;
        const data = await response.json();
        const members = data.members || [];

        const lookup: MemberLookup = {};
        for (const member of members) {
          if (!member.address) continue;
          lookup[member.address.toLowerCase()] = member;
        }
        setMemberLookup(lookup);
      } catch (err) {
        console.error("Failed to fetch member registry:", err);
      }
    }
    fetchMembers();
  }, []);

  // Refresh upvote counts when a new upvote is confirmed
  useEffect(() => {
    if (upvoteConfirmed) {
      refreshUpvotes();
    }
  }, [upvoteConfirmed, refreshUpvotes]);

  // Handle opening library card for a member
  const handleViewLibraryCard = (comment: OnchainComment) => {
    if (!comment.sender) return;
    const member = memberLookup[comment.sender.toLowerCase()];
    if (member) {
      setSelectedMember({
        ...member,
        pfpUrl: comment.pfpUrl,
      });
      setShowLibraryCard(true);
    }
  };

  // Handle opening Farcaster profile
  const handleViewFarcasterProfile = (username: string) => {
    safeOpenUrl(`https://warpcast.com/${username}`);
  };

  // Find a comment by ID (including nested replies)
  const findCommentById = useCallback((id: string): OnchainComment | null => {
    const searchInComments = (list: OnchainComment[]): OnchainComment | null => {
      for (const comment of list) {
        if (comment.id === id) return comment;
        if (comment.replies) {
          const found = searchInComments(comment.replies);
          if (found) return found;
        }
      }
      return null;
    };
    return searchInComments(comments);
  }, [comments]);

  // Handle clicking upvote - opens modal
  const handleUpvoteClick = useCallback((commentId: string) => {
    const comment = findCommentById(commentId);
    if (comment) {
      setUpvoteModalComment(comment);
    }
  }, [findCommentById]);

  // Handle actual upvote from modal
  const handleUpvoteSubmit = useCallback(async (count: number) => {
    if (!upvoteModalComment) return;
    const success = await upvoteComment(upvoteModalComment.id, count);
    if (success) {
      // Modal will close after transaction starts processing
      setUpvoteModalComment(null);
    }
  }, [upvoteModalComment, upvoteComment]);

  // Handle replying to a comment
  const handleReply = (comment: OnchainComment) => {
    setReplyingTo(comment);
  };

  const cancelReply = () => {
    setReplyingTo(null);
  };

  // Show success message when comment is confirmed onchain
  useEffect(() => {
    if (isConfirmed) {
      setShowSuccess(true);
      setNewComment("");
      setReplyingTo(null);
      const timer = setTimeout(() => setShowSuccess(false), 3000);
      return () => clearTimeout(timer);
    }
  }, [isConfirmed]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!address || !newComment.trim() || isPosting) return;

    await postComment(newComment.trim(), {
      username: userProfile?.username,
      pfpUrl: userProfile?.pfpUrl,
      parentCommentId: replyingTo?.id,
    });
  };

  const formatTimeAgo = (timestamp: number) => {
    const seconds = Math.floor((Date.now() - timestamp) / 1000);
    if (seconds < 60) return "just now";
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60) return `${minutes}m ago`;
    const hours = Math.floor(minutes / 60);
    if (hours < 24) return `${hours}h ago`;
    const days = Math.floor(hours / 24);
    if (days < 7) return `${days}d ago`;
    return new Date(timestamp).toLocaleDateString();
  };

  const truncateAddress = (addr: string) => {
    return `${addr.slice(0, 6)}...${addr.slice(-4)}`;
  };

  return (
    <div className="space-y-3">
      <OnchainInfoModal isOpen={showInfoModal} onClose={() => setShowInfoModal(false)} />

      <div className="flex items-center justify-between">
        <div className="flex items-center gap-1.5">
          <Small className="text-[#00ff00] font-mono font-bold uppercase tracking-wider">
            Onchain Comments {totalCount > 0 && `(${totalCount})`}
          </Small>
          <button
            onClick={() => setShowInfoModal(true)}
            className="w-4 h-4 rounded-full bg-[#00ff00]/20 text-[#00ff00] text-[10px] font-bold hover:bg-[#00ff00]/30 transition-colors flex items-center justify-center"
            aria-label="What are onchain comments?"
          >
            i
          </button>
        </div>
        {(isLoading || loadingUpvotes) && <Small className="text-gray-500 font-mono">Loading...</Small>}
      </div>

      {/* Success message */}
      {showSuccess && (
        <Card className="bg-[#00ff00]/10 border border-[#00ff00]/50">
          <CardContent className="p-2 text-center">
            <Small className="text-[#00ff00] font-mono">
              ✓ {replyingTo ? "Reply" : "Comment"} posted onchain!
            </Small>
          </CardContent>
        </Card>
      )}

      {/* Error message */}
      {postError && (
        <Card className="bg-red-500/10 border border-red-500/50">
          <CardContent className="p-2 text-center">
            <Small className="text-red-400 font-mono text-xs">
              {postError}
            </Small>
          </CardContent>
        </Card>
      )}

      {/* Reply indicator */}
      {replyingTo && (
        <div className="flex items-center gap-2 px-3 py-2 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg">
          <span className="text-[#00ff00] font-mono text-xs">
            Replying to {replyingTo.username ? `@${replyingTo.username}` : truncateAddress(replyingTo.sender)}
          </span>
          <button
            onClick={cancelReply}
            className="text-gray-400 hover:text-white transition-colors text-sm"
          >
            ×
          </button>
        </div>
      )}

      {/* Comment Form */}
      {address ? (
        <form onSubmit={handleSubmit} className="space-y-2">
          <div className="flex gap-2">
            <img
              src={userProfile?.pfpUrl || `https://api.dicebear.com/7.x/identicon/svg?seed=${address}`}
              alt="Your avatar"
              className="w-8 h-8 rounded-full border border-[#00ff00]/30 shrink-0"
            />
            <input
              type="text"
              value={newComment}
              onChange={(e) => setNewComment(e.target.value)}
              placeholder={replyingTo ? "Write a reply..." : "Add an onchain comment..."}
              className="flex-1 px-3 py-2 rounded-lg bg-black border border-[#00ff00]/30 text-white font-mono text-sm placeholder:text-gray-500 focus:border-[#00ff00] focus:outline-none"
              disabled={isPosting}
              maxLength={500}
            />
          </div>
          {newComment.trim() && (
            <div className="flex justify-between items-center">
              <Small className="text-gray-600 font-mono text-[10px]">
                {newComment.length}/500 • Stored permanently on Base
              </Small>
              <button
                type="submit"
                disabled={isPosting}
                className="px-4 py-1.5 rounded-lg bg-[#00ff00] text-black font-mono text-sm font-bold hover:bg-[#00dd00] disabled:opacity-50 transition-colors"
              >
                {isPosting ? "Posting..." : replyingTo ? "Reply ⛓️" : "Post ⛓️"}
              </button>
            </div>
          )}
        </form>
      ) : (
        <Card className="bg-[#0a0a0a] border border-[#00ff00]/20">
          <CardContent className="p-3 text-center">
            <Small className="text-gray-500 font-mono">Connect wallet to comment</Small>
          </CardContent>
        </Card>
      )}

      {/* Comments List (Threaded) - sorted by upvotes then timestamp */}
      {sortedComments.length === 0 && !isLoading ? (
        <Card className="bg-[#0a0a0a] border border-[#00ff00]/10">
          <CardContent className="p-4 text-center">
            <Small className="text-gray-500 font-mono">No comments yet. Be the first to comment onchain!</Small>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-2">
          {paginatedComments.map((comment) => (
            <ThreadedComment
              key={comment.id}
              comment={comment}
              depth={0}
              formatTimeAgo={formatTimeAgo}
              truncateAddress={truncateAddress}
              isMember={(addr: string) => !!memberLookup[addr.toLowerCase()]}
              onViewLibraryCard={handleViewLibraryCard}
              onViewFarcasterProfile={handleViewFarcasterProfile}
              onReply={handleReply}
              onUpvote={handleUpvoteClick}
              getUpvoteCount={getUpvoteCount}
              isUpvoting={isUpvotingComment}
              currentUserAddress={address}
              parentUpvotes={0}
            />
          ))}

          {/* Load more button */}
          {hasMoreComments && (
            <button
              onClick={() => setVisibleCount((prev) => prev + 20)}
              className="w-full py-3 rounded-lg bg-[#1a1a1a] border border-[#00ff00]/20 text-[#00ff00] font-mono text-sm hover:bg-[#00ff00]/10 transition-colors"
            >
              Load more comments ({sortedComments.length - visibleCount} remaining)
            </button>
          )}
        </div>
      )}

      {/* User Library Card Modal */}
      {selectedMember && (
        <UserLibraryCardModal
          isOpen={showLibraryCard}
          onClose={() => setShowLibraryCard(false)}
          member={selectedMember}
        />
      )}

      {/* Comment Upvote Modal */}
      <CommentUpvoteModal
        isOpen={!!upvoteModalComment}
        onClose={() => setUpvoteModalComment(null)}
        onUpvote={handleUpvoteSubmit}
        isUpvoting={isUpvotingComment}
        commenterName={
          upvoteModalComment?.username
            ? `@${upvoteModalComment.username}`
            : upvoteModalComment?.sender
            ? truncateAddress(upvoteModalComment.sender)
            : "Unknown"
        }
        currentUpvotes={upvoteModalComment ? getUpvoteCount(upvoteModalComment.id) : 0}
      />
    </div>
  );
}

// Threaded comment component - renders comment and its nested replies
interface ThreadedCommentProps {
  comment: OnchainComment;
  depth: number;
  formatTimeAgo: (ts: number) => string;
  truncateAddress: (addr: string) => string;
  isMember: (addr: string) => boolean;
  onViewLibraryCard: (comment: OnchainComment) => void;
  onViewFarcasterProfile: (username: string) => void;
  onReply: (comment: OnchainComment) => void;
  onUpvote: (commentId: string) => void;
  getUpvoteCount: (commentId: string) => number;
  isUpvoting: boolean;
  currentUserAddress?: string;
  parentUpvotes?: number; // Parent's upvote count to detect "hot replies"
}

function ThreadedComment({
  comment,
  depth,
  formatTimeAgo,
  truncateAddress,
  isMember,
  onViewLibraryCard,
  onViewFarcasterProfile,
  onReply,
  onUpvote,
  getUpvoteCount,
  isUpvoting,
  currentUserAddress,
  parentUpvotes = 0,
}: ThreadedCommentProps) {
  // Auto-collapse deep threads (depth 3+) by default
  const [isCollapsed, setIsCollapsed] = useState(depth >= 3);
  const hasReplies = comment.replies && comment.replies.length > 0;

  // Max depth for visual nesting (after this, no more indent)
  const maxDepth = 4;
  const effectiveDepth = Math.min(depth, maxDepth);
  const marginLeft = effectiveDepth > 0 ? `${effectiveDepth * 16}px` : "0";

  // Detect "hot reply" - a reply with significantly more upvotes than parent
  const upvoteCount = getUpvoteCount(comment.id);
  const isHotReply = depth > 0 && upvoteCount >= 3 && upvoteCount >= parentUpvotes * 2;

  const memberStatus = isMember(comment.sender);
  const isAgent = comment.isAgent;
  // Hot replies get a golden glow, agents get purple, members get green, others get gray
  const borderColor = isHotReply
    ? "border-yellow-500/50"
    : isAgent
    ? "border-[#B794F4]/30"
    : memberStatus
    ? "border-[#00ff00]/30"
    : "border-gray-700/30";
  const textColor = isAgent ? "text-[#B794F4]" : memberStatus ? "text-[#00ff00]" : "text-gray-400";
  const pfpBorderColor = isAgent ? "border-[#B794F4]/50" : memberStatus ? "border-[#00ff00]/50" : "border-gray-600/50";

  return (
    <div style={{ marginLeft }}>
      <Card className={`bg-[#0a0a0a] border ${borderColor}`}>
        <CardContent className="p-3">
          <div className="flex gap-2">
            {/* Collapse indicator for comments with replies */}
            {hasReplies && (
              <button
                onClick={() => setIsCollapsed(!isCollapsed)}
                className="w-4 h-4 flex items-center justify-center text-gray-500 hover:text-[#00ff00] transition-colors shrink-0 mt-1"
              >
                {isCollapsed ? "+" : "−"}
              </button>
            )}

            {/* PFP - tappable for members */}
            {memberStatus ? (
              <button
                onClick={() => onViewLibraryCard(comment)}
                className="shrink-0 focus:outline-none"
              >
                <img
                  src={comment.pfpUrl || `https://api.dicebear.com/7.x/identicon/svg?seed=${comment.sender}`}
                  alt={comment.username || "User"}
                  className={`w-6 h-6 rounded-full border ${pfpBorderColor} ${
                    isAgent ? "hover:border-[#B794F4]" : "hover:border-[#00ff00]"
                  } transition-colors`}
                />
              </button>
            ) : (
              <img
                src={comment.pfpUrl || `https://api.dicebear.com/7.x/identicon/svg?seed=${comment.sender}`}
                alt={comment.username || "User"}
                className={`w-6 h-6 rounded-full border ${pfpBorderColor} shrink-0`}
              />
            )}

            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 flex-wrap">
                {/* Username - tappable for members with Farcaster username */}
                {memberStatus && comment.username ? (
                  <button
                    onClick={() => onViewFarcasterProfile(comment.username!)}
                    className={`${textColor} font-mono font-medium text-sm hover:underline focus:outline-none`}
                  >
                    @{comment.username}
                  </button>
                ) : (
                  <Small className={`${textColor} font-mono font-medium`}>
                    {comment.username ? `@${comment.username}` : truncateAddress(comment.sender)}
                  </Small>
                )}
                {/* Hot reply badge */}
                {isHotReply && (
                  <span className="text-[8px] px-1 py-0.5 rounded bg-yellow-500/20 text-yellow-400 font-mono uppercase flex items-center gap-0.5">
                    <FlameIcon size={8} /> hot
                  </span>
                )}
                {/* Member badge - purple for agents */}
                {memberStatus && (
                  <span className={`text-[8px] px-1 py-0.5 rounded font-mono uppercase ${
                    isAgent
                      ? "bg-[#B794F4]/10 text-[#B794F4]"
                      : "bg-[#00ff00]/10 text-[#00ff00]"
                  }`}>
                    {isAgent ? "agent" : "member"}
                  </span>
                )}
                <Small className="text-gray-600 font-mono text-[10px]">
                  {formatTimeAgo(comment.timestamp)}
                </Small>
              </div>

              <P className="text-white font-mono text-sm mt-1 break-words">
                <LinkedText text={comment.text} />
              </P>

              {/* Action bar: Upvote, Reply, Basescan */}
              <div className="flex items-center gap-3 mt-2">
                {/* Upvote button */}
                <button
                  onClick={() => onUpvote(comment.id)}
                  disabled={isUpvoting || !currentUserAddress}
                  className="flex items-center gap-1 text-gray-500 hover:text-[#00ff00] transition-colors disabled:opacity-50 group"
                  title={`Upvote (~$${COMMENT_UPVOTE_COST_ETH.toFixed(4)} ETH)`}
                >
                  <span className="text-xs group-hover:scale-110 transition-transform">▲</span>
                  <span className="text-[10px] font-mono">{upvoteCount}</span>
                </button>

                {/* Reply button */}
                {currentUserAddress && (
                  <button
                    onClick={() => onReply(comment)}
                    className="text-[10px] font-mono text-gray-500 hover:text-[#00ff00] transition-colors"
                  >
                    Reply
                  </button>
                )}

                {/* Basescan link */}
                <a
                  href={`https://basescan.org/address/${comment.sender}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-[10px] font-mono text-gray-600 hover:text-[#00ff00] transition-colors"
                >
                  Basescan ↗
                </a>
              </div>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Nested replies */}
      {hasReplies && !isCollapsed && (
        <div className="mt-2 space-y-2">
          {comment.replies!.map((reply) => (
            <ThreadedComment
              key={reply.id}
              comment={reply}
              depth={depth + 1}
              formatTimeAgo={formatTimeAgo}
              truncateAddress={truncateAddress}
              isMember={isMember}
              onViewLibraryCard={onViewLibraryCard}
              onViewFarcasterProfile={onViewFarcasterProfile}
              onReply={onReply}
              onUpvote={onUpvote}
              getUpvoteCount={getUpvoteCount}
              isUpvoting={isUpvoting}
              currentUserAddress={currentUserAddress}
              parentUpvotes={upvoteCount}
            />
          ))}
        </div>
      )}

      {/* Collapsed indicator */}
      {hasReplies && isCollapsed && (
        <button
          onClick={() => setIsCollapsed(false)}
          className="ml-6 mt-1 text-[10px] font-mono text-gray-500 hover:text-[#00ff00] transition-colors"
        >
          Show {comment.replyCount} {comment.replyCount === 1 ? "reply" : "replies"} ▼
        </button>
      )}
    </div>
  );
}
src/features/app/components/connect-wallet-button.tsx
"use client";

import { useState } from "react";
import { useAccount, useConnect, useDisconnect } from "wagmi";
import { useAppMode } from "@/lib/app-mode";
import {
  setWalletPreference,
  clearWalletPreference,
} from "@/neynar-web-sdk/src/blockchain/app/neynar-wagmi-provider";

/**
 * Wallet option icons - Official logos
 */
const WalletIcons = {
  // MetaMask official fox logo
  metamask: (
    <svg viewBox="0 0 318.6 318.6" className="w-6 h-6">
      <path fill="#E2761B" stroke="#E2761B" strokeLinecap="round" strokeLinejoin="round" d="M274.1 35.5l-99.5 73.9L193 65.8z"/>
      <path fill="#E4761B" stroke="#E4761B" strokeLinecap="round" strokeLinejoin="round" d="M44.4 35.5l98.7 74.6-17.5-44.3zm193.9 171.3l-26.5 40.6 56.7 15.6 16.3-55.3zm-204.4.9L50.1 263l56.7-15.6-26.5-40.6z"/>
      <path fill="#E4761B" stroke="#E4761B" strokeLinecap="round" strokeLinejoin="round" d="M103.6 138.2l-15.8 23.9 56.3 2.5-2-60.5zm111.3 0l-39-34.8-1.3 61.2 56.2-2.5zM106.8 247.4l33.8-16.5-29.2-22.8zm71.1-16.5l33.9 16.5-4.7-39.3z"/>
      <path fill="#D7C1B3" stroke="#D7C1B3" strokeLinecap="round" strokeLinejoin="round" d="M211.8 247.4l-33.9-16.5 2.7 22.1-.3 9.3zm-105 0l31.5 14.9-.2-9.3 2.5-22.1z"/>
      <path fill="#233447" stroke="#233447" strokeLinecap="round" strokeLinejoin="round" d="M138.8 193.5l-28.2-8.3 19.9-9.1zm40.9 0l8.3-17.4 20 9.1z"/>
      <path fill="#CD6116" stroke="#CD6116" strokeLinecap="round" strokeLinejoin="round" d="M106.8 247.4l4.8-40.6-31.3.9zm100.2-40.6l4.8 40.6 26.5-39.7-31.3-.9zm23.8-44.7l-56.2 2.5 5.2 28.9 8.3-17.4 20 9.1zm-120.2 23.1l20-9.1 8.2 17.4 5.3-28.9-56.3-2.5z"/>
      <path fill="#E4751F" stroke="#E4751F" strokeLinecap="round" strokeLinejoin="round" d="M87.8 162.1l23.6 46-.8-22.9zm120.3 23.1l-1 22.9 23.7-46zm-64-20.6l-5.3 28.9 6.6 34.1 1.5-44.9zm30.5 0l-2.7 18 1.2 45 6.7-34.1z"/>
      <path fill="#F6851B" stroke="#F6851B" strokeLinecap="round" strokeLinejoin="round" d="M179.8 193.5l-6.7 34.1 4.8 3.3 29.2-22.8 1-22.9zm-69.2-8.3l.8 22.9 29.2 22.8 4.8-3.3-6.6-34.1z"/>
      <path fill="#C0AD9E" stroke="#C0AD9E" strokeLinecap="round" strokeLinejoin="round" d="M180.3 262.3l.3-9.3-2.5-2.2h-37.7l-2.3 2.2.2 9.3-31.5-14.9 11 9 22.3 15.5h38.3l22.4-15.5 11-9z"/>
      <path fill="#161616" stroke="#161616" strokeLinecap="round" strokeLinejoin="round" d="M177.9 230.9l-4.8-3.3h-27.7l-4.8 3.3-2.5 22.1 2.3-2.2h37.7l2.5 2.2z"/>
      <path fill="#763D16" stroke="#763D16" strokeLinecap="round" strokeLinejoin="round" d="M278.3 114.2l8.5-40.8-12.7-37.9-96.2 71.4 37 31.3 52.3 15.3 11.6-13.5-5-3.6 8-7.3-6.2-4.8 8-6.1zM31.8 73.4l8.5 40.8-5.4 4 8 6.1-6.1 4.8 8 7.3-5 3.6 11.5 13.5 52.3-15.3 37-31.3-96.2-71.4z"/>
      <path fill="#F6851B" stroke="#F6851B" strokeLinecap="round" strokeLinejoin="round" d="M267.2 153.5l-52.3-15.3 15.9 23.9-23.7 46 31.2-.4h46.5zm-163.6-15.3l-52.3 15.3-17.4 54.2h46.4l31.1.4-23.6-46zm71 26.4l3.3-57.7 15.2-41.1h-67.5l15 41.1 3.5 57.7 1.2 18.2.1 44.8h27.7l.2-44.8z"/>
    </svg>
  ),
  // Rainbow official logo - accurate recreation of their brand
  rainbow: (
    <svg viewBox="0 0 120 120" className="w-6 h-6">
      <defs>
        <linearGradient id="rainbow-bg" x1="0%" y1="0%" x2="100%" y2="100%">
          <stop offset="0%" stopColor="#174299"/>
          <stop offset="100%" stopColor="#001E59"/>
        </linearGradient>
      </defs>
      <rect width="120" height="120" rx="24" fill="url(#rainbow-bg)"/>
      {/* Rainbow arcs from outer to inner: red, orange, yellow, green, blue */}
      <path d="M20 94V68c0-26.51 21.49-48 48-48h26v12H68c-19.882 0-36 16.118-36 36v26H20z" fill="#FF6B6B"/>
      <path d="M32 94V68c0-19.882 16.118-36 36-36h26v12H68c-13.255 0-24 10.745-24 24v26H32z" fill="#FFD93D"/>
      <path d="M44 94V68c0-13.255 10.745-24 24-24h26v12H68c-6.627 0-12 5.373-12 12v26H44z" fill="#6BCB77"/>
      <path d="M56 94V68c0-6.627 5.373-12 12-12h26v12H68v26H56z" fill="#4D96FF"/>
    </svg>
  ),
  // Coinbase Wallet official logo
  coinbase: (
    <svg viewBox="0 0 1024 1024" className="w-6 h-6">
      <circle cx="512" cy="512" r="512" fill="#0052FF"/>
      <path fillRule="evenodd" clipRule="evenodd" d="M152 512c0 198.823 161.177 360 360 360s360-161.177 360-360-161.177-360-360-360-360 161.177-360 360zm268-116c-13.255 0-24 10.745-24 24v192c0 13.255 10.745 24 24 24h184c13.255 0 24-10.745 24-24V420c0-13.255-10.745-24-24-24H420z" fill="#fff"/>
    </svg>
  ),
};

type WalletOption = {
  id: string;
  name: string;
  description: string;
  icon: React.ReactNode;
  connectorId: string;
};

const WALLET_OPTIONS: WalletOption[] = [
  {
    id: "metamask",
    name: "MetaMask",
    description: "Connect with MetaMask browser extension",
    icon: WalletIcons.metamask,
    // EIP-6963 connector ID from MetaMask
    connectorId: "io.metamask",
  },
  {
    id: "rainbow",
    name: "Rainbow",
    description: "Connect with Rainbow wallet",
    icon: WalletIcons.rainbow,
    // EIP-6963 connector ID from Rainbow
    connectorId: "me.rainbow",
  },
  {
    id: "coinbase",
    name: "Coinbase Wallet",
    description: "Connect with Coinbase Wallet or Smart Wallet",
    icon: WalletIcons.coinbase,
    // EIP-6963 connector ID for Coinbase Wallet extension
    // Note: This may also appear as "coinbaseWalletSDK" from the SDK
    connectorId: "com.coinbase.wallet",
  },
];

/**
 * Connect Wallet Button with Multi-Wallet Selector
 *
 * Shows a modal with three wallet options:
 * - MetaMask (browser extension)
 * - Rainbow (browser extension or mobile)
 * - Coinbase Wallet (including Smart Wallet)
 */
export function ConnectWalletButton() {
  const { address, isConnected } = useAccount();
  const { connect, connectors, isPending } = useConnect();
  const { disconnect } = useDisconnect();
  const appMode = useAppMode();
  const [showModal, setShowModal] = useState(false);
  const [connectingWallet, setConnectingWallet] = useState<string | null>(null);

  // Don't show in Farcaster mode - wallet auto-connects via SDK
  if (appMode === "farcaster") return null;

  // Still detecting mode - don't flash the button
  if (appMode === "detecting") return null;

  // Handle disconnect - also clear wallet preference
  const handleDisconnect = () => {
    clearWalletPreference();
    disconnect();
  };

  // Connected state - show truncated address with disconnect option
  if (isConnected && address) {
    const truncatedAddress = `${address.slice(0, 6)}...${address.slice(-4)}`;

    return (
      <div className="flex items-center gap-2">
        <span className="text-[10px] font-mono text-[#00ff00]/70">
          {truncatedAddress}
        </span>
        <button
          onClick={handleDisconnect}
          className="px-3 py-1.5 rounded-lg bg-[#1a1a1a] border border-[#333] text-gray-400 text-xs font-mono hover:border-red-500/50 hover:text-red-400 transition-all"
        >
          Disconnect
        </button>
      </div>
    );
  }

  const handleWalletSelect = (option: WalletOption) => {
    setConnectingWallet(option.id);

    // Find the connector - EIP-6963 discovered connectors use their RDNS as ID
    // e.g., MetaMask uses "io.metamask", Rainbow uses "me.rainbow"
    let connector: typeof connectors[number] | undefined;

    // Log available connectors for debugging
    console.log(`[ConnectWallet] Looking for ${option.name}`, {
      requestedId: option.connectorId,
      availableConnectors: connectors.map(c => ({ id: c.id, name: c.name, type: c.type })),
    });

    // Try exact match first (this works for EIP-6963 connectors)
    connector = connectors.find(c => c.id === option.connectorId);

    // Fallback: partial match (connector IDs might have slight variations)
    if (!connector) {
      connector = connectors.find(c =>
        c.id.toLowerCase().includes(option.connectorId.toLowerCase()) ||
        option.connectorId.toLowerCase().includes(c.id.toLowerCase()) ||
        c.name?.toLowerCase() === option.name.toLowerCase()
      );
    }

    // Special handling for Coinbase - it might use different IDs
    if (!connector && option.id === "coinbase") {
      connector = connectors.find(c =>
        c.id === "coinbaseWalletSDK" ||
        c.id.includes("coinbase") ||
        c.name?.toLowerCase().includes("coinbase")
      );
      if (connector) {
        console.log(`[ConnectWallet] Found Coinbase connector with ID: ${connector.id}`);
      }
    }

    // Special case: if looking for MetaMask/Rainbow but only "injected" connector exists
    // This can happen if the browser only has one injected wallet
    if (!connector && (option.id === "metamask" || option.id === "rainbow")) {
      // IMPORTANT: Don't fall back to generic "injected" if it's Coinbase
      // This prevents Coinbase from hijacking MetaMask/Rainbow connections
      const injectedConnector = connectors.find(c => c.id === "injected");
      if (injectedConnector) {
        // Check if the injected provider is actually the wallet we want
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const win = window as any;

        // EIP-6963 providers array (modern multi-wallet support)
        const providers = win.ethereum?.providers || [];
        const hasMultipleProviders = providers.length > 0;

        if (hasMultipleProviders) {
          // Multiple wallets detected - check if our target wallet is in the list
          const targetProvider = providers.find((p: { isMetaMask?: boolean; isRainbow?: boolean }) =>
            option.id === "metamask" ? p.isMetaMask : p.isRainbow
          );

          if (targetProvider) {
            // Found our wallet in the providers array
            connector = injectedConnector;
            console.log(`[ConnectWallet] Found ${option.name} in EIP-6963 providers array`);
          } else {
            console.warn(`[ConnectWallet] ${option.name} not found in multi-provider environment`);
          }
        } else {
          // Single provider - check if it's the right one
          const provider = win.ethereum;
          const isCoinbaseHijack = provider?.isCoinbaseWallet && !provider?.isMetaMask && !provider?.isRainbow;

          if (isCoinbaseHijack) {
            console.warn(`[ConnectWallet] Coinbase has hijacked window.ethereum, cannot use generic injected for ${option.name}`);
          } else {
            connector = injectedConnector;
            console.log(`[ConnectWallet] Falling back to generic injected connector for ${option.name}`);
          }
        }
      }
    }

    if (connector) {
      console.log(`[ConnectWallet] Connecting with connector: ${connector.id} (${connector.name})`);

      connect(
        { connector },
        {
          onSuccess: (data) => {
            // Save the user's wallet preference AND address so we reconnect to the same one
            const connectedAddress = data.accounts?.[0];

            // Use the ACTUAL connector ID we connected with (important for EIP-6963)
            const actualConnectorId = connector?.id || option.connectorId;
            setWalletPreference(actualConnectorId, connectedAddress);
            console.log(`[ConnectWallet] Connected successfully!`, {
              connector: actualConnectorId,
              address: connectedAddress ? `${connectedAddress.slice(0, 6)}...${connectedAddress.slice(-4)}` : "unknown",
            });
            setShowModal(false);
            setConnectingWallet(null);
          },
          onError: (error) => {
            console.error(`[ConnectWallet] Connection error:`, error);
            setConnectingWallet(null);
          },
        }
      );
    } else {
      // Wallet not found - show user-friendly message
      console.warn(`[ConnectWallet] Connector not found for ${option.name}`);
      console.warn(`[ConnectWallet] Make sure ${option.name} extension is installed and enabled`);
      alert(`${option.name} not detected. Please make sure the ${option.name} browser extension is installed and enabled.`);
      setConnectingWallet(null);
    }
  };

  return (
    <>
      <button
        onClick={() => setShowModal(true)}
        disabled={isPending}
        className={`px-4 py-2 rounded-lg font-mono text-sm transition-all ${
          isPending
            ? "bg-[#00ff00]/20 text-[#00ff00]/50 border border-[#00ff00]/30"
            : "bg-[#00ff00] text-black font-medium hover:bg-[#00ff00]/90 hover:shadow-[0_0_20px_rgba(0,255,0,0.3)]"
        }`}
      >
        {isPending ? "Connecting..." : "Connect Wallet"}
      </button>

      {/* Wallet Selection Modal */}
      {showModal && (
        <div
          className="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 flex items-center justify-center p-4"
          onClick={() => setShowModal(false)}
        >
          <div
            className="bg-[#0a0a0a] border-2 border-[#00ff00]/30 rounded-xl w-full max-w-sm overflow-hidden"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Header */}
            <div className="px-4 py-3 border-b border-[#00ff00]/20 flex items-center justify-between">
              <h3 className="text-[#00ff00] font-mono font-medium">Connect Wallet</h3>
              <button
                onClick={() => setShowModal(false)}
                className="text-gray-500 hover:text-[#00ff00] transition-colors text-xl leading-none"
              >
                ×
              </button>
            </div>

            {/* Wallet Options */}
            <div className="p-3 space-y-2">
              {WALLET_OPTIONS.map((option) => {
                const isConnecting = connectingWallet === option.id;

                return (
                  <button
                    key={option.id}
                    onClick={() => handleWalletSelect(option)}
                    disabled={connectingWallet !== null}
                    className={`w-full p-3 rounded-lg border transition-all flex items-center gap-3 text-left ${
                      isConnecting
                        ? "bg-[#00ff00]/10 border-[#00ff00]/50"
                        : "bg-[#111] border-[#222] hover:border-[#00ff00]/50 hover:bg-[#00ff00]/5"
                    } ${connectingWallet !== null && !isConnecting ? "opacity-50" : ""}`}
                  >
                    {/* Wallet Icon */}
                    <div className="w-10 h-10 rounded-lg bg-[#1a1a1a] flex items-center justify-center shrink-0">
                      {option.icon}
                    </div>

                    {/* Wallet Info */}
                    <div className="flex-1 min-w-0">
                      <div className="text-[#00ff00] font-mono text-sm font-medium">
                        {option.name}
                      </div>
                      <div className="text-gray-500 text-xs truncate">
                        {isConnecting ? "Connecting..." : option.description}
                      </div>
                    </div>

                    {/* Arrow or Spinner */}
                    <div className="text-gray-500 shrink-0">
                      {isConnecting ? (
                        <div className="w-4 h-4 border-2 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
                      ) : (
                        <span className="text-sm">→</span>
                      )}
                    </div>
                  </button>
                );
              })}
            </div>

            {/* Footer */}
            <div className="px-4 py-3 border-t border-[#00ff00]/10">
              <p className="text-gray-600 text-[10px] font-mono text-center">
                By connecting, you agree to the Terms of Service
              </p>
            </div>
          </div>
        </div>
      )}
    </>
  );
}
src/features/app/components/connectivity-banner.tsx
"use client";

import { useConnectivity } from "@/hooks/use-connectivity";

/**
 * Banner that shows when user loses internet connection
 * Auto-hides when connection is restored
 */
export function ConnectivityBanner() {
  const { isOnline, wasOffline } = useConnectivity();

  // Show "back online" briefly after reconnecting
  if (wasOffline && isOnline) {
    return (
      <div className="fixed top-0 left-0 right-0 z-[9999] bg-green-900/95 border-b-2 border-green-500/50 p-2">
        <div className="flex items-center justify-center gap-2">
          <span className="text-green-400">✓</span>
          <span className="text-white font-mono text-sm">Back online</span>
        </div>
      </div>
    );
  }

  // Show offline warning
  if (!isOnline) {
    return (
      <div className="fixed top-0 left-0 right-0 z-[9999] bg-yellow-900/95 border-b-2 border-yellow-500/50 p-3">
        <div className="flex items-center justify-center gap-3">
          <span className="text-yellow-400 text-lg">📡</span>
          <div className="text-center">
            <span className="text-white font-mono text-sm block">No internet connection</span>
            <span className="text-yellow-400/70 font-mono text-[10px]">
              Some features may not work until you reconnect
            </span>
          </div>
        </div>
      </div>
    );
  }

  return null;
}
src/features/app/components/cover-backfill.tsx
"use client";

import { useEffect, useRef, useCallback } from "react";
import { usePdfCover } from "@/hooks/use-pdf-cover";
import { useEpubCover } from "@/hooks/use-epub-cover";
import { useCoverUpload } from "@/hooks/use-cover-upload";
import { getCdnUrl, BASE_CHAIN_ID } from "@/lib/net-protocol";

interface BackfillEntry {
  contentKey: string;
  title: string;
  operator: string;
  storageType: string;
  fileName?: string; // Original filename for correct CDN URL format
  cdnUrl?: string; // Stored CDN URL (preferred)
  hasDataUrlCover?: boolean; // If true, entry has a base64 cover that needs to be uploaded to hosted storage
}

interface CoverBackfillProps {
  onComplete?: () => void;
}

export function CoverBackfill({ onComplete }: CoverBackfillProps) {
  const { extractCover: extractPdfCover } = usePdfCover();
  const { extractCover: extractEpubCover } = useEpubCover();
  const { uploadCover } = useCoverUpload();

  // Ref to track if we've already started processing to prevent double-runs
  const hasStartedRef = useRef(false);

  // Process a single entry
  const processEntry = useCallback(async (entry: BackfillEntry): Promise<boolean> => {
    try {
      console.log(`[CoverBackfill] Processing: ${entry.title} (storageType: ${entry.storageType}, hasDataUrlCover: ${entry.hasDataUrlCover})`);

      let dataUrlToUpload: string | null = null;

      // If entry already has a base64 data URL cover, fetch it and upload to hosted storage
      if (entry.hasDataUrlCover) {
        console.log(`[CoverBackfill] Entry has existing base64 cover, fetching to convert to hosted URL...`);
        try {
          // Fetch the existing cover data URL from the discovery entry
          const coverArtRes = await fetch(`/api/cover-art/${encodeURIComponent(entry.contentKey)}`);
          const coverArtData = await coverArtRes.json();

          if (coverArtData.found && coverArtData.coverUrl && coverArtData.coverUrl.startsWith("data:")) {
            dataUrlToUpload = coverArtData.coverUrl;
            console.log(`[CoverBackfill] Got existing base64 cover (${Math.round(coverArtData.coverUrl.length / 1024)}KB)`);
          } else {
            console.log(`[CoverBackfill] Cover not found or not a data URL, will re-extract`);
          }
        } catch (err) {
          console.error(`[CoverBackfill] Failed to fetch existing cover:`, err);
        }
      }

      // If we don't have a data URL yet, extract it from the file
      if (!dataUrlToUpload) {
        // Get CDN URL for this content
        // Prefer: stored cdnUrl > /storage/load/ with fileName > /storage/raw/ fallback
        const cdnUrl = entry.cdnUrl || getCdnUrl(BASE_CHAIN_ID, entry.operator, entry.contentKey, entry.storageType as "regular" | "chunked" | "xml", entry.fileName);

        // Extract cover based on storage type
        // XML storage type = EPUB files, regular/chunked = PDF files
        const isEpub = entry.storageType === "xml";
        const cover = isEpub
          ? await extractEpubCover(cdnUrl, 300)
          : await extractPdfCover(cdnUrl, 300);

        if (cover) {
          dataUrlToUpload = cover.dataUrl;
        }
      }

      if (dataUrlToUpload) {
        // Upload the cover to get a hosted URL (not base64)
        // This is critical for share images to work
        const uploadResult = await uploadCover(dataUrlToUpload, entry.contentKey);

        if (!uploadResult.success || !uploadResult.url) {
          console.warn(`[CoverBackfill] Failed to upload cover for ${entry.title}:`, uploadResult.error);
          // Mark as failed so we don't keep retrying
          await fetch("/api/backfill-covers", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({
              contentKey: entry.contentKey,
              operator: entry.operator,
              failed: true,
            }),
          });
          return false;
        }

        // Save the hosted URL to backend
        const res = await fetch("/api/backfill-covers", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            contentKey: entry.contentKey,
            operator: entry.operator,
            coverUrl: uploadResult.url, // Hosted URL, not base64
          }),
        });

        const result = await res.json();
        console.log(`[CoverBackfill] Saved cover for ${entry.title}:`, result.success, uploadResult.url);
        return result.success;
      } else {
        // Mark as failed so we don't retry
        await fetch("/api/backfill-covers", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            contentKey: entry.contentKey,
            operator: entry.operator,
            failed: true,
          }),
        });
        console.log(`[CoverBackfill] No cover data available for ${entry.title} (extraction failed or no existing cover)`);
        return false;
      }
    } catch (error) {
      console.error(`[CoverBackfill] Failed for ${entry.title}:`, error);
      // Mark as failed
      try {
        await fetch("/api/backfill-covers", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            contentKey: entry.contentKey,
            operator: entry.operator,
            failed: true,
          }),
        });
      } catch {
        // Ignore error marking failure
      }
      return false;
    }
  }, [extractPdfCover, extractEpubCover, uploadCover]);

  // Fetch entries needing covers on mount and auto-start processing
  useEffect(() => {
    async function fetchAndProcess() {
      // Prevent double-runs
      if (hasStartedRef.current) return;
      hasStartedRef.current = true;

      try {
        const res = await fetch("/api/backfill-covers?action=list");
        const data = await res.json();

        if (data.success && data.entries && data.entries.length > 0) {
          const dataUrlCount = data.entries.filter((e: BackfillEntry) => e.hasDataUrlCover).length;
          const noCoversCount = data.entries.length - dataUrlCount;
          console.log(`[CoverBackfill] Found ${data.entries.length} entries needing processing (${dataUrlCount} with base64 covers to convert, ${noCoversCount} without covers), auto-processing...`);

          let successCount = 0;
          for (const entry of data.entries) {
            const success = await processEntry(entry);
            if (success) successCount++;
            // Small delay between extractions
            await new Promise(resolve => setTimeout(resolve, 300));
          }

          // Refresh the browse tab if any succeeded
          if (successCount > 0) {
            onComplete?.();
          }
        }
      } catch (e) {
        console.error("[CoverBackfill] Failed to fetch entries:", e);
      }
    }

    fetchAndProcess();
  }, [processEntry, onComplete]);

  // Fully silent - no UI
  return null;
}
src/features/app/components/cover-image.tsx
"use client";

import { useState, useCallback, useEffect } from "react";
import { normalizeCoverUrl } from "@/lib/cover-url-utils";

interface CoverImageProps {
  src: string | undefined;
  alt: string;
  className?: string;
  fallbackClassName?: string;
  fallbackLogoSize?: string;
}

/**
 * Smart cover image component that gracefully handles load failures.
 * Falls back to the app logo when image fails to load (e.g., 404 from /api/covers/).
 */
export function CoverImage({
  src,
  alt,
  className = "w-full h-full object-cover",
  fallbackClassName = "w-full h-full flex items-center justify-center",
  fallbackLogoSize = "w-12 h-12",
}: CoverImageProps) {
  const [hasError, setHasError] = useState(false);

  // Reset error state when src changes
  useEffect(() => {
    setHasError(false);
  }, [src]);

  const handleError = useCallback(() => {
    setHasError(true);
  }, []);

  // If no source or error occurred, show fallback
  if (!src || hasError) {
    return (
      <div className={fallbackClassName}>
        <img
          src="/app-logo.png"
          alt="Net Library"
          className={`${fallbackLogoSize} object-contain opacity-50`}
        />
      </div>
    );
  }

  return (
    <img
      src={normalizeCoverUrl(src)}
      alt={alt}
      className={className}
      onError={handleError}
    />
  );
}
src/features/app/components/create-grid-modal.tsx
"use client";

import { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { useAccount } from "wagmi";
import { useFarcasterLaunchParams } from "@/neynar-farcaster-sdk/mini";
import { useGrids } from "@/hooks/use-grids";
import { GRID_UNLOCK_PRICE_USD, GRID_FREE_MAX_SIZE } from "@/lib/net-protocol";
import type { GridVisibility } from "@/lib/net-protocol";
import { GridUnlockModal } from "./grid-unlock-modal";
import { useStoragePassModal } from "./unlimited-storage-pass-modal";

interface CreateGridModalProps {
  isOpen: boolean;
  onClose: () => void;
  onCreated?: (gridId: string) => void;
}

// Free tier options only
const FREE_GRID_OPTIONS = [
  { size: 2, label: "2×2", cells: 4 },
  { size: 3, label: "3×3", cells: 9 },
  { size: 4, label: "4×4", cells: 16 },
  { size: 5, label: "5×5", cells: 25 },
];

// Custom grid sizes (require payment or Unlimited Pass)
const CUSTOM_GRID_OPTIONS = [
  { size: 6, label: "6×6", cells: 36 },
  { size: 8, label: "8×8", cells: 64 },
  { size: 10, label: "10×10", cells: 100 },
];

export function CreateGridModal({ isOpen, onClose, onCreated }: CreateGridModalProps) {
  const { address } = useAccount();
  const farcasterLaunchParams = useFarcasterLaunchParams();
  const { createGrid } = useGrids({ autoFetch: false });
  const { openStoragePassModal } = useStoragePassModal();

  const [step, setStep] = useState<"size" | "custom" | "custom-input" | "details">("size");
  const [customSizeInput, setCustomSizeInput] = useState("");
  const [selectedSize, setSelectedSize] = useState<number | null>(null);
  const [name, setName] = useState("");
  const [subtitle, setSubtitle] = useState("");
  const [description, setDescription] = useState("");
  const [visibility, setVisibility] = useState<GridVisibility>("public");
  const [isCreating, setIsCreating] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Unlimited Pass state
  const [hasUnlimitedPass, setHasUnlimitedPass] = useState(false);
  const [showUnlockModal, setShowUnlockModal] = useState(false);
  const [pendingSize, setPendingSize] = useState<number | null>(null);

  // Check Unlimited Pass status when modal opens
  useEffect(() => {
    async function checkPass() {
      if (!address || !isOpen) return;
      try {
        const response = await fetch(`/api/membership/grid-pass?address=${address}`);
        const data = await response.json();
        setHasUnlimitedPass(data.hasUnlimitedPass || false);
      } catch (err) {
        console.error("Failed to check pass:", err);
      }
    }
    checkPass();
  }, [isOpen, address]);

  // Use portal to render modal at document root (avoids overflow clipping from parent containers)
  const [mounted, setMounted] = useState(false);
  useEffect(() => {
    setMounted(true);
  }, []);

  if (!isOpen || !mounted) return null;

  const handleFreeSelect = (size: number) => {
    setSelectedSize(size);
    setStep("details");
  };

  const handleCustomSelect = (size: number) => {
    // If user has Unlimited Pass, go straight to details
    if (hasUnlimitedPass) {
      setSelectedSize(size);
      setStep("details");
      return;
    }
    // Otherwise, show unlock modal for this specific grid
    setPendingSize(size);
    setShowUnlockModal(true);
  };

  const handleUnlockSuccess = () => {
    setShowUnlockModal(false);
    // Now proceed with the pending size selection
    if (pendingSize) {
      setSelectedSize(pendingSize);
      setStep("details");
      setPendingSize(null);
    }
  };

  const handleBack = () => {
    if (step === "details") {
      // Go back to custom-input if they typed a custom size, otherwise custom presets
      if (selectedSize && ![6, 8, 10].includes(selectedSize) && selectedSize > GRID_FREE_MAX_SIZE) {
        setStep("custom-input");
      } else if (selectedSize && selectedSize > GRID_FREE_MAX_SIZE) {
        setStep("custom");
      } else {
        setStep("size");
      }
    } else if (step === "custom-input") {
      setStep("custom");
    } else if (step === "custom") {
      setStep("size");
    }
    setError(null);
  };

  const handleCustomSizeSubmit = () => {
    const size = parseInt(customSizeInput, 10);
    if (isNaN(size) || size < 6 || size > 100) {
      setError("Please enter a size between 6 and 100");
      return;
    }
    handleCustomSelect(size);
  };

  const handleCreate = async () => {
    if (!address || !selectedSize || !name.trim()) return;

    setIsCreating(true);
    setError(null);

    try {
      const fidString = farcasterLaunchParams?.get('fid');
      const grid = await createGrid({
        name: name.trim(),
        subtitle: subtitle.trim() || undefined,
        description: description.trim() || undefined,
        size: selectedSize,
        visibility,
        creator: address,
        creatorFid: fidString ? parseInt(fidString, 10) : undefined,
      });

      if (grid) {
        onCreated?.(grid.id);
        handleClose();
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to create grid");
    } finally {
      setIsCreating(false);
    }
  };

  const handleClose = () => {
    setStep("size");
    setSelectedSize(null);
    setCustomSizeInput("");
    setName("");
    setSubtitle("");
    setDescription("");
    setVisibility("public");
    setError(null);
    onClose();
  };

  const modalContent = (
    <div className="fixed inset-0 z-[9999] flex items-start justify-center p-3 sm:p-4 pt-16 sm:pt-20 pb-20 sm:pb-24 bg-black/80 overflow-y-auto">
      <div className="w-full max-w-[calc(100%-1.5rem)] sm:max-w-sm md:max-w-md bg-[#0a0a0a] border border-[#1a1a1a] rounded-xl sm:rounded-2xl overflow-hidden max-h-[80vh] sm:max-h-[75vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center p-3 sm:p-4 border-b border-[#1a1a1a] shrink-0">
          <div className="flex items-center gap-2">
            {(step === "custom" || step === "custom-input" || step === "details") && (
              <button
                onClick={handleBack}
                className="w-10 h-10 sm:w-8 sm:h-8 rounded-lg bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white transition-colors"
                aria-label="Go back"
              >
                ←
              </button>
            )}
            <h2 className="text-[#00ff00] font-mono text-base sm:text-lg">
              {step === "size" && "New Grid"}
              {step === "custom" && "Custom Grid"}
              {step === "custom-input" && "Choose Size"}
              {step === "details" && "Grid Details"}
            </h2>
          </div>
        </div>

        {/* Content - scrollable with responsive padding */}
        <div className="p-3 sm:p-4 overflow-y-auto flex-1">
          {step === "size" && (
            <FreeSizeSelector
              onSelect={handleFreeSelect}
              onCustom={() => setStep("custom")}
            />
          )}
          {step === "custom" && (
            <CustomSizeSelector
              onSelect={handleCustomSelect}
              onChooseOwn={() => setStep("custom-input")}
              hasUnlimitedPass={hasUnlimitedPass}
              onOpenStoragePass={openStoragePassModal}
            />
          )}
          {step === "custom-input" && (
            <CustomSizeInput
              value={customSizeInput}
              onChange={setCustomSizeInput}
              hasUnlimitedPass={hasUnlimitedPass}
              error={error}
              onOpenStoragePass={openStoragePassModal}
            />
          )}
          {step === "details" && (
            <DetailsForm
              name={name}
              onNameChange={setName}
              subtitle={subtitle}
              onSubtitleChange={setSubtitle}
              description={description}
              onDescriptionChange={setDescription}
              visibility={visibility}
              onVisibilityChange={setVisibility}
              selectedSize={selectedSize!}
              error={error}
            />
          )}
        </div>

        {/* Footer - responsive padding and touch targets */}
        <div className="p-3 sm:p-4 border-t border-[#1a1a1a] shrink-0">
          {step === "details" && (
            <button
              onClick={handleCreate}
              disabled={!name.trim() || isCreating}
              className="w-full py-3.5 sm:py-3 rounded-lg font-mono text-sm bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/20 active:bg-[#00ff00]/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed min-h-[48px] sm:min-h-0"
            >
              {isCreating ? "Creating..." : "Create Grid"}
            </button>
          )}
          {step === "custom-input" && (
            <button
              onClick={handleCustomSizeSubmit}
              disabled={!customSizeInput.trim()}
              className="w-full py-3.5 sm:py-3 rounded-lg font-mono text-sm bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/20 active:bg-[#00ff00]/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed min-h-[48px] sm:min-h-0"
            >
              Continue
            </button>
          )}
          {(step === "size" || step === "custom") && (
            <button
              onClick={handleClose}
              className="w-full py-3.5 sm:py-3 rounded-lg font-mono text-sm bg-[#1a1a1a] text-gray-400 hover:text-white active:bg-[#2a2a2a] transition-colors min-h-[48px] sm:min-h-0"
            >
              Cancel
            </button>
          )}
        </div>
      </div>

      {/* Grid Unlock Modal */}
      <GridUnlockModal
        isOpen={showUnlockModal}
        onClose={() => {
          setShowUnlockModal(false);
          setPendingSize(null);
        }}
        onSuccess={handleUnlockSuccess}
        gridSize={pendingSize || 6}
      />
    </div>
  );

  return createPortal(modalContent, document.body);
}

function FreeSizeSelector({ onSelect, onCustom }: { onSelect: (size: number) => void; onCustom: () => void }) {
  return (
    <div className="space-y-3">
      <p className="text-gray-400 font-mono text-sm mb-4">
        Choose a size for your grid
      </p>

      {/* Free options */}
      <div className="space-y-2">
        {FREE_GRID_OPTIONS.map((option) => (
          <button
            key={option.size}
            onClick={() => onSelect(option.size)}
            className="w-full p-3 rounded-xl bg-black border border-[#1a1a1a] hover:border-[#00ff00]/30 transition-all text-left group flex items-center justify-between"
          >
            <div className="flex items-center gap-3">
              <GridSizePreview size={option.size} />
              <div>
                <span className="text-[#00ff00] font-mono text-lg">{option.label}</span>
                <p className="text-gray-500 font-mono text-xs">{option.cells} cells</p>
              </div>
            </div>
            <span className="text-gray-500 font-mono text-xs">Free</span>
          </button>
        ))}
      </div>

      {/* Custom grid option */}
      <button
        onClick={onCustom}
        className="w-full p-3 rounded-xl bg-black border border-[#1a1a1a] hover:border-yellow-500/30 transition-all text-left group flex items-center justify-between mt-4"
      >
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded bg-yellow-500/10 border border-yellow-500/20 flex items-center justify-center">
            <span className="text-yellow-400 text-lg">+</span>
          </div>
          <div>
            <span className="text-yellow-400 font-mono">Custom Grid</span>
            <p className="text-gray-500 font-mono text-xs">6×6 and larger</p>
          </div>
        </div>
        <span className="text-yellow-400 font-mono text-xs">${GRID_UNLOCK_PRICE_USD}+</span>
      </button>
    </div>
  );
}

function CustomSizeSelector({ onSelect, onChooseOwn, hasUnlimitedPass, onOpenStoragePass }: { onSelect: (size: number) => void; onChooseOwn: () => void; hasUnlimitedPass: boolean; onOpenStoragePass: () => void }) {
  return (
    <div className="space-y-3">
      {/* Info banner */}
      <div className="p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20">
        <p className="text-yellow-400 font-mono text-sm">
          {hasUnlimitedPass
            ? "✓ You have Unlimited Pass - all unlocked sizes included!"
            : `Unlocked grids (6×6+) cost $${GRID_UNLOCK_PRICE_USD} each`
          }
        </p>
        {!hasUnlimitedPass && (
          <p className="text-gray-500 font-mono text-xs mt-1">
            Planning to create multiple unlocked grids?{" "}
            <button
              onClick={onOpenStoragePass}
              className="text-[#00ff00] underline hover:text-[#00ff00]/80 transition-colors"
            >
              Get the Unlimited Pass
            </button>
            {" "}for unlimited unlocked grids + unlimited items in stacks.
          </p>
        )}
      </div>

      {/* Custom size options */}
      <div className="space-y-2">
        {CUSTOM_GRID_OPTIONS.map((option) => (
          <button
            key={option.size}
            onClick={() => onSelect(option.size)}
            className="w-full p-3 rounded-xl bg-black border border-[#1a1a1a] hover:border-[#00ff00]/30 transition-all text-left group flex items-center justify-between"
          >
            <div className="flex items-center gap-3">
              <GridSizePreview size={option.size} />
              <div>
                <span className="text-[#00ff00] font-mono text-lg">{option.label}</span>
                <p className="text-gray-500 font-mono text-xs">{option.cells} cells</p>
              </div>
            </div>
            {hasUnlimitedPass ? (
              <span className="text-[#00ff00] font-mono text-xs">Included</span>
            ) : (
              <span className="text-yellow-400 font-mono text-xs">${GRID_UNLOCK_PRICE_USD}</span>
            )}
          </button>
        ))}

        {/* Choose my own size button */}
        <button
          onClick={onChooseOwn}
          className="w-full p-3 rounded-xl bg-black border border-[#1a1a1a] hover:border-[#00ff00]/30 transition-all text-left group flex items-center justify-between mt-4"
        >
          <div className="flex items-center gap-3">
            <div className="w-10 h-10 rounded bg-[#00ff00]/10 border border-[#00ff00]/20 flex items-center justify-center">
              <span className="text-[#00ff00] font-mono text-lg">?</span>
            </div>
            <div>
              <span className="text-[#00ff00] font-mono">Choose my own size</span>
              <p className="text-gray-500 font-mono text-xs">Any size from 6×6 to 100×100</p>
            </div>
          </div>
        </button>
      </div>
    </div>
  );
}

function CustomSizeInput({ value, onChange, hasUnlimitedPass, error, onOpenStoragePass }: { value: string; onChange: (v: string) => void; hasUnlimitedPass: boolean; error: string | null; onOpenStoragePass: () => void }) {
  const parsedSize = parseInt(value, 10);
  const isValidSize = !isNaN(parsedSize) && parsedSize >= 6 && parsedSize <= 100;
  const cells = isValidSize ? parsedSize * parsedSize : 0;

  return (
    <div className="space-y-4">
      {/* Info banner */}
      <div className="p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/20">
        <p className="text-yellow-400 font-mono text-sm">
          {hasUnlimitedPass
            ? "✓ You have Unlimited Pass - all unlocked sizes included!"
            : `Unlocked grids (6×6+) cost $${GRID_UNLOCK_PRICE_USD} each`
          }
        </p>
        {!hasUnlimitedPass && (
          <button
            onClick={onOpenStoragePass}
            className="text-[#00ff00] font-mono text-xs mt-1 underline hover:text-[#00ff00]/80 transition-colors"
          >
            Get Unlimited Pass →
          </button>
        )}
      </div>

      {/* Size input */}
      <div>
        <label className="block text-gray-400 font-mono text-sm mb-2">
          Grid Size (6-100)
        </label>
        <div className="flex items-center gap-3">
          <input
            type="number"
            min="6"
            max="100"
            value={value}
            onChange={(e) => onChange(e.target.value)}
            placeholder="Enter size..."
            className="flex-1 px-4 py-3 rounded-lg bg-black border border-[#1a1a1a] text-white font-mono text-base placeholder:text-gray-600 focus:border-[#00ff00]/30 focus:outline-none transition-colors text-center"
          />
          <span className="text-gray-400 font-mono text-lg">×</span>
          <div className="flex-1 px-4 py-3 rounded-lg bg-black border border-[#1a1a1a] text-white font-mono text-lg text-center">
            {value || "?"}
          </div>
        </div>
      </div>

      {/* Preview */}
      {isValidSize && (
        <div className="p-3 rounded-lg bg-black border border-[#1a1a1a]">
          <div className="flex items-center justify-between">
            <span className="text-gray-400 font-mono text-sm">Grid size</span>
            <span className="text-[#00ff00] font-mono">{parsedSize}×{parsedSize}</span>
          </div>
          <div className="flex items-center justify-between mt-1">
            <span className="text-gray-400 font-mono text-sm">Total cells</span>
            <span className="text-[#00ff00] font-mono">{cells.toLocaleString()}</span>
          </div>
          {!hasUnlimitedPass && (
            <div className="flex items-center justify-between mt-1">
              <span className="text-gray-400 font-mono text-sm">Cost</span>
              <span className="text-yellow-400 font-mono">${GRID_UNLOCK_PRICE_USD} USDC</span>
            </div>
          )}
        </div>
      )}

      {/* Error */}
      {error && (
        <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30">
          <p className="text-red-400 font-mono text-sm">{error}</p>
        </div>
      )}
    </div>
  );
}

function GridSizePreview({ size }: { size: number }) {
  const displaySize = Math.min(size, 5);
  return (
    <div
      className="w-10 h-10 rounded bg-[#0a0a0a] border border-[#00ff00]/10 p-0.5 grid gap-px"
      style={{
        gridTemplateColumns: `repeat(${displaySize}, 1fr)`,
        gridTemplateRows: `repeat(${displaySize}, 1fr)`,
      }}
    >
      {Array.from({ length: displaySize * displaySize }).map((_, i) => (
        <div key={i} className="bg-[#00ff00]/20 rounded-sm" />
      ))}
    </div>
  );
}

function DetailsForm({
  name,
  onNameChange,
  subtitle,
  onSubtitleChange,
  description,
  onDescriptionChange,
  visibility,
  onVisibilityChange,
  selectedSize,
  error,
}: {
  name: string;
  onNameChange: (name: string) => void;
  subtitle: string;
  onSubtitleChange: (subtitle: string) => void;
  description: string;
  onDescriptionChange: (description: string) => void;
  visibility: GridVisibility;
  onVisibilityChange: (visibility: GridVisibility) => void;
  selectedSize: number;
  error: string | null;
}) {
  return (
    <div className="space-y-4">
      {/* Size info */}
      <div className="p-3 rounded-lg bg-black border border-[#1a1a1a]">
        <div className="flex items-center justify-between">
          <span className="text-gray-400 font-mono text-sm">Size</span>
          <span className="text-[#00ff00] font-mono">
            {selectedSize}×{selectedSize}
          </span>
        </div>
      </div>

      {/* Name input */}
      <div>
        <label className="block text-gray-400 font-mono text-sm mb-2">
          Grid Name *
        </label>
        <input
          type="text"
          value={name}
          onChange={(e) => onNameChange(e.target.value)}
          placeholder="My Collection"
          maxLength={50}
          className="w-full px-4 py-3 rounded-lg bg-black border border-[#1a1a1a] text-white font-mono placeholder:text-gray-600 focus:border-[#00ff00]/30 focus:outline-none transition-colors"
          style={{ fontSize: "16px" }}
        />
      </div>

      {/* Subtitle input */}
      <div>
        <label className="block text-gray-400 font-mono text-sm mb-2">
          Subtitle <span className="text-gray-600">(optional)</span>
        </label>
        <input
          type="text"
          value={subtitle}
          onChange={(e) => onSubtitleChange(e.target.value)}
          placeholder="A short tagline..."
          maxLength={100}
          className="w-full px-4 py-3 rounded-lg bg-black border border-[#1a1a1a] text-white font-mono placeholder:text-gray-600 focus:border-[#00ff00]/30 focus:outline-none transition-colors"
          style={{ fontSize: "16px" }}
        />
      </div>

      {/* Description input */}
      <div>
        <label className="block text-gray-400 font-mono text-sm mb-2">
          Description <span className="text-gray-600">(optional)</span>
        </label>
        <textarea
          value={description}
          onChange={(e) => onDescriptionChange(e.target.value)}
          placeholder="Tell people what this grid is about..."
          maxLength={500}
          rows={3}
          className="w-full px-4 py-3 rounded-lg bg-black border border-[#1a1a1a] text-white font-mono placeholder:text-gray-600 focus:border-[#00ff00]/30 focus:outline-none transition-colors resize-none"
          style={{ fontSize: "16px" }}
        />
        <p className="text-gray-600 font-mono text-xs mt-1 text-right">
          {description.length}/500
        </p>
      </div>

      {/* Visibility toggle */}
      <div>
        <label className="block text-gray-400 font-mono text-sm mb-2">
          Visibility
        </label>
        <div className="flex gap-2">
          <button
            onClick={() => onVisibilityChange("public")}
            className={`flex-1 py-2 px-3 rounded-lg font-mono text-sm border transition-all ${
              visibility === "public"
                ? "bg-[#00ff00]/10 border-[#00ff00]/30 text-[#00ff00]"
                : "bg-black border-[#1a1a1a] text-gray-400 hover:border-[#00ff00]/20"
            }`}
          >
            Public
          </button>
          <button
            onClick={() => onVisibilityChange("hidden")}
            className={`flex-1 py-2 px-3 rounded-lg font-mono text-sm border transition-all ${
              visibility === "hidden"
                ? "bg-[#00ff00]/10 border-[#00ff00]/30 text-[#00ff00]"
                : "bg-black border-[#1a1a1a] text-gray-400 hover:border-[#00ff00]/20"
            }`}
          >
            Hidden
          </button>
        </div>
        <p className="text-gray-600 font-mono text-xs mt-2">
          {visibility === "public"
            ? "Visible in public feed and can receive upvotes"
            : "Only visible to you"}
        </p>
      </div>

      {/* Error */}
      {error && (
        <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30">
          <p className="text-red-400 font-mono text-sm">{error}</p>
        </div>
      )}
    </div>
  );
}
src/features/app/components/create-image-upload.tsx
"use client";

import { useState, useCallback } from "react";
import { Card, CardContent, Small, H4 } from "@neynar/ui";
import { ImageIcon, EditIcon, TrashIcon, UploadIcon } from "@/components/icons/net-library-icons";
import { ImageEditor } from "./image-editor";
import type { Stack } from "@/features/app/types";

// Category IDs relevant for created content
const CREATE_CATEGORY_IDS = ["art", "memes", "culture", "farcaster", "other"] as const;
type CreateCategoryId = (typeof CREATE_CATEGORY_IDS)[number];

interface CreateImageUploadProps {
  categories: Array<{ id: string; label: string; emoji: string }>;
  stacks: Stack[];
  isLoadingStacks: boolean;
  onUpload: (data: {
    dataUrl: string;
    format: string;
    title: string;
    category: string;
    stackIds: string[];
  }) => Promise<void>;
  isUploading: boolean;
  /** If true, open the editor immediately without showing a button first */
  autoOpenEditor?: boolean;
  /** Called when user cancels from autoOpenEditor mode - parent should collapse the section */
  onAutoOpenCancel?: () => void;
}

export function CreateImageUpload({
  stacks,
  isLoadingStacks,
  onUpload,
  isUploading,
  autoOpenEditor = false,
  onAutoOpenCancel,
}: CreateImageUploadProps) {
  // Auto-open editor when autoOpenEditor is true
  const [showEditor, setShowEditor] = useState(autoOpenEditor);
  const [createdImage, setCreatedImage] = useState<{ dataUrl: string; format: string } | null>(null);

  // Item details
  const [title, setTitle] = useState("");
  const [selectedCategory, setSelectedCategory] = useState<CreateCategoryId>("art");
  const [selectedStackIds, setSelectedStackIds] = useState<string[]>([]);

  // Handle image export from editor (when using the format export panel)
  const handleExport = useCallback((dataUrl: string, format: string) => {
    setCreatedImage({ dataUrl, format });
    setShowEditor(false);
  }, []);

  // Handle cancel
  const handleCancel = useCallback(() => {
    setShowEditor(false);
    // If we were auto-opened, tell parent to collapse the section
    if (autoOpenEditor && onAutoOpenCancel) {
      onAutoOpenCancel();
    }
  }, [autoOpenEditor, onAutoOpenCancel]);

  // Handle upload after save to camera roll - keeps editor open but transitions to upload form
  const handleUploadAfterSave = useCallback((dataUrl: string, format: string) => {
    setCreatedImage({ dataUrl, format });
    setShowEditor(false);
  }, []);

  // Handle upload
  const handleUpload = useCallback(async () => {
    if (!createdImage || !title.trim()) return;

    await onUpload({
      dataUrl: createdImage.dataUrl,
      format: createdImage.format,
      title: title.trim(),
      category: selectedCategory,
      stackIds: selectedStackIds,
    });

    // Reset state on success
    setCreatedImage(null);
    setTitle("");
    setSelectedCategory("art");
    setSelectedStackIds([]);
  }, [createdImage, title, selectedCategory, selectedStackIds, onUpload]);

  // Toggle stack selection
  const toggleStack = useCallback((stackId: string) => {
    setSelectedStackIds((prev) =>
      prev.includes(stackId)
        ? prev.filter((id) => id !== stackId)
        : [...prev, stackId]
    );
  }, []);

  // If editor is open, show it full screen
  if (showEditor) {
    return (
      <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
        <CardContent className="p-3">
          <ImageEditor
            onExport={handleExport}
            onCancel={handleCancel}
            onUploadAfterSave={handleUploadAfterSave}
          />
        </CardContent>
      </Card>
    );
  }

  // If we have a created image, show preview and upload form
  if (createdImage) {
    return (
      <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
        <CardContent className="p-4 space-y-4">
          <H4 className="text-[#00ff00] font-mono flex items-center gap-2"><ImageIcon size={18} /> Your Creation</H4>

          {/* Preview */}
          <div className="relative bg-[#0d0d0d] rounded-lg overflow-hidden border border-[#00ff00]/20">
            <img
              src={createdImage.dataUrl}
              alt="Created image"
              className="w-full h-auto max-h-64 object-contain"
            />
            <button
              onClick={() => setShowEditor(true)}
              className="absolute top-2 right-2 px-2 py-1 bg-black/70 text-white text-xs font-mono rounded hover:bg-black/90 flex items-center gap-1"
            >
              <EditIcon size={12} /> Edit
            </button>
          </div>

          {/* Title */}
          <div>
            <Small className="text-gray-400 font-mono text-[10px] uppercase block mb-1">
              Title *
            </Small>
            <input
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="Give your creation a name..."
              className="w-full px-3 py-2.5 rounded-lg bg-black border border-[#00ff00]/30 text-white font-mono focus:outline-none focus:border-[#00ff00] transition-colors"
            />
          </div>

          {/* Category */}
          <div>
            <Small className="text-gray-400 font-mono text-[10px] uppercase block mb-1">
              Category
            </Small>
            <div className="flex flex-wrap gap-1">
              {CREATE_CATEGORY_IDS.map((catId) => (
                <button
                  key={catId}
                  onClick={() => setSelectedCategory(catId)}
                  className={`px-3 py-1.5 rounded-lg font-mono text-xs transition-all ${
                    selectedCategory === catId
                      ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/50"
                      : "bg-gray-800 text-gray-400 border border-transparent hover:border-gray-700"
                  }`}
                >
                  {catId}
                </button>
              ))}
            </div>
          </div>

          {/* Stacks */}
          {stacks.length > 0 && (
            <div>
              <Small className="text-gray-400 font-mono text-[10px] uppercase block mb-1">
                Add to Stacks (optional)
              </Small>
              <div className="flex flex-wrap gap-1 max-h-24 overflow-y-auto">
                {isLoadingStacks ? (
                  <Small className="text-gray-500 font-mono">Loading stacks...</Small>
                ) : (
                  stacks.map((stack) => {
                    const isSelected = selectedStackIds.includes(stack.id);
                    const isFull = !stack.unlocked && (stack.itemCount || 0) >= 20;
                    return (
                      <button
                        key={stack.id}
                        onClick={() => !isFull && toggleStack(stack.id)}
                        disabled={isFull}
                        className={`px-2 py-1 rounded font-mono text-xs transition-all ${
                          isFull
                            ? "bg-gray-800 text-gray-600 cursor-not-allowed"
                            : isSelected
                            ? "bg-purple-500/20 text-purple-400 border border-purple-500/50"
                            : "bg-gray-800 text-gray-400 hover:text-white"
                        }`}
                      >
                        📚 {stack.name}
                        {isFull && " (full)"}
                      </button>
                    );
                  })
                )}
              </div>
            </div>
          )}

          {/* Actions */}
          <div className="flex gap-2 pt-2">
            <button
              onClick={() => setCreatedImage(null)}
              className="flex-1 py-3 bg-gray-800 text-gray-300 rounded-lg font-mono text-sm hover:bg-gray-700 transition-colors flex items-center justify-center gap-1"
            >
              <TrashIcon size={14} /> Discard
            </button>
            <button
              onClick={handleUpload}
              disabled={!title.trim() || isUploading}
              className={`flex-1 py-3 rounded-lg font-mono text-sm transition-colors ${
                title.trim() && !isUploading
                  ? "bg-[#00ff00] text-black hover:bg-[#00ff00]/90"
                  : "bg-gray-700 text-gray-500 cursor-not-allowed"
              }`}
            >
              {isUploading ? "Uploading..." : <><UploadIcon size={14} className="inline mr-1" /> Upload to Net Library</>}
            </button>
          </div>
        </CardContent>
      </Card>
    );
  }

  // Default: Show start button
  return (
    <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
      <CardContent className="p-4">
        <button
          onClick={() => setShowEditor(true)}
          className="w-full py-8 border-2 border-dashed border-[#00ff00]/30 rounded-xl hover:border-[#00ff00]/60 transition-colors group"
        >
          <div className="text-center">
            <span className="text-4xl block mb-2 group-hover:scale-110 transition-transform">🎨</span>
            <H4 className="text-[#00ff00] font-mono">Open Image Editor</H4>
            <Small className="text-gray-500 font-mono block mt-1">
              Draw, make memes, add text & emojis
            </Small>
          </div>
        </button>
      </CardContent>
    </Card>
  );
}
src/features/app/components/create-stack-modal.tsx
"use client";

import { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { useAccount, useBalance } from "wagmi";
import { P, Small } from "@neynar/ui";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { useUserProfile } from "@/hooks/use-user-profile";
import { useSponsoredTransaction } from "@/hooks/use-sponsored-transaction";
import { formatUnits, type Address } from "viem";
import { base } from "viem/chains";
import type { Stack, CreateStackRequest } from "@/features/app/types";
import { LockIcon, LightbulbIcon, LoadingIcon, WalletIcon, CheckCircleIcon, FolderIcon, AddIcon } from "@/components/icons/net-library-icons";
import { useWalletCapabilities } from "@/hooks/use-wallet-capabilities";

// Constants
const STACK_CREATION_COST = 5; // $5 USDC for non-members
const MEMBERSHIP_COST = 2; // $2 USDC for membership

// USDC Contract on Base
const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" as Address;
const USDC_ABI = [
  {
    name: "transfer",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "to", type: "address" },
      { name: "value", type: "uint256" },
    ],
    outputs: [{ type: "bool" }],
  },
] as const;

// Treasury address for payments
const TREASURY_ADDRESS = "0xAcAD71e697Ef3bb148093b2DD2fCf0845e957627" as const;

interface CreateStackModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: (stack: Stack) => void;
  createStack: (data: CreateStackRequest) => Promise<Stack | null>;
}

export function CreateStackModal({
  isOpen,
  onClose,
  onSuccess,
  createStack,
}: CreateStackModalProps) {
  const { address } = useAccount();
  const { isMember, isLoading: isLoadingMembership, refreshMembership } = useMembershipStatus();
  const { profile: userProfile } = useUserProfile();

  const [name, setName] = useState("");
  const [description, setDescription] = useState("");
  const [isPrivate, setIsPrivate] = useState(false);
  const [stackType, setStackType] = useState<"standard" | "filesystem">("standard");
  const [isCreating, setIsCreating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [showPaymentStep, setShowPaymentStep] = useState(false);
  const [paymentMode, setPaymentMode] = useState<"stack" | "membership">("stack");
  const [paymentState, setPaymentState] = useState<"idle" | "paying" | "confirming" | "processing" | "complete" | "error">("idle");
  const [mounted, setMounted] = useState(false);
  const [createdStack, setCreatedStack] = useState<Stack | null>(null);

  // Check USDC balance
  const { data: usdcBalance } = useBalance({
    address: address as Address | undefined,
    token: USDC_ADDRESS,
    chainId: base.id,
  });

  const usdcBalanceFormatted = usdcBalance ? parseFloat(formatUnits(usdcBalance.value, 6)) : 0;
  const currentCost = paymentMode === "membership" ? MEMBERSHIP_COST : STACK_CREATION_COST;

  // Check if the wallet has auxiliary funds (Coinbase Smart Wallet / MagicSpend).
  // These users can pay from their Coinbase exchange balance even if onchain USDC is zero.
  const { hasAuxiliaryFunds } = useWalletCapabilities();
  const hasEnoughUsdc = usdcBalanceFormatted >= currentCost || hasAuxiliaryFunds;

  // Sponsored transaction hook
  const {
    sendSponsoredTransaction,
    txHash,
    isPending,
    isConfirming,
    isConfirmed,
    error: writeError,
    reset,
    isSponsored,
  } = useSponsoredTransaction();

  // Track client-side mount for portal
  useEffect(() => {
    setMounted(true);
  }, []);

  // Reset state when modal opens/closes
  useEffect(() => {
    if (!isOpen) {
      setName("");
      setDescription("");
      setIsPrivate(false);
      setStackType("standard");
      setError(null);
      setShowPaymentStep(false);
      setPaymentMode("stack");
      setPaymentState("idle");
      setIsCreating(false);
      setCreatedStack(null);
      reset();
    } else {
      // Also reset createdStack when modal opens (in case it was left over)
      setCreatedStack(null);
    }
  }, [isOpen, reset]);

  // Handle write errors
  useEffect(() => {
    if (writeError && paymentState === "paying") {
      const errMsg = writeError.message?.toLowerCase() || "";
      if (errMsg.includes("user rejected") || errMsg.includes("denied") || errMsg.includes("cancelled")) {
        reset();
        setPaymentState("idle");
        return;
      }
      setError(writeError.message?.slice(0, 60) || "Payment failed");
      setPaymentState("error");
    }
  }, [writeError, paymentState, reset]);

  // Handle transaction confirming
  useEffect(() => {
    if (txHash && isConfirming && paymentState === "paying") {
      setPaymentState("confirming");
    }
  }, [txHash, isConfirming, paymentState]);

  // Handle transaction confirmed
  useEffect(() => {
    if (isConfirmed && txHash && (paymentState === "paying" || paymentState === "confirming")) {
      handlePaymentComplete(txHash);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isConfirmed, txHash]);

  if (!isOpen || !mounted) return null;

  // Handle payment completion
  const handlePaymentComplete = async (hash: string) => {
    setPaymentState("processing");

    try {
      if (paymentMode === "membership") {
        // Register membership
        const response = await fetch("/api/membership", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            address,
            fid: userProfile?.fid,
            username: userProfile?.username,
            txHash: hash,
            signupPlatform: userProfile?.fid ? "farcaster" : "base-app",
          }),
        });

        const data = await response.json();
        if (!response.ok && !data.alreadyMember) {
          throw new Error(data.error || "Failed to register membership");
        }

        // Refresh membership status
        refreshMembership?.();

        // Now create the stack (member now, so free)
        await createStackAfterPayment();
      } else {
        // Create stack with payment txHash
        await createStackAfterPayment(hash);
      }
    } catch (err) {
      console.error("[CreateStackModal] Payment processing error:", err);
      setError(err instanceof Error ? err.message : "Failed to process payment");
      setPaymentState("error");
    }
  };

  // Create stack after payment (or free for members)
  const createStackAfterPayment = async (txHash?: string) => {
    const stackData: CreateStackRequest = {
      name: name.trim(),
      description: description.trim() || undefined,
      ownerFid: userProfile?.fid,
      ownerUsername: userProfile?.username,
      ownerPfpUrl: userProfile?.pfpUrl,
      isPrivate,
      txHash, // Include payment proof for non-member stack creation
    };

    const stack = await createStack(stackData);

    if (stack) {
      // If filesystem mode selected, set it on the stack
      if (stackType === "filesystem") {
        await fetch("/api/stacks", {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            stackId: stack.id,
            action: "set-filesystem-mode",
            owner: address,
            sourceType: "upload",
          }),
        });
        // Update the stack object with filesystem flag for the callback
        stack.isFileSystem = true;
      }

      setPaymentState("complete");
      reset();

      // Show success state with options instead of auto-closing
      setCreatedStack(stack);
    } else {
      throw new Error("Failed to create stack");
    }
  };

  // Initiate payment
  const handlePayment = async () => {
    if (!address) return;

    setError(null);
    setPaymentState("paying");

    try {
      // TODO: Add NET_LIBRARY_DATA_SUFFIX (ERC-8021) when payment path uses sendCallsAsync (EIP-5792)
      await sendSponsoredTransaction({
        address: USDC_ADDRESS,
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        abi: USDC_ABI as any,
        functionName: "transfer",
        args: [TREASURY_ADDRESS, BigInt(currentCost * 1_000_000)], // USDC has 6 decimals
      });
    } catch (err) {
      console.error("[CreateStackModal] Transaction failed:", err);
    }
  };

  const handleSubmit = async () => {
    if (!name.trim()) {
      setError("Stack name is required");
      return;
    }

    if (name.trim().length < 3) {
      setError("Stack name must be at least 3 characters");
      return;
    }

    if (name.trim().length > 50) {
      setError("Stack name must be 50 characters or less");
      return;
    }

    // Non-members need to pay
    if (!isMember && !showPaymentStep) {
      setShowPaymentStep(true);
      return;
    }

    // Members can create directly
    if (isMember) {
      setIsCreating(true);
      setError(null);

      try {
        const stackData: CreateStackRequest = {
          name: name.trim(),
          description: description.trim() || undefined,
          ownerFid: userProfile?.fid,
          ownerUsername: userProfile?.username,
          ownerPfpUrl: userProfile?.pfpUrl,
          isPrivate,
        };

        const stack = await createStack(stackData);

        if (stack) {
          // If filesystem mode selected, set it on the stack
          if (stackType === "filesystem") {
            await fetch("/api/stacks", {
              method: "PUT",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                stackId: stack.id,
                action: "set-filesystem-mode",
                owner: address,
                sourceType: "upload",
              }),
            });
            // Update the stack object with filesystem flag for the callback
            stack.isFileSystem = true;
          }

          // Show success state with options instead of auto-closing
          setCreatedStack(stack);
        } else {
          setError("Failed to create stack. Please try again.");
        }
      } catch (err) {
        console.error("[CreateStackModal] Error:", err);
        setError("An error occurred. Please try again.");
      } finally {
        setIsCreating(false);
      }
    }
  };

  const modalContent = (
    <div
      className="fixed inset-0 bg-black/90 z-[9999] flex items-center justify-center p-4"
      onClick={() => {
        if (createdStack) {
          onSuccess(createdStack);
        }
        onClose();
      }}
    >
      <div
        className="w-full max-w-sm bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl overflow-hidden"
        onClick={(e: React.MouseEvent) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 py-3 border-b border-[#00ff00]/20 flex items-center justify-between">
          <P className="text-[#00ff00] font-mono font-medium">
            {createdStack ? "Stack Created!" : showPaymentStep ? "Payment Required" : "Create Stack"}
          </P>
          {!createdStack && (
            <button
              onClick={onClose}
              className="w-8 h-8 rounded-lg bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors"
            >
              ✕
            </button>
          )}
        </div>

        <div className="p-4 space-y-3">
          {/* Success State - Stack Created */}
          {createdStack ? (
            <div className="text-center py-6">
              <div className="w-20 h-20 mx-auto mb-4 bg-[#00ff00]/20 rounded-full flex items-center justify-center">
                <CheckCircleIcon size={40} className="text-[#00ff00]" />
              </div>
              <P className="text-white font-mono font-bold text-lg mb-1">
                {createdStack.name}
              </P>
              <Small className="text-gray-400 font-mono block mb-6">
                {createdStack.isFileSystem ? "Filesystem stack ready for files" : "Stack ready for items"}
              </Small>

              {/* Action buttons */}
              <div className="flex flex-col gap-2">
                <button
                  onClick={() => {
                    // Navigate to stack detail to add items
                    onSuccess(createdStack);
                    window.dispatchEvent(
                      new CustomEvent("navigate-to-stack", { detail: createdStack })
                    );
                    onClose();
                  }}
                  className="w-full py-3 bg-[#00ff00] rounded-lg text-black font-mono font-bold text-sm hover:bg-[#00ff00]/90 transition-colors flex items-center justify-center gap-2"
                >
                  {createdStack.isFileSystem ? (
                    <>
                      <FolderIcon size={16} />
                      Import Files
                    </>
                  ) : (
                    <>
                      <AddIcon size={16} />
                      Add Items
                    </>
                  )}
                </button>
                <button
                  onClick={() => {
                    onSuccess(createdStack);
                    onClose();
                  }}
                  className="w-full py-3 bg-[#1a1a1a] rounded-lg text-gray-400 font-mono text-sm hover:bg-[#222] transition-colors"
                >
                  Done
                </button>
              </div>
            </div>
          ) : showPaymentStep ? (
            <>
              {/* Payment Complete - Brief transition state (stack creation handled by createdStack UI) */}
              {paymentState === "complete" && !createdStack && (
                <div className="text-center py-4">
                  <div className="w-16 h-16 mx-auto mb-4 bg-[#00ff00]/20 rounded-full flex items-center justify-center animate-pulse">
                    <LoadingIcon size={28} className="text-[#00ff00] animate-spin" />
                  </div>
                  <P className="text-[#00ff00] font-mono font-bold">
                    {paymentMode === "membership" ? "Welcome, Member!" : "Payment confirmed!"}
                  </P>
                  <Small className="text-gray-400 font-mono block mt-2">
                    Creating your stack...
                  </Small>
                </div>
              )}

              {/* Error State */}
              {paymentState === "error" && (
                <div className="text-center py-4">
                  <div className="w-16 h-16 mx-auto mb-4 bg-red-500/20 rounded-full flex items-center justify-center">
                    <span className="text-3xl">!</span>
                  </div>
                  <P className="text-red-400 font-mono font-bold">Payment Failed</P>
                  <Small className="text-gray-400 font-mono block mt-2">{error || "Something went wrong"}</Small>
                  <button
                    onClick={() => {
                      setPaymentState("idle");
                      setError(null);
                      reset();
                    }}
                    className="mt-4 px-6 py-2 bg-[#1a1a1a] text-white font-mono rounded-lg hover:bg-[#222] transition-colors"
                  >
                    Try Again
                  </button>
                </div>
              )}

              {/* Processing States */}
              {(paymentState === "paying" || paymentState === "confirming" || paymentState === "processing") && (
                <div className="text-center py-4">
                  <div className="w-16 h-16 mx-auto mb-4 bg-[#00ff00]/20 rounded-full flex items-center justify-center animate-pulse">
                    <LoadingIcon size={28} className="text-[#00ff00] animate-spin" />
                  </div>
                  <P className="text-[#00ff00] font-mono font-bold">
                    {paymentState === "paying" && "Confirm in wallet..."}
                    {paymentState === "confirming" && "Confirming transaction..."}
                    {paymentState === "processing" && "Processing..."}
                  </P>
                </div>
              )}

              {/* Idle State - Payment options */}
              {paymentState === "idle" && (
                <>
                  {/* Membership upsell - recommended option */}
                  <div
                    className={`p-4 rounded-xl cursor-pointer transition-all ${
                      paymentMode === "membership"
                        ? "bg-gradient-to-br from-purple-500/20 to-[#00ff00]/20 border-2 border-purple-500"
                        : "bg-[#1a1a1a] border border-gray-700 hover:border-purple-500/50"
                    }`}
                    onClick={() => setPaymentMode("membership")}
                  >
                    <div className="flex items-start gap-3">
                      <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center mt-0.5 ${
                        paymentMode === "membership" ? "border-purple-500 bg-purple-500" : "border-gray-500"
                      }`}>
                        {paymentMode === "membership" && <span className="text-white text-xs">✓</span>}
                      </div>
                      <div className="flex-1">
                        <div className="flex items-center gap-2">
                          <P className="text-white font-mono font-bold">Become a Member</P>
                          <span className="px-1.5 py-0.5 text-[10px] bg-purple-500/30 text-purple-300 rounded font-mono">BEST VALUE</span>
                        </div>
                        <Small className="text-purple-400 font-mono block">${MEMBERSHIP_COST} USDC</Small>
                        <div className="mt-2 space-y-1">
                          <Small className="text-gray-400 font-mono block">✓ Create stacks for FREE forever</Small>
                          <Small className="text-gray-400 font-mono block">✓ Save ${STACK_CREATION_COST - MEMBERSHIP_COST} on this stack alone</Small>
                          <Small className="text-gray-400 font-mono block">✓ Get your own ENS name (X.netlibrary.eth)</Small>
                          <Small className="text-gray-400 font-mono block">✓ Support the Net Library community</Small>
                        </div>
                      </div>
                    </div>
                  </div>

                  {/* One-time stack payment option */}
                  <div
                    className={`p-4 rounded-xl cursor-pointer transition-all ${
                      paymentMode === "stack"
                        ? "bg-[#00ff00]/10 border-2 border-[#00ff00]"
                        : "bg-[#1a1a1a] border border-gray-700 hover:border-[#00ff00]/50"
                    }`}
                    onClick={() => setPaymentMode("stack")}
                  >
                    <div className="flex items-start gap-3">
                      <div className={`w-5 h-5 rounded-full border-2 flex items-center justify-center mt-0.5 ${
                        paymentMode === "stack" ? "border-[#00ff00] bg-[#00ff00]" : "border-gray-500"
                      }`}>
                        {paymentMode === "stack" && <span className="text-black text-xs">✓</span>}
                      </div>
                      <div className="flex-1">
                        <P className="text-white font-mono font-bold">Pay Per Stack</P>
                        <Small className="text-[#00ff00] font-mono block">${STACK_CREATION_COST} USDC</Small>
                        <Small className="text-gray-500 font-mono block mt-1">One-time payment for this stack</Small>
                      </div>
                    </div>
                  </div>

                  {/* Balance warning */}
                  {!hasEnoughUsdc && (
                    <div className="p-3 bg-red-500/10 border border-red-500/30 rounded-lg">
                      <div className="flex items-start gap-2">
                        <WalletIcon size={20} className="text-red-400 shrink-0 mt-0.5" />
                        <div>
                          <P className="text-red-400 font-mono text-sm font-medium">Insufficient USDC</P>
                          <Small className="text-red-400/70 font-mono">
                            Need ${currentCost}, you have ${usdcBalanceFormatted.toFixed(2)}
                          </Small>
                        </div>
                      </div>
                    </div>
                  )}

                  {/* Action buttons */}
                  <div className="flex gap-2 pt-1">
                    <button
                      onClick={() => setShowPaymentStep(false)}
                      className="flex-1 py-2.5 bg-[#1a1a1a] rounded-lg text-gray-400 font-mono text-sm hover:bg-[#222] transition-colors"
                    >
                      ← Back
                    </button>
                    <button
                      onClick={handlePayment}
                      disabled={isPending || !hasEnoughUsdc}
                      className={`flex-1 py-2.5 rounded-lg font-mono text-sm font-bold transition-colors disabled:opacity-50 ${
                        paymentMode === "membership"
                          ? "bg-purple-500 text-white hover:bg-purple-600"
                          : "bg-[#00ff00] text-black hover:bg-[#00ff00]/90"
                      }`}
                    >
                      {isPending ? "Processing..." : `Pay $${currentCost} USDC`}
                      {isSponsored && <span className="ml-1 text-[10px] opacity-70">⛽</span>}
                    </button>
                  </div>
                </>
              )}
            </>
          ) : (
            <>
              {/* Member Status - compact */}
              {isLoadingMembership ? (
                <Small className="text-gray-400 font-mono block">Checking membership...</Small>
              ) : isMember ? (
                <div className="p-2 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg">
                  <Small className="text-[#00ff00] font-mono">✓ Member - Free stacks!</Small>
                </div>
              ) : (
                <div className="p-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">
                  <Small className="text-yellow-400 font-mono">${STACK_CREATION_COST} USDC per stack</Small>
                </div>
              )}

              {/* Stack Name Input */}
              <div>
                <label className="block text-xs font-mono text-gray-400 mb-1 uppercase tracking-wider">
                  Stack Name
                </label>
                <input
                  type="text"
                  value={name}
                  onChange={(e) => setName(e.target.value)}
                  placeholder="My Awesome Stack"
                  maxLength={50}
                  className="w-full px-3 py-2 bg-[#1a1a1a] border border-[#00ff00]/20 rounded-lg text-white font-mono text-sm placeholder:text-gray-600 focus:outline-none focus:border-[#00ff00]/50"
                />
              </div>

              {/* Description Input */}
              <div>
                <label className="block text-xs font-mono text-gray-400 mb-1 uppercase tracking-wider">
                  Description
                </label>
                <textarea
                  value={description}
                  onChange={(e) => setDescription(e.target.value)}
                  placeholder="Optional..."
                  maxLength={200}
                  rows={2}
                  className="w-full px-3 py-2 bg-[#1a1a1a] border border-[#00ff00]/20 rounded-lg text-white font-mono text-sm placeholder:text-gray-600 focus:outline-none focus:border-[#00ff00]/50 resize-none"
                />
              </div>

              {/* Stack Limit Info - First-time hint */}
              <div className="p-2.5 bg-[#1a1a1a] border border-[#00ff00]/20 rounded-lg">
                <div className="flex items-start gap-2">
                  <LightbulbIcon size={14} className="text-[#00ff00] mt-0.5 shrink-0" />
                  <div>
                    <Small className="text-gray-300 font-mono block">
                      Free stacks hold up to 20 items
                    </Small>
                    <Small className="text-gray-500 font-mono block mt-0.5">
                      Upgrade anytime for unlimited • $5 per stack or $10 for all stacks forever
                    </Small>
                  </div>
                </div>
              </div>

              {/* Privacy Toggle */}
              <div className="flex items-center justify-between p-3 bg-[#1a1a1a] border border-[#00ff00]/20 rounded-lg">
                <div>
                  <P className="text-white font-mono text-sm">Private Stack</P>
                  <Small className="text-gray-500 font-mono">Only you can see this stack</Small>
                </div>
                <button
                  type="button"
                  onClick={() => setIsPrivate(!isPrivate)}
                  className={`relative w-12 h-6 rounded-full transition-colors ${
                    isPrivate ? "bg-purple-500" : "bg-gray-600"
                  }`}
                >
                  <span
                    className={`absolute top-1 w-4 h-4 rounded-full bg-white transition-transform ${
                      isPrivate ? "left-7" : "left-1"
                    }`}
                  />
                </button>
              </div>

              {/* Privacy Info */}
              {isPrivate && (
                <div className="p-2 bg-purple-500/10 border border-purple-500/30 rounded-lg flex items-center gap-2">
                  <LockIcon size={12} className="text-purple-400 shrink-0" />
                  <Small className="text-purple-400 font-mono">
                    Items added to this stack will be hidden from public feeds
                  </Small>
                </div>
              )}

              {/* Stack Type Toggle */}
              <div className="p-3 bg-[#1a1a1a] border border-[#00ff00]/20 rounded-lg">
                <P className="text-white font-mono text-sm mb-2">Stack Type</P>
                <div className="flex gap-2">
                  <button
                    type="button"
                    onClick={() => setStackType("standard")}
                    className={`flex-1 py-2 px-3 rounded-lg font-mono text-sm transition-colors ${
                      stackType === "standard"
                        ? "bg-[#00ff00] text-black font-bold"
                        : "bg-[#0a0a0a] text-gray-400 hover:bg-[#111]"
                    }`}
                  >
                    Standard
                  </button>
                  <button
                    type="button"
                    onClick={() => setStackType("filesystem")}
                    className={`flex-1 py-2 px-3 rounded-lg font-mono text-sm transition-colors ${
                      stackType === "filesystem"
                        ? "bg-[#00ff00] text-black font-bold"
                        : "bg-[#0a0a0a] text-gray-400 hover:bg-[#111]"
                    }`}
                  >
                    Filesystem
                  </button>
                </div>
                <Small className="text-gray-500 font-mono block mt-2">
                  {stackType === "standard"
                    ? "A flat collection of items"
                    : "Organize items into folders — like a decentralized Dropbox"}
                </Small>
              </div>

              {/* Error */}
              {error && (
                <Small className="text-red-400 font-mono block">{error}</Small>
              )}

              {/* Actions */}
              <div className="flex gap-2 pt-1">
                <button
                  onClick={onClose}
                  className="flex-1 py-2 bg-[#1a1a1a] rounded-lg text-gray-400 font-mono text-sm hover:bg-[#222] transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleSubmit}
                  disabled={!name.trim() || isCreating}
                  className="flex-1 py-2 bg-[#00ff00] rounded-lg text-black font-mono font-bold text-sm disabled:opacity-50"
                >
                  {isCreating ? "Creating..." : "Create"}
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );

  return createPortal(modalContent, document.body);
}
src/features/app/components/desktop-context-menu.tsx
"use client";

/**
 * Desktop Context Menu Component
 *
 * Right-click context menu for desktop users only.
 * Does NOT render on mobile or in Farcaster/Base App contexts.
 */

import { useState, useCallback, useRef, useEffect, ReactNode } from "react";
import { useDesktopMode } from "@/hooks/use-desktop-mode";

export interface ContextMenuItem {
  label: string;
  icon?: string;
  onClick: () => void;
  disabled?: boolean;
  danger?: boolean;
  divider?: boolean;
}

interface ContextMenuProps {
  items: ContextMenuItem[];
  children: ReactNode;
  className?: string;
}

/**
 * Wrapper component that adds right-click context menu to its children
 * Only active on desktop - no-op on mobile
 */
export function DesktopContextMenu({
  items,
  children,
  className = "",
}: ContextMenuProps) {
  const { canShowContextMenus } = useDesktopMode();
  const [isOpen, setIsOpen] = useState(false);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const menuRef = useRef<HTMLDivElement>(null);

  // Handle right-click
  const handleContextMenu = useCallback(
    (e: React.MouseEvent) => {
      if (!canShowContextMenus) return;

      e.preventDefault();
      e.stopPropagation();

      // Calculate position, keeping menu within viewport
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;
      const menuWidth = 180; // Estimated menu width
      const menuHeight = items.length * 36 + 16; // Estimated menu height

      let x = e.clientX;
      let y = e.clientY;

      // Adjust if menu would go off-screen
      if (x + menuWidth > viewportWidth) {
        x = viewportWidth - menuWidth - 8;
      }
      if (y + menuHeight > viewportHeight) {
        y = viewportHeight - menuHeight - 8;
      }

      setPosition({ x, y });
      setIsOpen(true);
    },
    [canShowContextMenus, items.length]
  );

  // Close on click outside
  useEffect(() => {
    if (!isOpen) return;

    const handleClickOutside = (e: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
        setIsOpen(false);
      }
    };

    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        setIsOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    document.addEventListener("keydown", handleEscape);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
      document.removeEventListener("keydown", handleEscape);
    };
  }, [isOpen]);

  // Handle menu item click
  const handleItemClick = useCallback(
    (item: ContextMenuItem) => {
      if (item.disabled) return;
      setIsOpen(false);
      item.onClick();
    },
    []
  );

  // Don't render context menu functionality on mobile
  if (!canShowContextMenus) {
    return <div className={className}>{children}</div>;
  }

  return (
    <>
      <div onContextMenu={handleContextMenu} className={className}>
        {children}
      </div>

      {isOpen && (
        <div
          ref={menuRef}
          className="fixed z-[100] bg-[#1a1a1a] border border-[#00ff00]/30 rounded-lg shadow-lg py-1 min-w-[160px] animate-in fade-in zoom-in-95 duration-100"
          style={{
            left: position.x,
            top: position.y,
          }}
        >
          {items.map((item, index) => {
            if (item.divider) {
              return (
                <div
                  key={`divider-${index}`}
                  className="h-px bg-[#00ff00]/20 my-1"
                />
              );
            }

            return (
              <button
                key={item.label}
                onClick={() => handleItemClick(item)}
                disabled={item.disabled}
                className={`
                  w-full px-3 py-2 text-left text-sm font-mono
                  flex items-center gap-2 transition-colors
                  ${item.disabled
                    ? "text-gray-600 cursor-not-allowed"
                    : item.danger
                      ? "text-red-400 hover:bg-red-400/10"
                      : "text-[#00ff00] hover:bg-[#00ff00]/10"
                  }
                `}
              >
                {item.icon && <span>{item.icon}</span>}
                {item.label}
              </button>
            );
          })}
        </div>
      )}
    </>
  );
}

/**
 * Standard context menu items for books/content
 */
export function getBookContextMenuItems({
  onRead,
  onShare,
  onViewOnNet,
  onAddToStack,
}: {
  onRead?: () => void;
  onShare?: () => void;
  onViewOnNet?: () => void;
  onAddToStack?: () => void;
}): ContextMenuItem[] {
  const items: ContextMenuItem[] = [];

  if (onRead) {
    items.push({ label: "Open", icon: "📖", onClick: onRead });
  }

  if (onAddToStack) {
    items.push({ label: "Add to Stack", icon: "📚", onClick: onAddToStack });
  }

  if (items.length > 0 && (onShare || onViewOnNet)) {
    items.push({ label: "", icon: "", onClick: () => {}, divider: true });
  }

  if (onShare) {
    items.push({ label: "Share", icon: "↗", onClick: onShare });
  }

  if (onViewOnNet) {
    items.push({ label: "View on Net Protocol", icon: "🔗", onClick: onViewOnNet });
  }

  return items;
}

/**
 * Standard context menu items for stacks
 */
export function getStackContextMenuItems({
  onView,
  onEdit,
  onShare,
  onDelete,
  isOwner = false,
}: {
  onView?: () => void;
  onEdit?: () => void;
  onShare?: () => void;
  onDelete?: () => void;
  isOwner?: boolean;
}): ContextMenuItem[] {
  const items: ContextMenuItem[] = [];

  if (onView) {
    items.push({ label: "View Stack", icon: "👁️", onClick: onView });
  }

  if (onEdit && isOwner) {
    items.push({ label: "Edit Stack", icon: "✏️", onClick: onEdit });
  }

  if (onShare) {
    items.push({ label: "Share Stack", icon: "↗", onClick: onShare });
  }

  if (onDelete && isOwner) {
    items.push({ label: "", icon: "", onClick: () => {}, divider: true });
    items.push({ label: "Delete Stack", icon: "🗑️", onClick: onDelete, danger: true });
  }

  return items;
}
src/features/app/components/edit-item-modal.tsx
"use client";

import React, { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { P, Small } from "@neynar/ui";
import { BookmarkIcon } from "@/components/icons/net-library-icons";
import type { Category } from "@/features/app/types";
import type { DiscoveryEntry } from "@/lib/net-protocol";

interface EditItemModalProps {
  isOpen: boolean;
  onClose: () => void;
  entry: DiscoveryEntry;
  categories: Category[];
  onUpdate: () => void;
  currentUserAddress?: string; // Current wallet for cross-platform ownership
  userFid?: number | null; // FID for cross-platform ownership lookup
}

export function EditItemModal({
  isOpen,
  onClose,
  entry,
  categories,
  onUpdate,
  currentUserAddress,
  userFid,
}: EditItemModalProps) {
  const [formData, setFormData] = useState({
    title: entry.title || '',
    author: entry.author || '',
    categories: Array.isArray(entry.categories) ? entry.categories : [],
    publicationYear: entry.publicationYear?.toString() || "",
    publisher: entry.publisher || "",
    isbn: entry.isbn || "",
    coverUrl: entry.coverUrl || "",
  });
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [mounted, setMounted] = useState(false);
  const [showCategoryPicker, setShowCategoryPicker] = useState(false);

  // Track client-side mount for portal
  useEffect(() => {
    setMounted(true);
  }, []);

  // Reset form when entry changes
  useEffect(() => {
    setFormData({
      title: entry.title || '',
      author: entry.author || '',
      categories: Array.isArray(entry.categories) ? entry.categories : [],
      publicationYear: entry.publicationYear?.toString() || "",
      publisher: entry.publisher || "",
      isbn: entry.isbn || "",
      coverUrl: entry.coverUrl || "",
    });
  }, [entry]);

  const handleSave = async () => {
    // Validate required fields
    if (!formData.title.trim()) {
      setError("Title is required");
      return;
    }
    if (!formData.author.trim()) {
      setError("Author is required");
      return;
    }
    if (formData.categories.length === 0) {
      setError("At least one category is required");
      return;
    }

    setIsSaving(true);
    setError(null);

    try {
      // Use current user's address for cross-platform ownership verification
      // The API will look up all linked addresses via the membership system
      const operatorAddress = currentUserAddress || entry.operator;

      const response = await fetch("/api/discovery", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          contentKey: entry.contentKey,
          operator: operatorAddress,
          fid: userFid, // Include FID for cross-platform ownership lookup
          title: formData.title.trim(),
          author: formData.author.trim(),
          categories: formData.categories,
          publicationYear: formData.publicationYear ? parseInt(formData.publicationYear) : undefined,
          publisher: formData.publisher.trim() || undefined,
          isbn: formData.isbn.trim() || undefined,
          coverUrl: formData.coverUrl.trim() || undefined,
        }),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "Failed to update");
      }

      onUpdate();
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to save");
    } finally {
      setIsSaving(false);
    }
  };

  const toggleCategory = (categoryId: string) => {
    setFormData(prev => {
      const newCategories = prev.categories.includes(categoryId)
        ? prev.categories.filter(c => c !== categoryId)
        : [...prev.categories, categoryId];
      return { ...prev, categories: newCategories };
    });
  };

  // Filter out "all" from selectable categories
  const selectableCategories = categories.filter(c => c.id !== "all");

  if (!isOpen || !mounted) return null;

  const modalContent = (
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/90"
      onClick={onClose}
    >
      <div
        className="w-full max-w-md max-h-[90vh] overflow-y-auto bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="sticky top-0 p-3 border-b border-[#00ff00]/20 bg-[#0a0a0a] flex items-center justify-between z-10">
          <div>
            <P className="text-white font-mono font-medium text-sm">Edit Item Details</P>
            <Small className="text-gray-500 font-mono text-[10px]">Changes are saved to your display settings</Small>
          </div>
          <button
            onClick={onClose}
            className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-white/10 text-gray-400 hover:text-white transition-colors"
          >
            ✕
          </button>
        </div>

        {/* Content */}
        <div className="p-4 space-y-4">
          {/* Cover Preview + Title/Author side by side */}
          <div className="flex gap-4">
            {/* Cover Preview */}
            <div className="w-20 h-28 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-lg border-2 border-[#00ff00]/30 flex items-center justify-center overflow-hidden shrink-0">
              {formData.coverUrl ? (
                <img src={formData.coverUrl} alt="Cover preview" className="w-full h-full object-cover" />
              ) : (
                <BookmarkIcon size={28} className="text-[#00ff00]/50" />
              )}
            </div>

            {/* Title & Author */}
            <div className="flex-1 space-y-3">
              <div>
                <label className="text-[10px] font-mono text-gray-500 uppercase tracking-wider block mb-1">
                  Title *
                </label>
                <input
                  type="text"
                  value={formData.title}
                  onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                  className="w-full px-3 py-2 bg-black/50 border border-[#00ff00]/20 rounded-lg text-white font-mono text-sm focus:border-[#00ff00] focus:outline-none"
                  placeholder="Enter title"
                />
              </div>

              <div>
                <label className="text-[10px] font-mono text-gray-500 uppercase tracking-wider block mb-1">
                  Author *
                </label>
                <input
                  type="text"
                  value={formData.author}
                  onChange={(e) => setFormData(prev => ({ ...prev, author: e.target.value }))}
                  className="w-full px-3 py-2 bg-black/50 border border-[#00ff00]/20 rounded-lg text-white font-mono text-sm focus:border-[#00ff00] focus:outline-none"
                  placeholder="Enter author"
                />
              </div>
            </div>
          </div>

          {/* Categories */}
          <div>
            <label className="text-[10px] font-mono text-gray-500 uppercase tracking-wider block mb-1">
              Categories * ({formData.categories.length} selected)
            </label>
            <button
              onClick={() => setShowCategoryPicker(!showCategoryPicker)}
              className="w-full px-3 py-2 bg-black/50 border border-[#00ff00]/20 rounded-lg text-left font-mono text-sm hover:border-[#00ff00]/40 transition-colors"
            >
              <div className="flex flex-wrap gap-1">
                {formData.categories.length === 0 ? (
                  <span className="text-gray-500">Select categories...</span>
                ) : (
                  formData.categories.map(catId => {
                    const cat = selectableCategories.find(c => c.id === catId);
                    return cat ? (
                      <span key={cat.id} className="px-1.5 py-0.5 bg-[#00ff00]/20 text-[#00ff00] rounded text-xs">
                        {cat.emoji} {cat.label}
                      </span>
                    ) : null;
                  })
                )}
              </div>
            </button>

            {/* Category Picker Dropdown */}
            {showCategoryPicker && (
              <div className="mt-2 p-2 bg-black border border-[#00ff00]/30 rounded-lg max-h-48 overflow-y-auto">
                <div className="grid grid-cols-2 gap-1">
                  {selectableCategories.map(cat => (
                    <button
                      key={cat.id}
                      onClick={() => toggleCategory(cat.id)}
                      className={`px-2 py-1.5 rounded text-xs font-mono text-left transition-colors ${
                        formData.categories.includes(cat.id)
                          ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/40"
                          : "bg-[#1a1a1a] text-gray-400 hover:text-white hover:bg-[#222]"
                      }`}
                    >
                      {cat.emoji} {cat.label}
                    </button>
                  ))}
                </div>
                <button
                  onClick={() => setShowCategoryPicker(false)}
                  className="w-full mt-2 py-1.5 text-[#00ff00] font-mono text-xs border border-[#00ff00]/30 rounded hover:bg-[#00ff00]/10"
                >
                  Done
                </button>
              </div>
            )}
          </div>

          {/* Cover URL */}
          <div>
            <label className="text-[10px] font-mono text-gray-500 uppercase tracking-wider block mb-1">
              Cover Image URL
            </label>
            <input
              type="text"
              value={formData.coverUrl}
              onChange={(e) => setFormData(prev => ({ ...prev, coverUrl: e.target.value }))}
              className="w-full px-3 py-2 bg-black/50 border border-[#00ff00]/20 rounded-lg text-white font-mono text-sm focus:border-[#00ff00] focus:outline-none"
              placeholder="https://..."
            />
          </div>

          {/* Optional Fields Row */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="text-[10px] font-mono text-gray-500 uppercase tracking-wider block mb-1">
                Publication Year
              </label>
              <input
                type="number"
                value={formData.publicationYear}
                onChange={(e) => setFormData(prev => ({ ...prev, publicationYear: e.target.value }))}
                className="w-full px-3 py-2 bg-black/50 border border-[#00ff00]/20 rounded-lg text-white font-mono text-sm focus:border-[#00ff00] focus:outline-none"
                placeholder="2024"
                min="1000"
                max="2100"
              />
            </div>

            <div>
              <label className="text-[10px] font-mono text-gray-500 uppercase tracking-wider block mb-1">
                ISBN / DOI
              </label>
              <input
                type="text"
                value={formData.isbn}
                onChange={(e) => setFormData(prev => ({ ...prev, isbn: e.target.value }))}
                className="w-full px-3 py-2 bg-black/50 border border-[#00ff00]/20 rounded-lg text-white font-mono text-sm focus:border-[#00ff00] focus:outline-none"
                placeholder="978-..."
              />
            </div>
          </div>

          {/* Publisher */}
          <div>
            <label className="text-[10px] font-mono text-gray-500 uppercase tracking-wider block mb-1">
              Publisher
            </label>
            <input
              type="text"
              value={formData.publisher}
              onChange={(e) => setFormData(prev => ({ ...prev, publisher: e.target.value }))}
              className="w-full px-3 py-2 bg-black/50 border border-[#00ff00]/20 rounded-lg text-white font-mono text-sm focus:border-[#00ff00] focus:outline-none"
              placeholder="Publisher name"
            />
          </div>

          {/* Info note */}
          <div className="p-3 bg-[#00ff00]/5 border border-[#00ff00]/20 rounded-lg">
            <Small className="text-gray-400 font-mono text-[10px] block">
              💡 These changes update how your item displays in Net Library. The original on-chain data remains unchanged.
            </Small>
          </div>

          {/* Error display */}
          {error && (
            <div className="p-2 bg-red-500/10 border border-red-500/30 rounded-lg">
              <Small className="text-red-400 font-mono text-xs">{error}</Small>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="sticky bottom-0 p-3 border-t border-[#00ff00]/20 bg-[#0a0a0a] flex gap-2">
          <button
            onClick={onClose}
            className="flex-1 py-2.5 text-gray-400 font-mono text-sm hover:bg-white/5 rounded-lg transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={isSaving}
            className="flex-1 py-2.5 bg-[#00ff00] text-black font-mono font-bold text-sm rounded-lg hover:bg-[#00ff00]/90 transition-colors disabled:opacity-50"
          >
            {isSaving ? "Saving..." : "Save Changes"}
          </button>
        </div>
      </div>
    </div>
  );

  return createPortal(modalContent, document.body);
}
src/features/app/components/edit-stack-modal.tsx
"use client";

import React, { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { P, Small } from "@neynar/ui";
import type { Stack } from "@/features/app/types";

interface EditStackModalProps {
  isOpen: boolean;
  onClose: () => void;
  stack: Stack;
  onSave: (name: string, description?: string) => Promise<boolean>;
}

export function EditStackModal({
  isOpen,
  onClose,
  stack,
  onSave,
}: EditStackModalProps) {
  const [name, setName] = useState(stack.name);
  const [description, setDescription] = useState(stack.description || "");
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [mounted, setMounted] = useState(false);

  // Track client-side mount for portal
  useEffect(() => {
    setMounted(true);
  }, []);

  // Reset form when modal opens with new stack
  useEffect(() => {
    if (isOpen) {
      setName(stack.name);
      setDescription(stack.description || "");
      setError(null);
    }
  }, [isOpen, stack]);

  if (!isOpen || !mounted) return null;

  const handleSave = async () => {
    const trimmedName = name.trim();
    if (!trimmedName) {
      setError("Stack name is required");
      return;
    }

    if (trimmedName.length < 2) {
      setError("Name must be at least 2 characters");
      return;
    }

    if (trimmedName.length > 50) {
      setError("Name must be 50 characters or less");
      return;
    }

    setIsSaving(true);
    setError(null);

    try {
      const success = await onSave(trimmedName, description.trim() || undefined);
      if (success) {
        onClose();
      } else {
        setError("Failed to update stack");
      }
    } catch (err) {
      console.error("Save error:", err);
      setError("Something went wrong");
    } finally {
      setIsSaving(false);
    }
  };

  const modalContent = (
    <div
      className="fixed inset-0 bg-black/95 z-[9999] flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="bg-[#0a0a0a] border border-purple-500/30 rounded-xl max-w-sm w-full overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 py-3 border-b border-purple-500/20 bg-purple-500/5">
          <div className="flex items-center justify-between">
            <P className="text-purple-400 font-mono font-medium">Edit Stack</P>
            <button
              onClick={onClose}
              className="w-8 h-8 rounded-lg bg-[#1a1a1a] text-gray-400 hover:text-white flex items-center justify-center"
            >
              ×
            </button>
          </div>
        </div>

        {/* Form */}
        <div className="p-4 space-y-3">
          {/* Stack Name */}
          <div>
            <label className="text-xs font-mono text-gray-400 uppercase tracking-wider block mb-1">
              Stack Name
            </label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="Enter stack name"
              maxLength={50}
              className="w-full px-3 py-2 bg-[#1a1a1a] border border-purple-500/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-purple-500"
            />
          </div>

          {/* Description */}
          <div>
            <label className="text-xs font-mono text-gray-400 uppercase tracking-wider block mb-1">
              Description
            </label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Optional description..."
              maxLength={200}
              rows={2}
              className="w-full px-3 py-2 bg-[#1a1a1a] border border-purple-500/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-purple-500 resize-none"
            />
          </div>

          {/* Error Message */}
          {error && (
            <Small className="text-red-400 font-mono block">{error}</Small>
          )}

          {/* Action Buttons */}
          <div className="flex gap-2 pt-1">
            <button
              onClick={onClose}
              disabled={isSaving}
              className="flex-1 py-2 rounded-lg bg-[#1a1a1a] text-gray-400 font-mono text-sm hover:bg-[#222] transition-colors disabled:opacity-50"
            >
              Cancel
            </button>
            <button
              onClick={handleSave}
              disabled={isSaving || !name.trim()}
              className="flex-1 py-2 rounded-lg bg-purple-500 text-white font-mono font-bold text-sm hover:bg-purple-600 transition-colors disabled:opacity-50"
            >
              {isSaving ? "Saving..." : "Save"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  return createPortal(modalContent, document.body);
}
src/features/app/components/enhanced-library-card.tsx
"use client";

import { useState, useRef } from "react";
import { Card, CardContent, P, Small } from "@neynar/ui";
import { TrophyIcon, UserIcon, LibraryIcon } from "@/components/icons/net-library-icons";
import { type AchievementId } from "@/lib/net-protocol";
import { AchievementGrid } from "./achievements";

interface UserData {
  displayName?: string;
  username?: string;
  pfpUrl?: string;
  fid?: number;
  address?: string;
  wid?: string; // Web ID for web platform users
  signupPlatform?: "farcaster" | "base-app" | "web";
  isAgent?: boolean; // True if this member is a registered AI agent
  agentId?: string;  // The agent's registered ID (e.g., "cheryl")
}

interface MemberData {
  memberId: number;
  ensSubname: string;
  joinedAt: string;
}

interface StatsData {
  uploads: number;
  reads: number; // Times your uploads were read by others
  bytesUploaded: number;
  booksRead: number;
  reviewsWritten: number;
  tipsGiven: number;
}

interface EnhancedLibraryCardProps {
  user: UserData;
  memberData?: MemberData;
  stats: StatsData;
  rank?: number;
  achievements?: AchievementId[];
  hasStackPass?: boolean; // Unlimited Stack Pass holder
  onBecomeMember?: () => void;
  onShare?: () => void;
}

// Braille alphabet mapping
const BRAILLE_MAP: Record<string, string> = {
  'a': '⠁', 'b': '⠃', 'c': '⠉', 'd': '⠙', 'e': '⠑',
  'f': '⠋', 'g': '⠛', 'h': '⠓', 'i': '⠊', 'j': '⠚',
  'k': '⠅', 'l': '⠇', 'm': '⠍', 'n': '⠝', 'o': '⠕',
  'p': '⠏', 'q': '⠟', 'r': '⠗', 's': '⠎', 't': '⠞',
  'u': '⠥', 'v': '⠧', 'w': '⠺', 'x': '⠭', 'y': '⠽',
  'z': '⠵', '0': '⠚', '1': '⠁', '2': '⠃', '3': '⠉',
  '4': '⠙', '5': '⠑', '6': '⠋', '7': '⠛', '8': '⠓',
  '9': '⠊', ' ': '⠀', '.': '⠲', ',': '⠂', '-': '⠤',
  '_': '⠸', '@': '⠈⠁'
};

function toBraille(text: string): string {
  return (text || '').toLowerCase().split('').map(char => BRAILLE_MAP[char] || char).join('');
}

// Format bytes for display
function _formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}


// QR Code component (generates a deterministic pattern)
function QRCodeDisplay({ data, size = 60 }: { data: string; size?: number }) {
  const hash = (data || '').split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
  const pattern: boolean[][] = [];

  for (let i = 0; i < 7; i++) {
    pattern[i] = [];
    for (let j = 0; j < 7; j++) {
      // Fixed corners for QR alignment
      if ((i < 2 && j < 2) || (i < 2 && j > 4) || (i > 4 && j < 2)) {
        pattern[i][j] = true;
      } else {
        pattern[i][j] = ((hash + i * 7 + j) % 3) === 0;
      }
    }
  }

  const cellSize = size / 7;

  return (
    <svg width={size} height={size} className="rounded">
      <rect width={size} height={size} fill="white" />
      {pattern.map((row, i) =>
        row.map((cell, j) =>
          cell ? (
            <rect
              key={`${i}-${j}`}
              x={j * cellSize}
              y={i * cellSize}
              width={cellSize}
              height={cellSize}
              fill="black"
            />
          ) : null
        )
      )}
    </svg>
  );
}

export function EnhancedLibraryCard({
  user,
  memberData,
  stats,
  rank = 0,
  achievements = [],
  hasStackPass = false,
  onBecomeMember,
  onShare
}: EnhancedLibraryCardProps) {
  const cardRef = useRef<HTMLDivElement>(null);
  const [isFlipped, setIsFlipped] = useState(false);

  const isMember = !!memberData;
  const isAgent = user.isAgent;

  // Use consistent green color for all members, purple for agents
  const memberColor = isAgent ? "#B794F4" : "#00ff00";
  const profileUrl = user.username ? `https://warpcast.com/${user.username}` : "";

  // Front of card
  const CardFront = () => (
    <div className="absolute inset-0" style={{ backfaceVisibility: "hidden" }}>
      <Card
        className="h-full border-2 overflow-hidden"
        style={{ borderColor: isMember ? `${memberColor}50` : "#00ff0030", backgroundColor: "#0a0a0a" }}
      >
        {/* Tier accent line at top */}
        <div className="h-1" style={{ backgroundColor: isMember ? memberColor : "#00ff00" }} />

        {/* Scanline effect */}
        <div className="absolute inset-0 bg-[linear-gradient(transparent_50%,rgba(0,0,0,0.1)_50%)] bg-[length:100%_4px] pointer-events-none opacity-20" />

        <CardContent className="p-4 h-full flex flex-col relative">
          {/* Header */}
          <div className="flex items-start gap-3 mb-3">
            {/* Profile picture with tier border */}
            <div
              className="w-16 h-16 rounded-full overflow-hidden border-2 flex-shrink-0 shadow-lg"
              style={{
                borderColor: isMember ? memberColor : "#00ff00",
                boxShadow: isMember ? `0 0 15px ${memberColor}40` : "0 0 15px rgba(0,255,0,0.2)"
              }}
            >
              {user.pfpUrl ? (
                <img src={user.pfpUrl} alt="" className="w-full h-full object-cover" />
              ) : (
                <div className="w-full h-full bg-[#00ff00]/20 flex items-center justify-center">
                  <UserIcon size={24} className="text-[#00ff00]" />
                </div>
              )}
            </div>

            {/* Identity */}
            <div className="flex-1 min-w-0">
              <P className="font-mono font-bold text-lg leading-tight truncate" style={{ color: memberColor }}>
                {user.displayName || user.username || "Anonymous"}
              </P>
              {user.username && (
                <Small className="font-mono truncate block" style={{ color: memberColor, opacity: 0.6 }}>@{user.username}</Small>
              )}

              {isMember && memberData ? (
                <div className="mt-1 flex flex-col gap-0.5">
                  <span className="text-[10px] font-mono font-bold tracking-wider" style={{ color: memberColor }}>
                    {isAgent ? (
                      <>MEMBER <span style={{ color: "#B794F4" }}>· AGENT</span></>
                    ) : (
                      "MEMBER"
                    )}
                  </span>
                  <span className="text-[9px] font-mono" style={{ color: isAgent ? "#B794F4" : "#00ff00", opacity: 0.7 }}>
                    {memberData.ensSubname}
                  </span>
                </div>
              ) : (
                <div className="mt-1">
                  <span className="text-[10px] font-mono text-gray-500 tracking-wider">
                    GUEST ACCESS
                  </span>
                </div>
              )}
            </div>

            {/* QR Code */}
            <div className="flex-shrink-0 opacity-80">
              <QRCodeDisplay data={profileUrl || user.address || "guest"} size={50} />
            </div>
          </div>

          {/* Badges row */}
          <div className="flex flex-wrap items-center gap-2 mb-3">
            {rank > 0 && (
              <div className="inline-flex items-center gap-1 px-2 py-0.5 rounded bg-[#00ff00]/20 border border-[#00ff00]/30">
                <TrophyIcon size={12} className="text-[#00ff00]" />
                <span className="text-[10px] font-mono text-[#00ff00] font-bold">#{rank}</span>
              </div>
            )}
          </div>

          {/* Achievement preview */}
          {achievements.length > 0 && (
            <div className="mb-3">
              <AchievementGrid earnedIds={achievements} showLocked={false} maxDisplay={5} />
            </div>
          )}

          {/* Stats Grid */}
          <div className="grid grid-cols-3 gap-2 mt-auto">
            <div className="flex flex-col items-center justify-center p-2 rounded-lg bg-black/50 border border-[#00ff00]/20">
              <P className="text-lg font-bold text-[#00ff00] font-mono leading-none text-center">
                {stats.uploads}
              </P>
              <Small className="text-[9px] text-gray-500 font-mono uppercase tracking-wider text-center">Uploads</Small>
            </div>
            <div className="flex flex-col items-center justify-center p-2 rounded-lg bg-black/50 border border-[#00ff00]/20">
              <P className="text-lg font-bold text-[#00ff00] font-mono leading-none text-center">
                {(stats.bytesUploaded / (1024 * 1024)).toFixed(1)}
              </P>
              <Small className="text-[9px] text-gray-500 font-mono uppercase tracking-wider text-center">Data (MB)</Small>
            </div>
            <div className="flex flex-col items-center justify-center p-2 rounded-lg bg-black/50 border border-[#00ff00]/20">
              <P className="text-lg font-bold text-[#00ff00] font-mono leading-none text-center">
                {stats.tipsGiven}
              </P>
              <Small className="text-[9px] text-gray-500 font-mono uppercase tracking-wider text-center">Upvotes</Small>
            </div>
          </div>
        </CardContent>

        {/* Footer */}
        <div className="px-4 py-2 border-t border-[#00ff00]/20 bg-black/30">
          <div className="flex items-center justify-between gap-2">
            <span className="text-sm font-mono text-[#00ff00]/50 tracking-wide shrink-0">
              {toBraille(user.username || "guest")}
            </span>

            {/* Unlimited Pass Badge - Premium holographic style with occasional glimmer */}
            {hasStackPass && (
              <div className="relative flex items-center gap-1.5 px-2 py-0.5 rounded-full bg-gradient-to-r from-purple-500/20 via-[#00ff00]/20 to-purple-500/20 border border-purple-500/40 shrink-0 overflow-hidden">
                {/* Glimmer effect - sweeps on load, then occasionally */}
                <div
                  className="absolute inset-0 bg-gradient-to-r from-transparent via-white/30 to-transparent"
                  style={{
                    animation: 'glimmer-initial 0.6s ease-out forwards, glimmer-repeat 5s ease-in-out 1s infinite',
                  }}
                />
                <span className="text-[10px] relative z-10">∞</span>
                <span className="text-[8px] font-mono font-bold bg-gradient-to-r from-purple-400 via-[#00ff00] to-purple-400 bg-clip-text text-transparent tracking-wider uppercase relative z-10">
                  UNLIMITED
                </span>
                <style jsx>{`
                  @keyframes glimmer-initial {
                    0% {
                      transform: translateX(-100%);
                    }
                    100% {
                      transform: translateX(100%);
                    }
                  }
                  @keyframes glimmer-repeat {
                    0%, 85%, 100% {
                      transform: translateX(-100%);
                    }
                    92% {
                      transform: translateX(100%);
                    }
                  }
                `}</style>
              </div>
            )}

            {/* Show WID for web users, FID for Farcaster users */}
            <span className={`text-[8px] font-mono tracking-widest shrink-0 ${
              user.signupPlatform === "web" ? "text-yellow-400/60" :
              user.signupPlatform === "base-app" ? "text-blue-400/60" :
              "text-purple-400/60"
            }`}>
              {user.wid ? `WID-${user.wid}` :
               user.fid ? `FID-${user.fid}` :
               'NET LIBRARY'}
            </span>
          </div>
        </div>
      </Card>
    </div>
  );

  // Back of card (member details)
  const CardBack = () => (
    <div
      className="absolute inset-0"
      style={{ backfaceVisibility: "hidden", transform: "rotateY(180deg)" }}
    >
      <Card
        className="h-full border-2 overflow-hidden"
        style={{ borderColor: isMember ? `${memberColor}50` : "#00ff0030", backgroundColor: "#0a0a0a" }}
      >
        <div className="h-1" style={{ backgroundColor: isMember ? memberColor : "#00ff00" }} />
        <CardContent className="p-4 h-full flex flex-col justify-center">
          {isMember && memberData ? (
            <>
              <div className="text-center mb-4">
                <Small className="text-[#00ff00] font-mono uppercase tracking-wider">Member Since</Small>
                <P className="text-white font-mono text-lg mt-1">
                  {new Date(memberData.joinedAt).toLocaleDateString("en-US", {
                    month: "long",
                    day: "numeric",
                    year: "numeric"
                  })}
                </P>
              </div>

              <div className="text-center mb-4">
                <Small className="text-gray-500 font-mono uppercase tracking-wider text-[10px]">Member ID</Small>
                <P className="text-[#00ff00] font-mono font-bold text-2xl">
                  #{memberData.memberId}
                </P>
                {/* Show platform-specific ID */}
                <P className={`font-mono font-bold text-sm mt-1 ${
                  user.signupPlatform === "web" ? "text-yellow-400" :
                  user.signupPlatform === "base-app" ? "text-blue-400" :
                  "text-purple-400"
                }`}>
                  {user.wid ? `WID ${user.wid}` :
                   user.fid ? `FID ${user.fid}` :
                   null}
                </P>
              </div>

              <div className="space-y-2 text-center">
                <Small className="text-gray-500 font-mono text-[10px] uppercase tracking-wider">Wallet</Small>
                <P className="text-[#00ff00]/70 font-mono text-xs break-all">
                  {user.address}
                </P>
              </div>

              {/* Net Library Crest watermark */}
              <div className="absolute bottom-4 right-4 opacity-10">
                <svg viewBox="0 0 40 50" className="w-12 h-auto">
                  <path
                    d="M 20,1 L 39,7 L 39,25 Q 39,42 20,49 Q 1,42 1,25 L 1,7 Z"
                    fill="none"
                    stroke="#00ff00"
                    strokeWidth="1"
                  />
                  <g transform="translate(20, 22)" stroke="#00ff00" fill="none" strokeWidth="1">
                    <path d="M -8,-6 L -8,6 Q -4,5 0,6 L 0,-6 Q -4,-5 -8,-6" />
                    <path d="M 8,-6 L 8,6 Q 4,5 0,6 L 0,-6 Q 4,-5 8,-6" />
                  </g>
                </svg>
              </div>
            </>
          ) : (
            <div className="text-center">
              <div className="w-20 h-20 mx-auto mb-4 rounded-full bg-[#00ff00]/10 flex items-center justify-center border-2 border-dashed border-[#00ff00]/30">
                <LibraryIcon size={32} className="text-[#00ff00]" />
              </div>
              <P className="text-[#00ff00] font-mono mb-2">Become a Member</P>
              <Small className="text-gray-500 font-mono block mb-4">
                Get your ENS subname, unlock tiers, and earn badges!
              </Small>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );

  return (
    <div className="space-y-2">
      {/* Flip hint */}
      <div className="flex justify-center">
        <Small className="text-gray-600 font-mono text-[10px]">TAP CARD TO FLIP</Small>
      </div>

      {/* Flippable card */}
      <div
        ref={cardRef}
        className="relative h-[320px] cursor-pointer"
        onClick={() => setIsFlipped(!isFlipped)}
        style={{ perspective: "1000px" }}
      >
        <div
          className="relative w-full h-full transition-transform duration-500"
          style={{
            transformStyle: "preserve-3d",
            transform: isFlipped ? "rotateY(180deg)" : "rotateY(0deg)"
          }}
        >
          <CardFront />
          <CardBack />
        </div>
      </div>

      {/* Action button */}
      {isMember ? (
        <button
          onClick={(e) => {
            e.stopPropagation();
            onShare?.();
          }}
          className="w-full py-2 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] text-xs font-mono uppercase tracking-wider hover:bg-[#00ff00]/20 hover:shadow-[0_0_15px_rgba(0,255,0,0.3)] transition-all"
        >
          Share Profile
        </button>
      ) : (
        <button
          onClick={(e) => {
            e.stopPropagation();
            onBecomeMember?.();
          }}
          className="w-full py-2 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] text-xs font-mono uppercase tracking-wider hover:bg-[#00ff00]/20 hover:shadow-[0_0_15px_rgba(0,255,0,0.3)] transition-all"
        >
          Become a Net Library Member!
        </button>
      )}
    </div>
  );
}
src/features/app/components/file-preview-modal.tsx
"use client";

import { useState, useEffect, useMemo } from "react";
import { P, Small, H3 } from "@neynar/ui";
import { DocumentIcon, ImageIcon, AudioIcon, VideoIcon, NoteIcon, PackageIcon } from "@/components/icons/net-library-icons";

// Content types we support
export type PreviewContentType = "pdf" | "image" | "audio" | "video" | "text" | "unknown";

// Detect content type from file
export function detectContentType(file: File): PreviewContentType {
  const mimeType = (file.type || '').toLowerCase();
  const fileName = (file.name || '').toLowerCase();

  // PDF
  if (mimeType === "application/pdf" || fileName.endsWith(".pdf")) {
    return "pdf";
  }

  // Images
  if (mimeType.startsWith("image/") || /\.(jpg|jpeg|png|gif|webp|svg|bmp)$/.test(fileName)) {
    return "image";
  }

  // Audio
  if (mimeType.startsWith("audio/") || /\.(mp3|wav|ogg|m4a|aac|flac)$/.test(fileName)) {
    return "audio";
  }

  // Video
  if (mimeType.startsWith("video/") || /\.(mp4|webm|mov|avi|mkv)$/.test(fileName)) {
    return "video";
  }

  // Text files
  if (
    mimeType.startsWith("text/") ||
    mimeType === "application/json" ||
    /\.(txt|md|json|csv|xml|html|css|js|ts|tsx|jsx)$/.test(fileName)
  ) {
    return "text";
  }

  // EPUB (will be converted to PDF)
  if (mimeType === "application/epub+zip" || fileName.endsWith(".epub")) {
    return "pdf"; // Treat as PDF since we convert it
  }

  return "unknown";
}

// Get icon for content type
export function ContentTypeIcon({ type, size = 16 }: { type: PreviewContentType; size?: number }) {
  switch (type) {
    case "pdf": return <DocumentIcon size={size} />;
    case "image": return <ImageIcon size={size} />;
    case "audio": return <AudioIcon size={size} />;
    case "video": return <VideoIcon size={size} />;
    case "text": return <NoteIcon size={size} />;
    default: return <PackageIcon size={size} />;
  }
}

// Get label for content type
export function getContentTypeLabel(type: PreviewContentType): string {
  switch (type) {
    case "pdf": return "Document";
    case "image": return "Image";
    case "audio": return "Audio";
    case "video": return "Video";
    case "text": return "Text File";
    default: return "File";
  }
}

interface FilePreviewModalProps {
  file: File;
  isOpen: boolean;
  onClose: () => void;
  onContinue: () => void;
}

export function FilePreviewModal({
  file,
  isOpen,
  onClose,
  onContinue,
}: FilePreviewModalProps) {
  const contentType = useMemo(() => detectContentType(file), [file]);
  const [thumbnailUrl, setThumbnailUrl] = useState<string | null>(null);
  const [textPreview, setTextPreview] = useState<string>("");

  // Create thumbnail URL for images/videos
  useEffect(() => {
    if (!file || !isOpen) return;

    // Only create object URL for images
    if (contentType === "image") {
      const url = URL.createObjectURL(file);
      setThumbnailUrl(url);
      return () => {
        URL.revokeObjectURL(url);
        setThumbnailUrl(null);
      };
    }

    // For text files, read first few lines
    if (contentType === "text") {
      const reader = new FileReader();
      reader.onload = (e) => {
        const text = e.target?.result as string || "";
        // Show first 200 chars as preview
        setTextPreview(text.slice(0, 200) + (text.length > 200 ? "..." : ""));
      };
      reader.readAsText(file.slice(0, 1000)); // Only read first 1KB for preview
    }
  }, [file, isOpen, contentType]);

  if (!isOpen) return null;

  // Format file size
  const formatSize = (bytes: number) => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  };

  // Render compact thumbnail based on content type
  const renderThumbnail = () => {
    switch (contentType) {
      case "image":
        return thumbnailUrl ? (
          <img
            src={thumbnailUrl}
            alt={file.name}
            className="w-full h-full object-cover"
          />
        ) : (
          <ImageIcon size={36} className="text-[#00ff00]" />
        );

      case "pdf":
        return (
          <div className="flex flex-col items-center justify-center">
            <DocumentIcon size={36} className="text-[#00ff00] mb-1" />
            <Small className="text-gray-400 font-mono text-[10px]">PDF</Small>
          </div>
        );

      case "audio":
        return (
          <div className="flex flex-col items-center justify-center">
            <AudioIcon size={36} className="text-purple-400 mb-1" />
            <Small className="text-gray-400 font-mono text-[10px]">Audio</Small>
          </div>
        );

      case "video":
        return (
          <div className="flex flex-col items-center justify-center">
            <VideoIcon size={36} className="text-yellow-400 mb-1" />
            <Small className="text-gray-400 font-mono text-[10px]">Video</Small>
          </div>
        );

      case "text":
        return (
          <div className="flex flex-col items-center justify-center p-2 overflow-hidden">
            <NoteIcon size={32} className="text-gray-400 mb-1" />
            {textPreview && (
              <div className="text-[8px] text-gray-500 font-mono leading-tight overflow-hidden max-h-12 text-center">
                {textPreview.slice(0, 60)}...
              </div>
            )}
          </div>
        );

      default:
        return <PackageIcon size={36} className="text-gray-400" />;
    }
  };

  return (
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/90"
      onClick={onClose}
    >
      <div
        className="w-full max-w-sm bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 py-3 border-b border-[#00ff00]/20">
          <H3 className="text-[#00ff00] font-mono tracking-tight text-sm text-center">
            Upload This File?
          </H3>
        </div>

        {/* Content - Compact Preview */}
        <div className="p-4">
          <div className="flex items-center gap-4">
            {/* Thumbnail */}
            <div className="w-20 h-20 shrink-0 rounded-lg bg-[#1a1a1a] border border-[#00ff00]/20 flex items-center justify-center overflow-hidden">
              {renderThumbnail()}
            </div>

            {/* File Info */}
            <div className="flex-1 min-w-0">
              <P className="text-white font-mono text-sm truncate mb-1">
                {file.name}
              </P>
              <div className="flex items-center gap-2 flex-wrap">
                <span className="px-2 py-0.5 rounded-full bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] font-mono text-[10px] inline-flex items-center gap-1">
                  <ContentTypeIcon type={contentType} size={12} /> {getContentTypeLabel(contentType)}
                </span>
                <Small className="text-gray-500 font-mono text-[10px]">
                  {formatSize(file.size)}
                </Small>
              </div>
              <Small className="text-gray-600 font-mono text-[10px] mt-1 block truncate">
                {file.type || "Unknown type"}
              </Small>
            </div>
          </div>
        </div>

        {/* Footer with actions */}
        <div className="px-4 py-3 border-t border-[#00ff00]/20 flex gap-3">
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation();
              e.preventDefault();
              onClose();
            }}
            className="flex-1 py-2.5 rounded-lg bg-[#1a1a1a] border border-gray-700 text-gray-300 font-mono text-sm hover:bg-[#222] transition-colors"
          >
            Cancel
          </button>
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation();
              e.preventDefault();
              onContinue();
            }}
            className="flex-1 py-2.5 rounded-lg bg-[#00ff00] text-black font-mono font-bold text-sm hover:bg-[#00ff00]/90 transition-colors"
          >
            Continue →
          </button>
        </div>
      </div>
    </div>
  );
}
src/features/app/components/folder-tree-view.tsx
"use client";

import { useState, useMemo } from "react";
import { Small } from "@neynar/ui";
import type { FileTreeNode } from "@/features/app/types-filesystem";
import {
  FolderIcon,
  DocumentIcon,
  ImageIcon,
  AudioIcon,
  VideoIcon,
  ChevronDownIcon,
} from "@/components/icons/net-library-icons";

// Custom ChevronRightIcon since it might not exist
function ChevronRight({ size = 24, ...props }: { size?: number } & React.SVGProps<SVGSVGElement>) {
  return (
    <svg
      width={size}
      height={size}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth={2}
      strokeLinecap="round"
      strokeLinejoin="round"
      {...props}
    >
      <polyline points="9,6 15,12 9,18" />
    </svg>
  );
}

interface FolderTreeViewProps {
  nodes: FileTreeNode[];
  onFileClick: (contentKey: string) => void;
  expandedByDefault?: boolean;
  /** Set of paths that are excluded (will show dimmed + strikethrough) */
  excludedPaths?: Set<string>;
  /** Called when user clicks exclude/include toggle on a file */
  onToggleExclude?: (path: string) => void;
}

/**
 * Format file size in human-readable format
 */
function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

/**
 * Get icon component based on MIME type
 */
function getFileIcon(mimeType?: string) {
  if (!mimeType) return DocumentIcon;

  if (mimeType.startsWith("image/")) return ImageIcon;
  if (mimeType.startsWith("audio/")) return AudioIcon;
  if (mimeType.startsWith("video/")) return VideoIcon;
  if (mimeType === "application/pdf") return DocumentIcon;
  if (mimeType.startsWith("text/")) return DocumentIcon;

  return DocumentIcon;
}

/**
 * Count total files in a tree node (recursive)
 */
function countFilesInNode(node: FileTreeNode): number {
  if (!node.isDirectory) return 1;
  return node.children.reduce((sum, child) => sum + countFilesInNode(child), 0);
}

/**
 * Collect all folder paths from nodes (for expanding all by default)
 */
function collectAllFolderPaths(nodes: FileTreeNode[], paths: Set<string> = new Set()): Set<string> {
  for (const node of nodes) {
    if (node.isDirectory) {
      paths.add(node.path);
      collectAllFolderPaths(node.children, paths);
    }
  }
  return paths;
}

/**
 * Single tree node component (recursive)
 */
function TreeNode({
  node,
  depth,
  expanded,
  onToggle,
  onFileClick,
  excludedPaths,
  onToggleExclude,
}: {
  node: FileTreeNode;
  depth: number;
  expanded: Set<string>;
  onToggle: (path: string) => void;
  onFileClick: (contentKey: string) => void;
  excludedPaths?: Set<string>;
  onToggleExclude?: (path: string) => void;
}) {
  const isExpanded = expanded.has(node.path);
  const FileIcon = getFileIcon(node.mimeType);
  const fileCount = node.isDirectory ? countFilesInNode(node) : 0;
  const isExcluded = excludedPaths?.has(node.path) ?? false;

  return (
    <div>
      {/* Node row */}
      <div
        className={`
          flex items-center gap-2 py-1.5 px-2 rounded-md cursor-pointer
          hover:bg-[#1a1a1a] transition-colors
          ${!node.isDirectory && node.contentKey ? "hover:text-[#00ff00]" : ""}
          ${isExcluded ? "opacity-50" : ""}
        `}
        style={{ paddingLeft: `${depth * 20 + 8}px` }}
        onClick={() => {
          if (node.isDirectory) {
            onToggle(node.path);
          } else if (node.contentKey) {
            onFileClick(node.contentKey);
          }
        }}
      >
        {/* Expand/collapse chevron for folders */}
        {node.isDirectory ? (
          <span className="text-[#666] w-4 h-4 flex items-center justify-center">
            {isExpanded ? (
              <ChevronDownIcon size={14} />
            ) : (
              <ChevronRight size={14} />
            )}
          </span>
        ) : (
          <span className="w-4" /> // Spacer for alignment
        )}

        {/* Icon */}
        <span className={node.isDirectory ? "text-[#f59e0b]" : "text-[#888]"}>
          {node.isDirectory ? (
            <FolderIcon size={16} />
          ) : (
            <FileIcon size={16} />
          )}
        </span>

        {/* Name */}
        <span className={`flex-1 truncate font-mono text-sm text-[#ccc] ${isExcluded ? "line-through" : ""}`}>
          {node.name}
          {node.isDirectory && "/"}
        </span>

        {/* Exclude/include toggle for files */}
        {!node.isDirectory && onToggleExclude && (
          <button
            type="button"
            onClick={(e) => {
              e.stopPropagation();
              onToggleExclude(node.path);
            }}
            className={`
              px-1.5 py-0.5 rounded text-[10px] font-mono transition-colors
              ${isExcluded
                ? "bg-[#333] text-gray-400 hover:bg-[#444] hover:text-white"
                : "bg-red-500/20 text-red-400 hover:bg-red-500/30"
              }
            `}
          >
            {isExcluded ? "include" : "exclude"}
          </button>
        )}

        {/* File count for folders or size for files */}
        <Small className="text-[#666] text-xs whitespace-nowrap">
          {node.isDirectory ? (
            `${fileCount} file${fileCount !== 1 ? "s" : ""}`
          ) : (
            node.size !== undefined ? formatFileSize(node.size) : ""
          )}
        </Small>
      </div>

      {/* Children (if expanded) */}
      {node.isDirectory && isExpanded && (
        <div>
          {node.children.map((child) => (
            <TreeNode
              key={child.path}
              node={child}
              depth={depth + 1}
              expanded={expanded}
              onToggle={onToggle}
              onFileClick={onFileClick}
              excludedPaths={excludedPaths}
              onToggleExclude={onToggleExclude}
            />
          ))}
        </div>
      )}
    </div>
  );
}

/**
 * FolderTreeView - Renders a collapsible folder/file tree
 */
export function FolderTreeView({
  nodes,
  onFileClick,
  expandedByDefault = false,
  excludedPaths,
  onToggleExclude,
}: FolderTreeViewProps) {
  // Initialize expanded state
  const initialExpanded = useMemo(() => {
    if (expandedByDefault) {
      return collectAllFolderPaths(nodes);
    }
    return new Set<string>();
  }, [nodes, expandedByDefault]);

  const [expanded, setExpanded] = useState<Set<string>>(initialExpanded);

  const handleToggle = (path: string) => {
    setExpanded((prev) => {
      const next = new Set(prev);
      if (next.has(path)) {
        next.delete(path);
      } else {
        next.add(path);
      }
      return next;
    });
  };

  if (nodes.length === 0) {
    return (
      <div className="text-center py-8 text-[#666]">
        <Small>No files in this folder</Small>
      </div>
    );
  }

  return (
    <div className="bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg p-2 font-mono">
      {nodes.map((node) => (
        <TreeNode
          key={node.path}
          node={node}
          depth={0}
          expanded={expanded}
          onToggle={handleToggle}
          onFileClick={onFileClick}
          excludedPaths={excludedPaths}
          onToggleExclude={onToggleExclude}
        />
      ))}
    </div>
  );
}

src/features/app/components/folder-upload-modal.tsx
"use client";

import { useState, useCallback, useRef, useEffect } from "react";
import { P, Small, H3 } from "@neynar/ui";
import {
  FolderIcon,
  UploadIcon,
  WarningIcon,
  CheckCircleIcon,
  CloseIcon,
} from "@/components/icons/net-library-icons";
import {
  type FileSystemItem,
  type FileTreeNode,
  buildFileTree,
  shouldIgnorePath,
} from "@/features/app/types-filesystem";
import { FolderTreeView } from "./folder-tree-view";
import {
  FREE_TIER_MEMBER_MAX_SIZE,
  FREE_TIER_NON_MEMBER_MAX_SIZE,
} from "@/lib/net-protocol";

// ============================================
// Types
// ============================================

interface FileWithPath {
  file: File;
  path: string;
  fileName: string;
  parentPath: string;
}

interface FolderUploadModalProps {
  isOpen: boolean;
  onClose: () => void;
  isMember: boolean;
  onUploadFile: (
    file: File,
    metadata: {
      path: string;
      fileName: string;
      fileSize: number;
      mimeType: string;
    }
  ) => Promise<{ success: boolean; contentKey?: string; error?: string }>;
  onComplete: () => void;
  initialFiles?: File[] | null; // Pre-loaded files from drag-and-drop, skip file selection
}

type UploadStep = "select" | "preview" | "uploading" | "complete";

// ============================================
// Helpers
// ============================================

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function getParentPath(path: string): string {
  const lastSlash = path.lastIndexOf("/");
  if (lastSlash <= 0) return "/";
  return path.substring(0, lastSlash);
}

function getMimeType(file: File): string {
  if (file.type) return file.type;
  // Fallback based on extension
  const ext = file.name.split(".").pop()?.toLowerCase();
  const mimeMap: Record<string, string> = {
    txt: "text/plain",
    md: "text/markdown",
    json: "application/json",
    js: "text/javascript",
    ts: "text/typescript",
    tsx: "text/typescript",
    jsx: "text/javascript",
    html: "text/html",
    css: "text/css",
    pdf: "application/pdf",
    png: "image/png",
    jpg: "image/jpeg",
    jpeg: "image/jpeg",
    gif: "image/gif",
    webp: "image/webp",
    svg: "image/svg+xml",
    mp3: "audio/mpeg",
    wav: "audio/wav",
    mp4: "video/mp4",
    webm: "video/webm",
  };
  return mimeMap[ext || ""] || "application/octet-stream";
}

// ============================================
// Component
// ============================================

export function FolderUploadModal({
  isOpen,
  onClose,
  isMember,
  onUploadFile,
  onComplete,
  initialFiles,
}: FolderUploadModalProps) {
  const [step, setStep] = useState<UploadStep>("select");
  const [files, setFiles] = useState<FileWithPath[]>([]);
  const [excludedPaths, setExcludedPaths] = useState<Set<string>>(new Set());
  const [uploadProgress, setUploadProgress] = useState({ current: 0, total: 0, currentFile: "" });
  const [uploadResults, setUploadResults] = useState<{ success: number; failed: number; errors: string[] }>({
    success: 0,
    failed: 0,
    errors: [],
  });
  const [isDragging, setIsDragging] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const abortRef = useRef(false);
  const initialFilesProcessedRef = useRef(false);

  const maxFileSize = isMember ? FREE_TIER_MEMBER_MAX_SIZE : FREE_TIER_NON_MEMBER_MAX_SIZE;

  // Reset state when modal closes
  const handleClose = useCallback(() => {
    abortRef.current = true;
    setStep("select");
    setFiles([]);
    setExcludedPaths(new Set());
    setUploadProgress({ current: 0, total: 0, currentFile: "" });
    setUploadResults({ success: 0, failed: 0, errors: [] });
    onClose();
  }, [onClose]);

  // Process selected files from input or drop
  const processFiles = useCallback((fileList: FileList) => {
    const processed: FileWithPath[] = [];

    for (let i = 0; i < fileList.length; i++) {
      const file = fileList[i];
      // webkitRelativePath gives us the full path including folder name
      const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;

      // Normalize path to start with /
      const path = relativePath.startsWith("/") ? relativePath : "/" + relativePath;

      // Skip ignored paths
      if (shouldIgnorePath(path)) continue;

      processed.push({
        file,
        path,
        fileName: file.name,
        parentPath: getParentPath(path),
      });
    }

    if (processed.length > 0) {
      setFiles(processed);
      setStep("preview");
    }
  }, []);

  // Process files from an array (for initialFiles from drag-drop)
  const processFilesArray = useCallback((fileArray: File[]) => {
    const processed: FileWithPath[] = [];

    for (const file of fileArray) {
      // webkitRelativePath gives us the full path including folder name
      const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;

      // Normalize path to start with /
      const path = relativePath.startsWith("/") ? relativePath : "/" + relativePath;

      // Skip ignored paths
      if (shouldIgnorePath(path)) continue;

      processed.push({
        file,
        path,
        fileName: file.name,
        parentPath: getParentPath(path),
      });
    }

    if (processed.length > 0) {
      setFiles(processed);
      setStep("preview");
    }
  }, []);

  // Auto-process initial files when provided (from drag-and-drop)
  useEffect(() => {
    if (isOpen && initialFiles && initialFiles.length > 0 && !initialFilesProcessedRef.current) {
      console.log("[FolderUploadModal] Processing", initialFiles.length, "initial files");
      initialFilesProcessedRef.current = true;
      processFilesArray(initialFiles);
    }
  }, [isOpen, initialFiles, processFilesArray]);

  // Reset the processed ref when modal closes
  useEffect(() => {
    if (!isOpen) {
      initialFilesProcessedRef.current = false;
    }
  }, [isOpen]);

  // Handle file input change
  const handleFileInputChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      if (e.target.files && e.target.files.length > 0) {
        processFiles(e.target.files);
      }
    },
    [processFiles]
  );

  // Handle drag events
  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
  }, []);

  const handleDrop = useCallback(
    async (e: React.DragEvent) => {
      e.preventDefault();
      e.stopPropagation();
      setIsDragging(false);

      const items = e.dataTransfer.items;
      if (!items) return;

      // Collect all files from dropped items
      const allFiles: File[] = [];

      const readEntry = async (entry: FileSystemEntry, path: string): Promise<void> => {
        if (entry.isFile) {
          const fileEntry = entry as FileSystemFileEntry;
          return new Promise((resolve) => {
            fileEntry.file((file) => {
              // Create a new file with the path embedded
              Object.defineProperty(file, "webkitRelativePath", {
                value: path + "/" + file.name,
                writable: false,
              });
              allFiles.push(file);
              resolve();
            });
          });
        } else if (entry.isDirectory) {
          const dirEntry = entry as FileSystemDirectoryEntry;
          const reader = dirEntry.createReader();
          return new Promise((resolve) => {
            reader.readEntries(async (entries) => {
              for (const childEntry of entries) {
                await readEntry(childEntry, path + "/" + entry.name);
              }
              resolve();
            });
          });
        }
      };

      for (let i = 0; i < items.length; i++) {
        const item = items[i];
        const entry = item.webkitGetAsEntry?.();
        if (entry) {
          await readEntry(entry, "");
        }
      }

      if (allFiles.length > 0) {
        // Convert to FileList-like structure
        const dataTransfer = new DataTransfer();
        allFiles.forEach((f) => dataTransfer.items.add(f));
        processFiles(dataTransfer.files);
      }
    },
    [processFiles]
  );

  // Toggle file exclusion
  const toggleExclude = useCallback((path: string) => {
    setExcludedPaths((prev) => {
      const next = new Set(prev);
      if (next.has(path)) {
        next.delete(path);
      } else {
        next.add(path);
      }
      return next;
    });
  }, []);

  // Build tree for preview (show ALL files, exclusion state is visual)
  const previewTree = useCallback((): FileTreeNode[] => {
    const items: FileSystemItem[] = files
      .map((f) => ({
        contentKey: "", // Not uploaded yet
        addedAt: Date.now(),
        addedBy: "",
        path: f.path,
        fileName: f.fileName,
        fileSize: f.file.size,
        mimeType: getMimeType(f.file),
        isDirectory: false,
        parentPath: f.parentPath,
      }));

    return buildFileTree(items);
  }, [files]);

  // Get files that exceed size limit
  const oversizedFiles = files.filter(
    (f) => !excludedPaths.has(f.path) && f.file.size > maxFileSize
  );

  // Get included files
  const includedFiles = files.filter((f) => !excludedPaths.has(f.path));
  const totalSize = includedFiles.reduce((sum, f) => sum + f.file.size, 0);

  // Start upload process
  const startUpload = useCallback(async () => {
    abortRef.current = false;
    setStep("uploading");

    const toUpload = files.filter((f) => !excludedPaths.has(f.path));
    setUploadProgress({ current: 0, total: toUpload.length, currentFile: "" });

    const results = { success: 0, failed: 0, errors: [] as string[] };

    for (let i = 0; i < toUpload.length; i++) {
      if (abortRef.current) break;

      const { file, path, fileName } = toUpload[i];
      setUploadProgress({
        current: i + 1,
        total: toUpload.length,
        currentFile: path,
      });

      try {
        const result = await onUploadFile(file, {
          path,
          fileName,
          fileSize: file.size,
          mimeType: getMimeType(file),
        });

        if (result.success) {
          results.success++;
        } else {
          results.failed++;
          results.errors.push(`${fileName}: ${result.error || "Unknown error"}`);
        }
      } catch (err) {
        results.failed++;
        results.errors.push(`${fileName}: ${err instanceof Error ? err.message : "Upload failed"}`);
      }
    }

    setUploadResults(results);
    setStep("complete");
  }, [files, excludedPaths, onUploadFile]);

  // Handle completion
  const handleComplete = useCallback(() => {
    onComplete();
    handleClose();
  }, [onComplete, handleClose]);

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/90"
      onClick={handleClose}
    >
      <div
        className="w-full max-w-md bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl overflow-hidden max-h-[80vh] flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 py-3 border-b border-[#00ff00]/20 flex items-center justify-between shrink-0">
          <H3 className="text-[#00ff00] font-mono tracking-tight text-sm">
            {step === "select" && "Select Folder"}
            {step === "preview" && "Review Files"}
            {step === "uploading" && "Uploading..."}
            {step === "complete" && "Upload Complete"}
          </H3>
          <button
            type="button"
            onClick={handleClose}
            className="text-gray-500 hover:text-white transition-colors"
          >
            <CloseIcon size={20} />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-4">
          {/* Step 1: Select Folder */}
          {step === "select" && (
            <div className="space-y-4">
              {/* Drag and drop zone */}
              <div
                className={`
                  border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors
                  ${isDragging ? "border-[#00ff00] bg-[#00ff00]/10" : "border-[#333] hover:border-[#00ff00]/50"}
                `}
                onDragOver={handleDragOver}
                onDragLeave={handleDragLeave}
                onDrop={handleDrop}
                onClick={() => fileInputRef.current?.click()}
              >
                <FolderIcon size={48} className="mx-auto mb-4 text-[#00ff00]/60" />
                <P className="text-white font-mono text-sm mb-2">
                  Drag & drop a folder here
                </P>
                <Small className="text-gray-500">
                  or click to browse
                </Small>
              </div>

              {/* Hidden file input with webkitdirectory */}
              <input
                ref={fileInputRef}
                type="file"
                className="hidden"
                /* @ts-expect-error webkitdirectory is non-standard but widely supported */
                webkitdirectory="true"
                directory="true"
                multiple
                onChange={handleFileInputChange}
              />

              <Small className="text-gray-600 text-center block">
                Files like .git, node_modules, and .env will be automatically excluded
              </Small>
            </div>
          )}

          {/* Step 2: Preview */}
          {step === "preview" && (
            <div className="space-y-4">
              {/* Summary stats */}
              <div className="grid grid-cols-3 gap-2 text-center">
                <div className="bg-[#1a1a1a] rounded-lg p-2">
                  <P className="text-[#00ff00] font-mono text-lg font-bold">
                    {includedFiles.length}
                  </P>
                  <Small className="text-gray-500">Files</Small>
                </div>
                <div className="bg-[#1a1a1a] rounded-lg p-2">
                  <P className="text-[#00ff00] font-mono text-lg font-bold">
                    {formatFileSize(totalSize)}
                  </P>
                  <Small className="text-gray-500">Total Size</Small>
                </div>
                <div className="bg-[#1a1a1a] rounded-lg p-2">
                  <P className="text-[#00ff00] font-mono text-lg font-bold">
                    {includedFiles.length}
                  </P>
                  <Small className="text-gray-500">Transactions</Small>
                </div>
              </div>

              {/* Oversized files warning */}
              {oversizedFiles.length > 0 && (
                <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-3">
                  <div className="flex items-start gap-2">
                    <WarningIcon size={16} className="text-yellow-500 shrink-0 mt-0.5" />
                    <div>
                      <P className="text-yellow-500 font-mono text-xs font-bold mb-1">
                        {oversizedFiles.length} file(s) exceed the {formatFileSize(maxFileSize)} limit
                      </P>
                      <Small className="text-yellow-500/70">
                        {oversizedFiles.slice(0, 3).map((f) => f.fileName).join(", ")}
                        {oversizedFiles.length > 3 && ` and ${oversizedFiles.length - 3} more`}
                      </Small>
                    </div>
                  </div>
                </div>
              )}

              {/* File tree */}
              <div className="max-h-64 overflow-y-auto">
                <FolderTreeView
                  nodes={previewTree()}
                  onFileClick={() => {}}
                  expandedByDefault={files.length < 50}
                  excludedPaths={excludedPaths}
                  onToggleExclude={toggleExclude}
                />
              </div>

              {/* Excluded files count */}
              {excludedPaths.size > 0 && (
                <Small className="text-gray-500 text-center block">
                  {excludedPaths.size} file(s) excluded from upload
                </Small>
              )}
            </div>
          )}

          {/* Step 3: Uploading */}
          {step === "uploading" && (
            <div className="space-y-4">
              <div className="text-center">
                <P className="text-white font-mono text-sm mb-2">
                  Uploading file {uploadProgress.current} of {uploadProgress.total}
                </P>
                <Small className="text-gray-500 truncate block">
                  {uploadProgress.currentFile}
                </Small>
              </div>

              {/* Progress bar */}
              <div className="h-2 bg-[#1a1a1a] rounded-full overflow-hidden">
                <div
                  className="h-full bg-[#00ff00] transition-all duration-300"
                  style={{
                    width: `${uploadProgress.total > 0 ? Math.round((uploadProgress.current / uploadProgress.total) * 100) : 0}%`,
                  }}
                />
              </div>

              <Small className="text-gray-600 text-center block">
                Please keep this window open until upload completes
              </Small>
            </div>
          )}

          {/* Step 4: Complete */}
          {step === "complete" && (
            <div className="space-y-4 text-center">
              <CheckCircleIcon size={48} className="mx-auto text-[#00ff00]" />
              <P className="text-white font-mono text-sm">
                Upload Complete!
              </P>

              <div className="grid grid-cols-2 gap-2">
                <div className="bg-[#1a1a1a] rounded-lg p-3">
                  <P className="text-[#00ff00] font-mono text-xl font-bold">
                    {uploadResults.success}
                  </P>
                  <Small className="text-gray-500">Succeeded</Small>
                </div>
                <div className="bg-[#1a1a1a] rounded-lg p-3">
                  <P className={`font-mono text-xl font-bold ${uploadResults.failed > 0 ? "text-red-500" : "text-gray-500"}`}>
                    {uploadResults.failed}
                  </P>
                  <Small className="text-gray-500">Failed</Small>
                </div>
              </div>

              {uploadResults.errors.length > 0 && (
                <div className="bg-red-500/10 border border-red-500/30 rounded-lg p-3 text-left max-h-32 overflow-y-auto">
                  <Small className="text-red-500 font-mono">
                    {uploadResults.errors.slice(0, 5).map((err, i) => (
                      <div key={i} className="truncate">{err}</div>
                    ))}
                    {uploadResults.errors.length > 5 && (
                      <div className="text-red-500/70">
                        ...and {uploadResults.errors.length - 5} more errors
                      </div>
                    )}
                  </Small>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-4 py-3 border-t border-[#00ff00]/20 shrink-0">
          {step === "select" && (
            <button
              type="button"
              onClick={handleClose}
              className="w-full py-2.5 rounded-lg bg-[#1a1a1a] border border-gray-700 text-gray-300 font-mono text-sm hover:bg-[#222] transition-colors"
            >
              Cancel
            </button>
          )}

          {step === "preview" && (
            <div className="flex gap-3">
              <button
                type="button"
                onClick={() => setStep("select")}
                className="flex-1 py-2.5 rounded-lg bg-[#1a1a1a] border border-gray-700 text-gray-300 font-mono text-sm hover:bg-[#222] transition-colors"
              >
                Back
              </button>
              <button
                type="button"
                onClick={startUpload}
                disabled={includedFiles.length === 0}
                className="flex-1 py-2.5 rounded-lg bg-[#00ff00] text-black font-mono font-bold text-sm hover:bg-[#00ff00]/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                <UploadIcon size={16} />
                Upload {includedFiles.length} Files
              </button>
            </div>
          )}

          {step === "uploading" && (
            <button
              type="button"
              onClick={() => {
                abortRef.current = true;
              }}
              className="w-full py-2.5 rounded-lg bg-red-500/20 border border-red-500/30 text-red-500 font-mono text-sm hover:bg-red-500/30 transition-colors"
            >
              Cancel Upload
            </button>
          )}

          {step === "complete" && (
            <button
              type="button"
              onClick={handleComplete}
              className="w-full py-2.5 rounded-lg bg-[#00ff00] text-black font-mono font-bold text-sm hover:bg-[#00ff00]/90 transition-colors"
            >
              Done
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

src/features/app/components/github-import-modal.tsx
"use client";

import { useState, useCallback, useRef, useMemo } from "react";
import { P, Small, H3 } from "@neynar/ui";
import {
  CloseIcon,
  UploadIcon,
  WarningIcon,
  CheckCircleIcon,
  LinkIcon,
  RefreshIcon,
} from "@/components/icons/net-library-icons";
import {
  type FileSystemItem,
  type FileTreeNode,
  buildFileTree,
  shouldIgnorePath,
} from "@/features/app/types-filesystem";
import { FolderTreeView } from "./folder-tree-view";
import {
  FREE_TIER_MEMBER_MAX_SIZE,
  FREE_TIER_NON_MEMBER_MAX_SIZE,
} from "@/lib/net-protocol";

// ============================================
// Types
// ============================================

interface GitHubTreeEntry {
  path: string;
  type: "file" | "directory";
  size: number;
  sha: string | null;
  downloadUrl: string | null;
}

interface GitHubTreeResponse {
  success: boolean;
  repo: string;
  branch: string;
  tree: GitHubTreeEntry[];
  totalFiles: number;
  totalSize: number;
  truncated: boolean;
  note?: string;
  error?: string;
}

interface GitHubImportModalProps {
  isOpen: boolean;
  onClose: () => void;
  isMember: boolean;
  onUploadFile: (
    file: File,
    metadata: {
      path: string;
      fileName: string;
      fileSize: number;
      mimeType: string;
    }
  ) => Promise<{ success: boolean; contentKey?: string; error?: string }>;
  onComplete: () => void;
  onSetSourceMeta?: (meta: { sourceUrl: string; sourceCommit?: string }) => void;
}

type ImportStep = "input" | "preview" | "importing" | "complete";

// ============================================
// Helpers
// ============================================

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function getMimeType(path: string): string {
  const ext = path.split(".").pop()?.toLowerCase();
  const mimeMap: Record<string, string> = {
    txt: "text/plain",
    md: "text/markdown",
    json: "application/json",
    js: "text/javascript",
    ts: "text/typescript",
    tsx: "text/typescript",
    jsx: "text/javascript",
    html: "text/html",
    css: "text/css",
    pdf: "application/pdf",
    png: "image/png",
    jpg: "image/jpeg",
    jpeg: "image/jpeg",
    gif: "image/gif",
    webp: "image/webp",
    svg: "image/svg+xml",
    mp3: "audio/mpeg",
    wav: "audio/wav",
    mp4: "video/mp4",
    webm: "video/webm",
    yaml: "text/yaml",
    yml: "text/yaml",
    xml: "text/xml",
    sh: "text/x-shellscript",
    py: "text/x-python",
    rb: "text/x-ruby",
    go: "text/x-go",
    rs: "text/x-rust",
    toml: "text/x-toml",
  };
  return mimeMap[ext || ""] || "application/octet-stream";
}

function getParentPath(path: string): string {
  const lastSlash = path.lastIndexOf("/");
  if (lastSlash <= 0) return "/";
  return "/" + path.substring(0, lastSlash);
}

/**
 * Parse GitHub URL into components
 * Supports:
 * - https://github.com/owner/repo
 * - https://github.com/owner/repo/tree/branch
 * - https://github.com/owner/repo/tree/branch/path/to/folder
 */
function parseGitHubUrl(url: string): {
  owner: string;
  repo: string;
  branch?: string;
  path?: string;
} | null {
  try {
    const parsed = new URL(url);
    if (parsed.hostname !== "github.com") return null;

    const parts = parsed.pathname.split("/").filter(Boolean);
    if (parts.length < 2) return null;

    const owner = parts[0];
    const repo = parts[1];

    // Check for /tree/branch/path pattern
    if (parts[2] === "tree" && parts[3]) {
      const branch = parts[3];
      const path = parts.slice(4).join("/") || undefined;
      return { owner, repo, branch, path };
    }

    // Just owner/repo
    return { owner, repo };
  } catch {
    return null;
  }
}

// ============================================
// Component
// ============================================

export function GitHubImportModal({
  isOpen,
  onClose,
  isMember,
  onUploadFile,
  onComplete,
  onSetSourceMeta,
}: GitHubImportModalProps) {
  const [step, setStep] = useState<ImportStep>("input");
  const [url, setUrl] = useState("");
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Tree data from GitHub
  const [treeData, setTreeData] = useState<GitHubTreeResponse | null>(null);
  const [excludedPaths, setExcludedPaths] = useState<Set<string>>(new Set());

  // Upload state
  const [uploadProgress, setUploadProgress] = useState({ current: 0, total: 0, currentFile: "" });
  const [uploadResults, setUploadResults] = useState<{ success: number; failed: number; errors: string[] }>({
    success: 0,
    failed: 0,
    errors: [],
  });

  const abortRef = useRef(false);
  const maxFileSize = isMember ? FREE_TIER_MEMBER_MAX_SIZE : FREE_TIER_NON_MEMBER_MAX_SIZE;

  // Reset state when modal closes
  const handleClose = useCallback(() => {
    abortRef.current = true;
    setStep("input");
    setUrl("");
    setError(null);
    setTreeData(null);
    setExcludedPaths(new Set());
    setUploadProgress({ current: 0, total: 0, currentFile: "" });
    setUploadResults({ success: 0, failed: 0, errors: [] });
    onClose();
  }, [onClose]);

  // Fetch repository tree
  const fetchTree = useCallback(async () => {
    setError(null);
    setIsLoading(true);

    const parsed = parseGitHubUrl(url.trim());
    if (!parsed) {
      setError("Invalid GitHub URL. Expected format: https://github.com/owner/repo");
      setIsLoading(false);
      return;
    }

    try {
      const params = new URLSearchParams({
        repo: `${parsed.owner}/${parsed.repo}`,
      });
      if (parsed.branch) params.set("branch", parsed.branch);
      if (parsed.path) params.set("path", parsed.path);

      const response = await fetch(`/api/v1/github-tree?${params}`);
      const data = (await response.json()) as GitHubTreeResponse;

      if (!data.success) {
        setError(data.error || "Failed to fetch repository");
        setIsLoading(false);
        return;
      }

      setTreeData(data);
      setStep("preview");
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to fetch repository");
    } finally {
      setIsLoading(false);
    }
  }, [url]);

  // Toggle file exclusion
  const toggleExclude = useCallback((path: string) => {
    // Remove leading slash for matching with tree data paths
    const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
    setExcludedPaths((prev) => {
      const next = new Set(prev);
      if (next.has(normalizedPath)) {
        next.delete(normalizedPath);
      } else {
        next.add(normalizedPath);
      }
      return next;
    });
  }, []);

  // Build tree for preview (show ALL files, exclusion state is visual)
  const buildPreviewTree = useCallback((): FileTreeNode[] => {
    if (!treeData) return [];

    const items: FileSystemItem[] = treeData.tree
      .filter((entry) => {
        // Only filter out auto-ignored paths (node_modules, .git, etc.)
        if (shouldIgnorePath(entry.path)) return false;
        return true;
      })
      .map((entry) => ({
        contentKey: entry.sha || "",
        addedAt: Date.now(),
        addedBy: "",
        path: "/" + entry.path,
        fileName: entry.path.split("/").pop() || entry.path,
        fileSize: entry.size,
        mimeType: entry.type === "file" ? getMimeType(entry.path) : undefined,
        isDirectory: entry.type === "directory",
        parentPath: getParentPath(entry.path),
      }));

    return buildFileTree(items);
  }, [treeData]);

  // Get included files (for stats and upload) - memoized to prevent unnecessary recalcs
  const includedFiles = useMemo(() => {
    return treeData?.tree.filter(
      (entry) =>
        entry.type === "file" &&
        !excludedPaths.has(entry.path) &&
        !shouldIgnorePath(entry.path)
    ) || [];
  }, [treeData, excludedPaths]);

  const totalSize = includedFiles.reduce((sum, f) => sum + f.size, 0);
  const oversizedFiles = includedFiles.filter((f) => f.size > maxFileSize);

  // Fetch actual commit SHA from GitHub API
  const fetchCommitSha = useCallback(async (owner: string, repo: string, branch: string): Promise<string | null> => {
    try {
      const response = await fetch(`https://api.github.com/repos/${owner}/${repo}/commits/${branch}`, {
        headers: {
          Accept: "application/vnd.github.v3+json",
          "User-Agent": "Net-Library-App",
        },
      });
      if (!response.ok) return null;
      const data = await response.json();
      return data.sha || null;
    } catch {
      return null;
    }
  }, []);

  // Start import process
  const startImport = useCallback(async () => {
    if (!treeData) return;

    abortRef.current = false;
    setStep("importing");

    const filesToImport = includedFiles.filter((f) => f.downloadUrl);
    setUploadProgress({ current: 0, total: filesToImport.length, currentFile: "" });

    const results = { success: 0, failed: 0, errors: [] as string[] };

    // Set source metadata with actual commit SHA
    if (onSetSourceMeta) {
      const [owner, repo] = treeData.repo.split("/");
      const commitSha = await fetchCommitSha(owner, repo, treeData.branch);
      onSetSourceMeta({
        sourceUrl: `https://github.com/${treeData.repo}`,
        sourceCommit: commitSha || undefined,
      });
    }

    for (let i = 0; i < filesToImport.length; i++) {
      if (abortRef.current) break;

      const entry = filesToImport[i];
      const fileName = entry.path.split("/").pop() || entry.path;

      setUploadProgress({
        current: i + 1,
        total: filesToImport.length,
        currentFile: entry.path,
      });

      try {
        // Fetch file content from GitHub
        const response = await fetch(entry.downloadUrl!);
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}`);
        }

        const blob = await response.blob();
        const file = new File([blob], fileName, { type: getMimeType(entry.path) });

        // Upload via callback
        const result = await onUploadFile(file, {
          path: "/" + entry.path,
          fileName,
          fileSize: entry.size,
          mimeType: getMimeType(entry.path),
        });

        if (result.success) {
          results.success++;
        } else {
          results.failed++;
          results.errors.push(`${fileName}: ${result.error || "Upload failed"}`);
        }
      } catch (err) {
        results.failed++;
        results.errors.push(`${fileName}: ${err instanceof Error ? err.message : "Download failed"}`);
      }
    }

    setUploadResults(results);
    setStep("complete");
  }, [treeData, includedFiles, onUploadFile, onSetSourceMeta, fetchCommitSha]);

  // Handle completion
  const handleComplete = useCallback(() => {
    onComplete();
    handleClose();
  }, [onComplete, handleClose]);

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/90"
      onClick={handleClose}
    >
      <div
        className="w-full max-w-md bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl overflow-hidden max-h-[80vh] flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 py-3 border-b border-[#00ff00]/20 flex items-center justify-between shrink-0">
          <H3 className="text-[#00ff00] font-mono tracking-tight text-sm flex items-center gap-2">
            <svg className="w-4 h-4" viewBox="0 0 24 24" fill="currentColor">
              <path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z" />
            </svg>
            {step === "input" && "Import from GitHub"}
            {step === "preview" && "Review Files"}
            {step === "importing" && "Importing..."}
            {step === "complete" && "Import Complete"}
          </H3>
          <button
            type="button"
            onClick={handleClose}
            className="text-gray-500 hover:text-white transition-colors"
          >
            <CloseIcon size={20} />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-4">
          {/* Step 1: URL Input */}
          {step === "input" && (
            <div className="space-y-4">
              <div>
                <label className="block text-gray-400 font-mono text-xs mb-2">
                  GitHub Repository URL
                </label>
                <div className="flex gap-2">
                  <input
                    type="url"
                    value={url}
                    onChange={(e) => setUrl(e.target.value)}
                    placeholder="https://github.com/owner/repo"
                    className="flex-1 px-3 py-2 bg-[#1a1a1a] border border-[#333] rounded-lg text-white font-mono text-sm placeholder:text-gray-600 focus:outline-none focus:border-[#00ff00]/50"
                  />
                </div>
              </div>

              {/* URL format help */}
              <div className="bg-[#1a1a1a] rounded-lg p-3">
                <Small className="text-gray-500 block mb-2">Supported URL formats:</Small>
                <div className="space-y-1 text-xs font-mono text-gray-600">
                  <div>• github.com/owner/repo</div>
                  <div>• github.com/owner/repo/tree/branch</div>
                  <div>• github.com/owner/repo/tree/branch/path</div>
                </div>
              </div>

              {/* Rate limit warning */}
              <div className="flex items-start gap-2 text-yellow-500/70">
                <WarningIcon size={14} className="shrink-0 mt-0.5" />
                <Small>
                  GitHub allows 60 requests per hour without authentication. Large repos may require multiple requests.
                </Small>
              </div>

              {/* Error message */}
              {error && (
                <div className="bg-red-500/10 border border-red-500/30 rounded-lg p-3">
                  <Small className="text-red-500">{error}</Small>
                </div>
              )}
            </div>
          )}

          {/* Step 2: Preview */}
          {step === "preview" && treeData && (
            <div className="space-y-4">
              {/* Repo info */}
              <div className="bg-[#1a1a1a] rounded-lg p-3">
                <div className="flex items-center gap-2 mb-2">
                  <LinkIcon size={14} className="text-[#00ff00]" />
                  <P className="text-white font-mono text-sm font-bold">{treeData.repo}</P>
                </div>
                <Small className="text-gray-500">
                  Branch: {treeData.branch}
                </Small>
              </div>

              {/* Summary stats */}
              <div className="grid grid-cols-3 gap-2 text-center">
                <div className="bg-[#1a1a1a] rounded-lg p-2">
                  <P className="text-[#00ff00] font-mono text-lg font-bold">
                    {includedFiles.length}
                  </P>
                  <Small className="text-gray-500">Files</Small>
                </div>
                <div className="bg-[#1a1a1a] rounded-lg p-2">
                  <P className="text-[#00ff00] font-mono text-lg font-bold">
                    {formatFileSize(totalSize)}
                  </P>
                  <Small className="text-gray-500">Total Size</Small>
                </div>
                <div className="bg-[#1a1a1a] rounded-lg p-2">
                  <P className="text-[#00ff00] font-mono text-lg font-bold">
                    {includedFiles.length}
                  </P>
                  <Small className="text-gray-500">Transactions</Small>
                </div>
              </div>

              {/* Truncation warning */}
              {treeData.truncated && (
                <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-3">
                  <div className="flex items-start gap-2">
                    <WarningIcon size={16} className="text-yellow-500 shrink-0 mt-0.5" />
                    <Small className="text-yellow-500">
                      {treeData.note || "Repository tree was truncated. Some files may be missing."}
                    </Small>
                  </div>
                </div>
              )}

              {/* Oversized files warning */}
              {oversizedFiles.length > 0 && (
                <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-3">
                  <div className="flex items-start gap-2">
                    <WarningIcon size={16} className="text-yellow-500 shrink-0 mt-0.5" />
                    <div>
                      <P className="text-yellow-500 font-mono text-xs font-bold mb-1">
                        {oversizedFiles.length} file(s) exceed the {formatFileSize(maxFileSize)} limit
                      </P>
                      <Small className="text-yellow-500/70">
                        {oversizedFiles.slice(0, 3).map((f) => f.path.split("/").pop()).join(", ")}
                        {oversizedFiles.length > 3 && ` and ${oversizedFiles.length - 3} more`}
                      </Small>
                    </div>
                  </div>
                </div>
              )}

              {/* File tree */}
              <div className="max-h-48 overflow-y-auto">
                <FolderTreeView
                  nodes={buildPreviewTree()}
                  onFileClick={() => {}}
                  expandedByDefault={includedFiles.length < 30}
                  excludedPaths={new Set(Array.from(excludedPaths).map(p => "/" + p))}
                  onToggleExclude={toggleExclude}
                />
              </div>

              {/* Excluded files count */}
              {excludedPaths.size > 0 && (
                <Small className="text-gray-500 text-center block">
                  {excludedPaths.size} file(s) excluded from import
                </Small>
              )}
            </div>
          )}

          {/* Step 3: Importing */}
          {step === "importing" && (
            <div className="space-y-4">
              <div className="text-center">
                <P className="text-white font-mono text-sm mb-2">
                  Importing file {uploadProgress.current} of {uploadProgress.total}
                </P>
                <Small className="text-gray-500 truncate block">
                  {uploadProgress.currentFile}
                </Small>
              </div>

              {/* Progress bar */}
              <div className="h-2 bg-[#1a1a1a] rounded-full overflow-hidden">
                <div
                  className="h-full bg-[#00ff00] transition-all duration-300"
                  style={{
                    width: `${uploadProgress.total > 0 ? Math.round((uploadProgress.current / uploadProgress.total) * 100) : 0}%`,
                  }}
                />
              </div>

              <Small className="text-gray-600 text-center block">
                Downloading from GitHub and uploading to Net Protocol...
              </Small>
            </div>
          )}

          {/* Step 4: Complete */}
          {step === "complete" && (
            <div className="space-y-4 text-center">
              <CheckCircleIcon size={48} className="mx-auto text-[#00ff00]" />
              <P className="text-white font-mono text-sm">
                Import Complete!
              </P>

              <div className="grid grid-cols-2 gap-2">
                <div className="bg-[#1a1a1a] rounded-lg p-3">
                  <P className="text-[#00ff00] font-mono text-xl font-bold">
                    {uploadResults.success}
                  </P>
                  <Small className="text-gray-500">Succeeded</Small>
                </div>
                <div className="bg-[#1a1a1a] rounded-lg p-3">
                  <P className={`font-mono text-xl font-bold ${uploadResults.failed > 0 ? "text-red-500" : "text-gray-500"}`}>
                    {uploadResults.failed}
                  </P>
                  <Small className="text-gray-500">Failed</Small>
                </div>
              </div>

              {uploadResults.errors.length > 0 && (
                <div className="bg-red-500/10 border border-red-500/30 rounded-lg p-3 text-left max-h-32 overflow-y-auto">
                  <Small className="text-red-500 font-mono">
                    {uploadResults.errors.slice(0, 5).map((err, i) => (
                      <div key={i} className="truncate">{err}</div>
                    ))}
                    {uploadResults.errors.length > 5 && (
                      <div className="text-red-500/70">
                        ...and {uploadResults.errors.length - 5} more errors
                      </div>
                    )}
                  </Small>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-4 py-3 border-t border-[#00ff00]/20 shrink-0">
          {step === "input" && (
            <div className="flex gap-3">
              <button
                type="button"
                onClick={handleClose}
                className="flex-1 py-2.5 rounded-lg bg-[#1a1a1a] border border-gray-700 text-gray-300 font-mono text-sm hover:bg-[#222] transition-colors"
              >
                Cancel
              </button>
              <button
                type="button"
                onClick={fetchTree}
                disabled={!url.trim() || isLoading}
                className="flex-1 py-2.5 rounded-lg bg-[#00ff00] text-black font-mono font-bold text-sm hover:bg-[#00ff00]/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                {isLoading ? (
                  <>
                    <RefreshIcon size={16} className="animate-spin" />
                    Fetching...
                  </>
                ) : (
                  <>
                    Fetch Repository
                  </>
                )}
              </button>
            </div>
          )}

          {step === "preview" && (
            <div className="flex gap-3">
              <button
                type="button"
                onClick={() => setStep("input")}
                className="flex-1 py-2.5 rounded-lg bg-[#1a1a1a] border border-gray-700 text-gray-300 font-mono text-sm hover:bg-[#222] transition-colors"
              >
                Back
              </button>
              <button
                type="button"
                onClick={startImport}
                disabled={includedFiles.length === 0}
                className="flex-1 py-2.5 rounded-lg bg-[#00ff00] text-black font-mono font-bold text-sm hover:bg-[#00ff00]/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                <UploadIcon size={16} />
                Import {includedFiles.length} Files
              </button>
            </div>
          )}

          {step === "importing" && (
            <button
              type="button"
              onClick={() => {
                abortRef.current = true;
              }}
              className="w-full py-2.5 rounded-lg bg-red-500/20 border border-red-500/30 text-red-500 font-mono text-sm hover:bg-red-500/30 transition-colors"
            >
              Cancel Import
            </button>
          )}

          {step === "complete" && (
            <button
              type="button"
              onClick={handleComplete}
              className="w-full py-2.5 rounded-lg bg-[#00ff00] text-black font-mono font-bold text-sm hover:bg-[#00ff00]/90 transition-colors"
            >
              Done
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

src/features/app/components/grid-archive-modal.tsx
"use client";

import { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { useAccount } from "wagmi";
import { useFarcasterLaunchParams } from "@/neynar-farcaster-sdk/mini";
import {
  useGridArchive,
  generateArchivePNG,
  loadImageAsDataUrl,
} from "@/hooks/use-grid-archive";
import { useRelayUploadV2 } from "@/hooks/use-relay-upload-v2";
import type { GridCell, GridWithStats, ArchivedGrid } from "@/lib/net-protocol";
import { MoneyIcon } from "@/components/icons/net-library-icons";

interface GridArchiveModalProps {
  isOpen: boolean;
  onClose: () => void;
  grid: GridWithStats;
  cells: GridCell[];
  onArchived?: (archive: ArchivedGrid) => void;
}

type ArchiveStep = "preview" | "generating" | "uploading" | "complete";

export function GridArchiveModal({
  isOpen,
  onClose,
  grid,
  cells,
  onArchived,
}: GridArchiveModalProps) {
  const { address } = useAccount();
  const farcasterLaunchParams = useFarcasterLaunchParams();
  const { createArchive } = useGridArchive({ autoFetch: false });
  const { uploadFile } = useRelayUploadV2();

  const [step, setStep] = useState<ArchiveStep>("preview");
  const [progress, setProgress] = useState(0);
  const [error, setError] = useState<string | null>(null);
  const [archiveResult, setArchiveResult] = useState<ArchivedGrid | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [needsFunding, setNeedsFunding] = useState(false);

  // Reset state when modal opens
  useEffect(() => {
    if (isOpen) {
      setStep("preview");
      setProgress(0);
      setError(null);
      setArchiveResult(null);
      setPreviewUrl(null);
      setNeedsFunding(false);
    }
  }, [isOpen]);

  // Use portal to render modal at document root
  const [mounted, setMounted] = useState(false);
  useEffect(() => {
    setMounted(true);
  }, []);

  if (!isOpen || !mounted) return null;

  const handleArchive = async () => {
    if (!address) return;

    setStep("generating");
    setProgress(0);
    setError(null);
    setNeedsFunding(false);

    try {
      // Step 1: Load all cell images (0-25% of progress)
      const cellImageUrls = new Map<string, string>();
      const cellsToLoad = cells.filter((c) => c.cdnUrl);
      let loaded = 0;

      for (const cell of cellsToLoad) {
        const dataUrl = await loadImageAsDataUrl(cell.cdnUrl);
        if (dataUrl) {
          cellImageUrls.set(`${cell.row}-${cell.col}`, dataUrl);
        }
        loaded++;
        setProgress(Math.round((loaded / cellsToLoad.length) * 25));
      }

      // Step 2: Generate PNG (25-50%)
      setProgress(30);
      const pngBlob = await generateArchivePNG(
        grid.name,
        grid.size,
        cells,
        cellImageUrls
      );
      setProgress(50);

      // Create preview URL for display
      const previewBlobUrl = URL.createObjectURL(pngBlob);
      setPreviewUrl(previewBlobUrl);

      // Step 3: Upload to KV as cover art (50-60%)
      setStep("uploading");
      setProgress(55);

      // Convert blob to base64 data URL for KV storage
      const blobToDataUrl = (blob: Blob): Promise<string> => {
        return new Promise((resolve, reject) => {
          const reader = new FileReader();
          reader.onloadend = () => resolve(reader.result as string);
          reader.onerror = reject;
          reader.readAsDataURL(blob);
        });
      };
      const pngDataUrl = await blobToDataUrl(pngBlob);

      // Upload cover to KV for thumbnails/sharing
      let coverUrl: string | undefined;
      try {
        const coverKey = `grid-archive-${grid.id}-${Date.now()}`;
        const coverResponse = await fetch("/api/upload-cover", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ dataUrl: pngDataUrl, contentKey: coverKey }),
        });
        const coverResult = await coverResponse.json();
        if (coverResult.success && coverResult.url) {
          coverUrl = coverResult.url;
          console.log("[GridArchive] Cover uploaded to KV:", coverUrl);
        }
      } catch (e) {
        console.warn("[GridArchive] Cover upload failed (non-critical):", e);
      }
      setProgress(60);

      // Step 4: Upload PNG to Net Protocol via relay (60-85%)
      // Convert blob to File for upload
      const archiveFileName = `${(grid.name || 'grid').replace(/\s+/g, "-")}-archive-${Date.now()}.png`;
      const archiveFile = new File([pngBlob], archiveFileName, { type: "image/png" });

      // Get user info for metadata
      const fidString = farcasterLaunchParams?.get('fid');
      const fid = fidString ? parseInt(fidString, 10) : undefined;

      // Upload to Net Protocol with cover URL
      const uploadResult = await uploadFile(archiveFile, {
        title: `${grid.name} - Archive`,
        author: address,
        categories: ["grid-archive"],
        uploaderFid: fid,
        coverUrl, // Pass the KV-hosted cover URL
      });

      // Check if funding is needed
      if (!uploadResult.success && uploadResult.error === "NEEDS_FUNDING") {
        setNeedsFunding(true);
        setError("Please fund your Upload Wallet to archive this grid onchain.");
        setStep("preview");
        return;
      }

      if (!uploadResult.success) {
        throw new Error(uploadResult.error || "Failed to upload archive to Net Protocol");
      }

      setProgress(85);

      // Step 4: Create archive record with contentKey and CDN info (85-100%)
      const result = await createArchive(
        grid.id,
        address,
        uploadResult.contentKey, // Now we have the contentKey from relay upload!
        fid,
        {
          cdnUrl: uploadResult.cdnUrl, // Full CDN URL from upload
          fileName: archiveFileName, // Original filename for CDN URL generation
          operator: uploadResult.operator || address, // Backend wallet that wrote to chain
        }
      );

      if (!result) {
        throw new Error("Failed to create archive record");
      }

      setProgress(100);
      setArchiveResult(result.archive);
      setStep("complete");

      // Notify parent
      onArchived?.(result.archive);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Archive failed");
      setStep("preview");
    }
  };

  const handleClose = () => {
    // Clean up preview URL if exists
    if (previewUrl) {
      URL.revokeObjectURL(previewUrl);
    }
    onClose();
  };

  const handleDownload = () => {
    if (previewUrl) {
      const link = document.createElement("a");
      link.href = previewUrl;
      link.download = `${(grid.name || 'grid').replace(/\s+/g, "-")}-archive-${Date.now()}.png`;
      link.click();
    }
  };

  const modalContent = (
    <div className="fixed inset-0 z-[9999] flex items-start justify-center p-3 sm:p-4 pt-16 sm:pt-20 pb-20 sm:pb-24 bg-black/80 overflow-y-auto">
      <div className="w-full max-w-[calc(100%-1.5rem)] sm:max-w-md md:max-w-lg bg-[#0a0a0a] border border-[#1a1a1a] rounded-xl sm:rounded-2xl overflow-hidden max-h-[80vh] sm:max-h-[75vh] flex flex-col">
        {/* Header - responsive */}
        <div className="shrink-0 flex items-center p-3 sm:p-4 border-b border-[#1a1a1a]">
          <h2 className="text-[#00ff00] font-mono text-base sm:text-lg">
            {step === "preview" && "Archive Grid"}
            {step === "generating" && "Creating Archive..."}
            {step === "uploading" && "Uploading Onchain..."}
            {step === "complete" && "Archive Created"}
          </h2>
        </div>

        {/* Content - responsive padding */}
        <div className="flex-1 overflow-y-auto p-3 sm:p-4">
          {step === "preview" && (
            <PreviewStep grid={grid} cells={cells} error={error} needsFunding={needsFunding} />
          )}

          {step === "generating" && <GeneratingStep progress={progress} stepLabel="Preparing archive..." />}

          {step === "uploading" && <GeneratingStep progress={progress} stepLabel="Uploading to Net Protocol..." />}

          {step === "complete" && archiveResult && (
            <CompleteStep
              archive={archiveResult}
              previewUrl={previewUrl}
              onDownload={handleDownload}
            />
          )}
        </div>

        {/* Footer - responsive with touch targets */}
        <div className="shrink-0 p-3 sm:p-4 border-t border-[#1a1a1a] flex gap-2">
          {step === "preview" && (
            <>
              <button
                onClick={handleClose}
                className="flex-1 py-3.5 sm:py-3 rounded-lg font-mono text-sm bg-[#1a1a1a] text-gray-400 hover:text-white active:bg-[#2a2a2a] transition-colors min-h-[48px] sm:min-h-0"
              >
                Cancel
              </button>
              <button
                onClick={handleArchive}
                disabled={cells.length === 0}
                className="flex-1 py-3.5 sm:py-3 rounded-lg font-mono text-sm bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/20 active:bg-[#00ff00]/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed min-h-[48px] sm:min-h-0"
              >
                Create Archive
              </button>
            </>
          )}

          {(step === "generating" || step === "uploading") && (
            <div className="flex-1 text-center py-3">
              <span className="text-gray-400 font-mono text-sm">
                Please wait...
              </span>
            </div>
          )}

          {step === "complete" && (
            <>
              <button
                onClick={handleDownload}
                className="flex-1 py-3.5 sm:py-3 rounded-lg font-mono text-sm bg-[#1a1a1a] text-gray-400 hover:text-white active:bg-[#2a2a2a] transition-colors min-h-[48px] sm:min-h-0"
              >
                Download PNG
              </button>
              <button
                onClick={handleClose}
                className="flex-1 py-3.5 sm:py-3 rounded-lg font-mono text-sm bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/20 active:bg-[#00ff00]/30 transition-all min-h-[48px] sm:min-h-0"
              >
                Done
              </button>
            </>
          )}
        </div>
      </div>
    </div>
  );

  return createPortal(modalContent, document.body);
}

// Preview step - show what will be archived
function PreviewStep({
  grid,
  cells,
  error,
  needsFunding,
}: {
  grid: GridWithStats;
  cells: GridCell[];
  error: string | null;
  needsFunding: boolean;
}) {
  return (
    <div className="space-y-4">
      {/* Grid info */}
      <div className="p-3 rounded-lg bg-black border border-[#1a1a1a]">
        <h3 className="text-[#00ff00] font-mono text-sm mb-2">{grid.name}</h3>
        <div className="flex justify-between text-sm font-mono">
          <span className="text-gray-400">Size</span>
          <span className="text-gray-300">
            {grid.size}×{grid.size}
          </span>
        </div>
        <div className="flex justify-between text-sm font-mono mt-1">
          <span className="text-gray-400">Filled cells</span>
          <span className="text-gray-300">{cells.length}</span>
        </div>
      </div>

      {/* What happens */}
      <div className="space-y-2">
        <h4 className="text-gray-400 font-mono text-sm">What happens</h4>
        <div className="space-y-2 text-gray-500 font-mono text-xs">
          <div className="flex gap-2">
            <span className="text-[#00ff00]">1.</span>
            <span>Grid is rendered to a PNG image</span>
          </div>
          <div className="flex gap-2">
            <span className="text-[#00ff00]">2.</span>
            <span>Cell data is embedded in image metadata</span>
          </div>
          <div className="flex gap-2">
            <span className="text-[#00ff00]">3.</span>
            <span>Archive is uploaded to Net Protocol (onchain)</span>
          </div>
          <div className="flex gap-2">
            <span className="text-[#00ff00]">4.</span>
            <span>Permanent record created in your library</span>
          </div>
        </div>
      </div>

      {/* Info box */}
      <div className="p-3 rounded-lg bg-[#00ff00]/5 border border-[#00ff00]/20">
        <p className="text-gray-400 font-mono text-xs">
          Archives are stored permanently onchain. Your live grid remains fully
          editable after archiving.
        </p>
      </div>

      {/* Needs funding warning */}
      {needsFunding && (
        <div className="p-3 rounded-lg bg-purple-500/10 border border-purple-500/30">
          <p className="text-purple-400 font-mono text-sm mb-1 flex items-center gap-1.5"><MoneyIcon size={14} /> Upload Wallet Empty</p>
          <p className="text-gray-400 font-mono text-xs">
            Please fund your Upload Wallet in the Upload tab before archiving.
          </p>
        </div>
      )}

      {/* Error */}
      {error && !needsFunding && (
        <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30">
          <p className="text-red-400 font-mono text-sm">{error}</p>
        </div>
      )}

      {/* Warning if empty */}
      {cells.length === 0 && (
        <div className="p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30">
          <p className="text-yellow-400 font-mono text-sm">
            This grid is empty. Add some cells before archiving.
          </p>
        </div>
      )}
    </div>
  );
}

// Generating step - show progress
function GeneratingStep({ progress, stepLabel }: { progress: number; stepLabel?: string }) {
  // Determine step text based on progress
  const getStepText = () => {
    if (stepLabel) return stepLabel;
    if (progress < 25) return "Loading cell images...";
    if (progress < 50) return "Generating PNG...";
    if (progress < 85) return "Uploading to Net Protocol...";
    return "Finalizing...";
  };

  return (
    <div className="py-8 text-center">
      <div className="w-16 h-16 mx-auto mb-4 rounded-full border-4 border-[#1a1a1a] border-t-[#00ff00] animate-spin" />

      <div className="mb-4">
        <p className="text-[#00ff00] font-mono text-2xl">{progress}%</p>
      </div>

      <p className="text-gray-500 font-mono text-sm">
        {getStepText()}
      </p>

      {/* Progress bar */}
      <div className="mt-4 mx-8">
        <div className="h-1 bg-[#1a1a1a] rounded-full overflow-hidden">
          <div
            className="h-full bg-[#00ff00] transition-all duration-300"
            style={{ width: `${progress}%` }}
          />
        </div>
      </div>
    </div>
  );
}

// Complete step - show success
function CompleteStep({
  archive,
  previewUrl,
  onDownload: _onDownload,
}: {
  archive: ArchivedGrid;
  previewUrl: string | null;
  onDownload: () => void;
}) {
  return (
    <div className="space-y-4">
      {/* Success icon */}
      <div className="text-center py-4">
        <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-[#00ff00]/10 border border-[#00ff00]/30 flex items-center justify-center">
          <span className="text-3xl">✓</span>
        </div>
        <h3 className="text-[#00ff00] font-mono text-lg">Archive Created</h3>
      </div>

      {/* Preview image */}
      {previewUrl && (
        <div className="rounded-lg overflow-hidden border border-[#1a1a1a]">
          <img
            src={previewUrl}
            alt="Archive preview"
            className="w-full"
            style={{ imageRendering: "pixelated" }}
          />
        </div>
      )}

      {/* Archive details */}
      <div className="p-3 rounded-lg bg-black border border-[#1a1a1a]">
        <div className="flex justify-between text-sm font-mono mb-1">
          <span className="text-gray-400">Name</span>
          <span className="text-gray-300">{archive.gridName}</span>
        </div>
        <div className="flex justify-between text-sm font-mono mb-1">
          <span className="text-gray-400">Size</span>
          <span className="text-gray-300">
            {archive.gridSize}×{archive.gridSize}
          </span>
        </div>
        <div className="flex justify-between text-sm font-mono mb-1">
          <span className="text-gray-400">Cells</span>
          <span className="text-gray-300">{archive.cellCount}</span>
        </div>
        <div className="flex justify-between text-sm font-mono">
          <span className="text-gray-400">Archived</span>
          <span className="text-gray-300">
            {new Date(archive.archivedAt).toLocaleDateString()}
          </span>
        </div>
      </div>
    </div>
  );
}
src/features/app/components/grid-detail.tsx
"use client";

import { useState, useEffect, useRef, useCallback, useMemo } from "react";
import { createPortal } from "react-dom";
import { useAccount } from "wagmi";
import { useGrid } from "@/hooks/use-grids";
import { useUpvote, UPVOTE_COST_ETH } from "@/hooks/use-upvotes";
import { GridArchiveModal } from "./grid-archive-modal";
import { safeComposeCast, safeOpenUrl, useAppMode } from "@/lib/app-mode";
import type { GridCell, GridWithStats, GridMediaType, DiscoveryEntry } from "@/lib/net-protocol";
import { detectGridMediaType, getMediaTypeBorderColor, isPlayableMedia, getUserFriendlyCdnUrl, BASE_CHAIN_ID } from "@/lib/net-protocol";
import { useDiscoveryContext } from "@/contexts/discovery-context";
import { useGridArchive } from "@/hooks/use-grid-archive";
import { EditIcon, WarningIcon, TrashIcon, LibraryIcon, DocumentIcon, PlayIcon, PauseIcon, PencilIcon, ShareIcon, LinkIcon, ClipboardIcon, CheckIcon } from "@/components/icons/net-library-icons";

// Convert IPFS/Arweave URLs to gateway URLs for display
function toGatewayUrl(url: string): string {
  if (!url) return url;

  // IPFS URLs - support multiple formats
  if (url.startsWith("ipfs://")) {
    const cid = url.slice(7); // Remove "ipfs://"
    return `https://ipfs.io/ipfs/${cid}`;
  }

  // IPFS gateway URLs that need normalization
  if (url.includes("/ipfs/") && !url.startsWith("https://ipfs.io")) {
    const match = url.match(/\/ipfs\/(.+)/);
    if (match) {
      return `https://ipfs.io/ipfs/${match[1]}`;
    }
  }

  // Arweave URLs
  if (url.startsWith("ar://")) {
    const txId = url.slice(5); // Remove "ar://"
    return `https://arweave.net/${txId}`;
  }

  // Already HTTP(S) - return as-is
  return url;
}

// Build raw media URL for Net Protocol content
// Uses our media-proxy endpoint to serve with correct MIME type
// (Net Protocol storage doesn't preserve content-type headers)
function toRawMediaUrl(cell: GridCell): string {
  // If we have operator and contentKey, use our proxy endpoint
  // This ensures correct MIME type headers for audio/video playback
  if (cell.operator && cell.contentKey && cell.mediaType) {
    // Build URL with storageType to help the proxy reconstruct the content correctly
    // Most audio/video files use XML chunked storage
    const storageType = cell.storageType || "xml";
    return `/api/media-proxy?operator=${encodeURIComponent(cell.operator)}&contentKey=${encodeURIComponent(cell.contentKey)}&mediaType=${encodeURIComponent(cell.mediaType)}&storageType=${encodeURIComponent(storageType)}`;
  }

  // Try to extract operator/contentKey from existing cdnUrl patterns
  const url = cell.cdnUrl;

  // Already a raw storage URL - but this won't have correct content-type
  if (url.includes('/storage/raw/') || url.includes('/storage/load/')) {
    // Try to extract operator and contentKey to use proxy
    const match = url.match(/storage\/(?:raw|load)\/([^/]+)\/([^/?]+)/);
    if (match) {
      const [, operator, contentKey] = match;
      const storageType = cell.storageType || "xml";
      // Use mediaType if available, otherwise default to "audio" and let proxy detect from content
      const mediaType = cell.mediaType || "audio";
      return `/api/media-proxy?operator=${encodeURIComponent(operator)}&contentKey=${encodeURIComponent(contentKey)}&mediaType=${encodeURIComponent(mediaType)}&storageType=${encodeURIComponent(storageType)}`;
    }
    return url;
  }

  // /content/0x... URL - extract contentKey and use with cell's operator if available
  if (url.includes('storedon.net/content/')) {
    // Extract contentKey from URL
    const contentKeyMatch = url.match(/content\/(0x[a-fA-F0-9]+)/i);
    if (contentKeyMatch && cell.operator) {
      const extractedContentKey = contentKeyMatch[1];
      const storageType = cell.storageType || "xml";
      const mediaType = cell.mediaType || "audio";
      return `/api/media-proxy?operator=${encodeURIComponent(cell.operator)}&contentKey=${encodeURIComponent(extractedContentKey)}&mediaType=${encodeURIComponent(mediaType)}&storageType=${encodeURIComponent(storageType)}`;
    }
    // Can't convert without operator - return as-is (will fail to play)
    console.warn('[toRawMediaUrl] Cannot convert /content/ URL without operator:', url, 'cell.operator:', cell.operator);
    return url;
  }

  // Fall back to gateway URL conversion for non-Net Protocol URLs
  return toGatewayUrl(url);
}

// Preview component with loading/error states for AddCellModal
// Looks up metadata from discovery index to get cover art
function PreviewImage({
  url,
  onMetadataFound
}: {
  url: string;
  onMetadataFound?: (title: string, coverUrl: string, contentKey?: string, mediaType?: string, operator?: string, storageType?: string) => void;
}) {
  const [status, setStatus] = useState<"loading" | "loaded" | "error">("loading");
  const [imageUrl, setImageUrl] = useState<string | null>(null);
  const [metadata, setMetadata] = useState<{ title?: string; author?: string; mediaType?: string } | null>(null);

  // Fetch metadata when URL changes
  useEffect(() => {
    if (!url.trim()) {
      setStatus("loading");
      setImageUrl(null);
      setMetadata(null);
      return;
    }

    setStatus("loading");
    setImageUrl(null);
    setMetadata(null);

    // Look up metadata from discovery index
    fetch(`/api/lookup-cdn?url=${encodeURIComponent(url.trim())}`)
      .then((res) => res.json())
      .then((data) => {
        console.log("[PreviewImage] Lookup result for", url.slice(0, 50), ":", data);
        if (data.success && data.found && data.metadata) {
          const meta = data.metadata;
          console.log("[PreviewImage] Found metadata - mediaType:", meta.mediaType, "title:", meta.title);
          setMetadata({ title: meta.title, author: meta.author, mediaType: meta.mediaType });

          // Use cover art if available, otherwise try the URL directly
          const resolvedCoverUrl = meta.coverUrl || url.trim();
          if (meta.coverUrl) {
            setImageUrl(toGatewayUrl(meta.coverUrl));
          } else {
            // Fall back to trying the URL directly (for images)
            setImageUrl(toGatewayUrl(url.trim()));
          }

          // Auto-fill title, coverUrl, contentKey, mediaType, operator, storageType if callback provided
          // Call callback whenever we find metadata (operator/contentKey are critical for media playback)
          if (onMetadataFound) {
            onMetadataFound(meta.title || "", resolvedCoverUrl, meta.contentKey, meta.mediaType, meta.operator, meta.storageType);
          }
        } else {
          console.log("[PreviewImage] No metadata found for URL");
          // No metadata found - try using URL directly (might be a direct image link)
          setImageUrl(toGatewayUrl(url.trim()));
        }
      })
      .catch((err) => {
        console.error("[PreviewImage] Lookup error:", err);
        // Fallback to direct URL
        setImageUrl(toGatewayUrl(url.trim()));
      });
  }, [url, onMetadataFound]);

  return (
    <div>
      <label className="block text-gray-400 font-mono text-sm mb-2">
        Preview
      </label>
      <div className="w-24 h-24 rounded-lg overflow-hidden bg-black border border-[#1a1a1a] relative">
        {status === "loading" && !imageUrl && (
          <div className="absolute inset-0 flex items-center justify-center">
            <div className="w-5 h-5 border-2 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
          </div>
        )}
        {status === "error" && (
          <div className="absolute inset-0 flex items-center justify-center">
            <span className="text-red-400 text-xs font-mono text-center px-1">No cover</span>
          </div>
        )}
        {imageUrl && (
          <img
            src={imageUrl}
            alt="Preview"
            className={`w-full h-full object-cover transition-opacity ${status === "loaded" ? "opacity-100" : "opacity-0"}`}
            onLoad={() => setStatus("loaded")}
            onError={() => setStatus("error")}
          />
        )}
      </div>
      {/* Show metadata if found */}
      {metadata?.title && (
        <p className="text-[#00ff00]/70 font-mono text-[10px] mt-1 truncate max-w-[200px]">
          {metadata.title}
        </p>
      )}
      {/* Show mediaType if detected */}
      {metadata?.mediaType && (
        <p className="text-purple-400 font-mono text-[10px] mt-0.5">
          Type: {metadata.mediaType}
        </p>
      )}
    </div>
  );
}

interface GridDetailProps {
  gridId: string;
  onBack: () => void;
  /** Called when user wants to view the full item detail page for a grid cell */
  onViewItemDetail?: (contentKey: string) => void;
}

export function GridDetail({ gridId, onBack, onViewItemDetail }: GridDetailProps) {
  const { address, isConnected } = useAccount();
  const { grid, cells, isLoading, error, refresh } = useGrid(gridId, address);
  const { upvote, isUpvoting, isConfirmed, reset: resetUpvote } = useUpvote();
  const { archives, refresh: refreshArchives } = useGridArchive({ gridId });
  const appMode = useAppMode();
  const isBaseApp = appMode === "base-app";

  const [selectedCell, setSelectedCell] = useState<{ row: number; col: number } | null>(null);
  const [showAddCellModal, setShowAddCellModal] = useState(false);
  const [showArchiveModal, setShowArchiveModal] = useState(false);
  const [showEditModal, setShowEditModal] = useState(false);
  const [showShareMenu, setShowShareMenu] = useState(false);
  const [localUpvoteCount, setLocalUpvoteCount] = useState<number | null>(null);
  const [showCdnLinkModal, setShowCdnLinkModal] = useState(false);
  const [cdnLinkCopied, setCdnLinkCopied] = useState(false);

  // Get the latest archive (if any) for this grid
  const latestArchive = archives.length > 0 ? archives[0] : null; // Archives sorted by newest first

  // Build the CDN URL for the archived grid
  const archiveCdnUrl = latestArchive?.cdnUrl || (
    latestArchive?.fileName && latestArchive?.operator
      ? getUserFriendlyCdnUrl(BASE_CHAIN_ID, latestArchive.operator, latestArchive.fileName)
      : latestArchive?.contentKey && latestArchive?.operator
        ? `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${latestArchive.operator}/${latestArchive.contentKey}`
        : null
  );

  // Viewer mode state - for viewing media in full screen
  const [viewingCell, setViewingCell] = useState<GridCell | null>(null);
  const [viewingCellIndex, setViewingCellIndex] = useState<number>(0);

  // Edit Mode - owners start in View Mode by default, can toggle to Edit Mode
  const [editMode, setEditMode] = useState(false);

  const isOwner = grid && address && grid.creator && grid.creator.toLowerCase() === address.toLowerCase();

  // Get sorted list of filled cells for navigation (left-to-right, top-to-bottom)
  const sortedFilledCells = cells
    .filter(c => c.cdnUrl) // Only cells with content
    .sort((a, b) => a.row === b.row ? a.col - b.col : a.row - b.row);

  // Sync local upvote count with grid data
  useEffect(() => {
    if (grid) {
      setLocalUpvoteCount(grid.upvoteCount);
    }
  }, [grid]);

  // Handle successful upvote
  useEffect(() => {
    if (isConfirmed) {
      // Optimistically update local count
      setLocalUpvoteCount((prev) => (prev ?? 0) + 1);
      // Reset upvote state
      resetUpvote();
      // Refresh grid data to get actual count from contract
      setTimeout(() => refresh(), 2000);
    }
  }, [isConfirmed, resetUpvote, refresh]);

  const handleUpvote = async () => {
    if (!grid || !isConnected) return;

    // Use the grid ID as the storage key for upvotes
    // The operator is the grid creator (who receives the upvote "points")
    await upvote(grid.id, grid.creator, 1, `grid:${grid.id}`);
  };


  if (isLoading) {
    return (
      <div className="flex-1 flex items-center justify-center bg-[#0a0a0a]">
        <div className="w-10 h-10 border-2 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
      </div>
    );
  }

  if (error || !grid) {
    return (
      <div className="flex-1 flex flex-col items-center justify-center bg-[#0a0a0a] p-4">
        <p className="text-red-400 font-mono text-sm mb-4">{error || "Grid not found"}</p>
        <button
          onClick={onBack}
          className="px-4 py-2 rounded-lg font-mono text-sm bg-[#1a1a1a] text-gray-400"
        >
          Go Back
        </button>
      </div>
    );
  }

  const handleCellClick = (row: number, col: number) => {
    const cell = cells.find(c => c.row === row && c.col === col);

    // Edit Mode: owners can add/edit cells directly
    if (editMode && isOwner) {
      setSelectedCell({ row, col });
      setShowAddCellModal(true);
      return;
    }

    // View Mode (default): tap filled cells to view, empty cells do nothing for non-owners
    if (cell && cell.cdnUrl) {
      // Cell has content - open viewer
      const cellIndex = sortedFilledCells.findIndex(c => c.row === row && c.col === col);
      setViewingCellIndex(cellIndex >= 0 ? cellIndex : 0);
      setViewingCell(cell);
    }
    // In View Mode, tapping empty cells does nothing (owners must enable Edit Mode)
  };

  // Owner can edit a cell from the viewer
  const handleEditCell = (row: number, col: number) => {
    setViewingCell(null); // Close viewer first
    setSelectedCell({ row, col });
    setShowAddCellModal(true);
  };

  const handleCellSwap = async (fromRow: number, fromCol: number, toRow: number, toCol: number) => {
    if (!grid || !isOwner) return;

    try {
      const response = await fetch("/api/grids", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          gridId,
          action: "swap-cells",
          creator: address,
          fromRow,
          fromCol,
          toRow,
          toCol,
        }),
      });

      const data = await response.json();
      if (data.success) {
        refresh();
      } else {
        console.error("Failed to swap cells:", data.error);
      }
    } catch (err) {
      console.error("Error swapping cells:", err);
    }
  };

  return (
    <div className="flex-1 flex flex-col bg-[#0a0a0a] min-h-0 h-full">
      {/* Header */}
      <div className="shrink-0 p-4 border-b border-[#1a1a1a]">
        <div className="flex items-center justify-between mb-2">
          <button
            onClick={onBack}
            className="flex items-center gap-2 text-gray-400 hover:text-white transition-colors"
          >
            <span className="text-lg">←</span>
            <span className="font-mono text-sm">Back</span>
          </button>

          <div className="flex items-center gap-2">
            {/* Upvote button */}
            <button
              onClick={handleUpvote}
              disabled={isUpvoting || !isConnected}
              className={`px-3 py-1.5 rounded-lg font-mono text-sm border transition-all ${
                isUpvoting
                  ? "bg-[#00ff00]/20 border-[#00ff00]/50 text-[#00ff00] animate-pulse"
                  : "bg-[#1a1a1a] border-[#2a2a2a] text-gray-400 hover:border-[#00ff00]/30 hover:text-[#00ff00]"
              } disabled:opacity-50 disabled:cursor-not-allowed`}
              title={isConnected ? `Upvote (${UPVOTE_COST_ETH} ETH)` : "Connect wallet to upvote"}
            >
              ▲ {localUpvoteCount ?? grid.upvoteCount}
            </button>

            {/* Archive button (owner only) */}
            {isOwner && (
              <button
                onClick={() => setShowArchiveModal(true)}
                className="px-3 py-1.5 rounded-lg bg-[#1a1a1a] border border-[#2a2a2a] text-gray-400 font-mono text-sm hover:border-[#00ff00]/30 hover:text-[#00ff00] transition-colors"
                title="Archive this grid"
              >
                Archive
              </button>
            )}

            {/* CDN Link button (shown when archived) */}
            {archiveCdnUrl && (
              <button
                onClick={() => setShowCdnLinkModal(true)}
                className="px-3 py-1.5 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] font-mono text-sm hover:bg-[#00ff00]/20 transition-colors flex items-center gap-1.5"
                title="View archive CDN link"
              >
                <LinkIcon size={14} /> CDN
              </button>
            )}

            {/* Share button */}
            <div className="relative">
              <button
                onClick={() => setShowShareMenu(!showShareMenu)}
                className={`px-3 py-1.5 rounded-lg border font-mono text-sm transition-colors flex items-center gap-1.5 ${
                  isBaseApp
                    ? "bg-[#0052FF]/20 border-[#0052FF]/40 text-[#0052FF] hover:bg-[#0052FF]/30"
                    : "bg-[#8A63D2]/20 border-[#8A63D2]/40 text-[#8A63D2] hover:bg-[#8A63D2]/30"
                }`}
                title="Share grid"
              >
                <ShareIcon size={14} /> Share
              </button>

              {showShareMenu && (
                <>
                  <div className="fixed inset-0 z-40" onClick={() => setShowShareMenu(false)} />
                  <div className="absolute right-0 top-full mt-1 bg-black border border-[#00ff00]/30 rounded-lg overflow-hidden z-50 shadow-lg min-w-[160px]">
                    <button
                      onClick={async () => {
                        setShowShareMenu(false);
                        const source = isBaseApp ? "base" : "farcaster";
                        const gridUrl = `${window.location.origin}/share/grid/${encodeURIComponent(gridId)}?source=${source}`;
                        const creatorName = grid.creatorUsername || "a Net Library member";
                        const castText = `Check out "${grid.name || 'this grid'}" by ${creatorName} on Net Library!\n\n${grid.size || 3}×${grid.size || 3} grid with ${grid.cellCount || 0} items\n\nExperience the decentralized onchain media library powered by @netprotocol`;
                        await safeComposeCast({
                          text: castText,
                          embeds: [gridUrl],
                        });
                      }}
                      className={`w-full px-3 py-2.5 text-left text-xs font-mono flex items-center gap-2 transition-colors ${
                        isBaseApp
                          ? "hover:bg-[#0052FF]/20 text-[#0052FF]"
                          : "hover:bg-[#8A63D2]/20 text-[#8A63D2]"
                      }`}
                    >
                      {isBaseApp ? (
                        <svg width="14" height="14" viewBox="0 0 111 111" fill="none">
                          <path d="M54.921 110.034C85.359 110.034 110.034 85.402 110.034 55.017C110.034 24.6319 85.359 0 54.921 0C26.0432 0 2.35281 22.1714 0 50.3923H72.8467V59.6416H0C2.35281 87.8625 26.0432 110.034 54.921 110.034Z" fill="#0052FF"/>
                        </svg>
                      ) : (
                        <svg width="14" height="14" viewBox="0 0 1000 1000" fill="#8A63D2">
                          <path d="M257.778 155.556H742.222V844.445H671.111V528.889H670.414C662.554 441.677 589.258 373.333 500 373.333C410.742 373.333 337.446 441.677 329.586 528.889H328.889V844.445H257.778V155.556Z"/>
                          <path d="M128.889 253.333L157.778 351.111H182.222V746.667C169.949 746.667 160 756.616 160 768.889V795.556H155.556C143.283 795.556 133.333 805.505 133.333 817.778V844.445H382.222V817.778C382.222 805.505 372.273 795.556 360 795.556H355.556V768.889C355.556 756.616 345.606 746.667 333.333 746.667H306.667V253.333H128.889Z"/>
                          <path d="M675.556 746.667C663.283 746.667 653.333 756.616 653.333 768.889V795.556H648.889C636.616 795.556 626.667 805.505 626.667 817.778V844.445H875.556V817.778C875.556 805.505 865.606 795.556 853.333 795.556H848.889V768.889C848.889 756.616 838.94 746.667 826.667 746.667V351.111H851.111L880 253.333H702.222V746.667H675.556Z"/>
                        </svg>
                      )}
                      {isBaseApp ? "Share to Feed" : "Share to Farcaster"}
                    </button>
                    <button
                      onClick={async () => {
                        setShowShareMenu(false);
                        const gridUrl = `${window.location.origin}/share/grid/${encodeURIComponent(gridId)}?source=web`;
                        const creatorName = grid.creatorUsername || "a Net Library member";
                        const xText = `Check out "${grid.name || 'this grid'}" by ${creatorName} on Net Library!\n\n${grid.size || 3}×${grid.size || 3} grid with ${grid.cellCount || 0} items\n\nExperience the decentralized onchain media library powered by @netprotocolapp`;
                        const xIntentParams = new URLSearchParams({
                          text: xText,
                          url: gridUrl,
                        });
                        const xIntentUrl = `https://twitter.com/intent/tweet?${xIntentParams.toString()}`;
                        if (isBaseApp) {
                          window.open(xIntentUrl, "_blank", "noopener,noreferrer");
                        } else {
                          await safeOpenUrl(xIntentUrl);
                        }
                      }}
                      className="w-full px-3 py-2.5 text-left text-xs font-mono flex items-center gap-2 hover:bg-white/10 text-white transition-colors border-t border-gray-800"
                    >
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="white">
                        <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                      </svg>
                      Share to X
                    </button>
                    <button
                      onClick={async () => {
                        setShowShareMenu(false);
                        const gridUrl = `${window.location.origin}/share/grid/${encodeURIComponent(gridId)}`;
                        try {
                          await navigator.clipboard.writeText(gridUrl);
                          // Could add a toast here
                        } catch (err) {
                          console.error("Failed to copy:", err);
                        }
                      }}
                      className="w-full px-3 py-2.5 text-left text-xs font-mono flex items-center gap-2 hover:bg-[#00ff00]/10 text-[#00ff00] transition-colors border-t border-gray-800"
                    >
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                        <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
                        <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
                      </svg>
                      Copy Link
                    </button>
                  </div>
                </>
              )}
            </div>
          </div>
        </div>

        <div className="flex items-start justify-between gap-2">
          <div className="flex-1 min-w-0">
            <h1 className="text-[#00ff00] font-mono text-xl">{grid.name}</h1>
            {grid.subtitle && (
              <p className="text-gray-400 font-mono text-sm mt-0.5">{grid.subtitle}</p>
            )}
          </div>
          {isOwner && (
            <button
              onClick={() => setShowEditModal(true)}
              className="shrink-0 w-8 h-8 rounded-lg bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white transition-colors"
              aria-label="Edit grid"
            >
              ✎
            </button>
          )}
        </div>
        <p className="text-gray-500 font-mono text-sm mt-1">
          {grid.size || 3}×{grid.size || 3} • {grid.cellCount || 0}/{grid.totalCells || 9} filled
          {isOwner && !editMode && <span className="text-[#00ff00] ml-2">• Owner</span>}
        </p>

        {/* Edit Mode Toggle - only shown to owners */}
        {isOwner && (
          <button
            onClick={() => setEditMode(!editMode)}
            className={`mt-2 px-3 py-1.5 rounded-lg font-mono text-sm border transition-all ${
              editMode
                ? "bg-[#00ff00]/20 border-[#00ff00]/50 text-[#00ff00]"
                : "bg-[#1a1a1a] border-[#2a2a2a] text-gray-400 hover:border-[#00ff00]/30 hover:text-[#00ff00]"
            }`}
          >
            {editMode ? "✓ Edit Mode" : "✎ Edit Grid"}
          </button>
        )}
        {grid.description && (
          <p className="text-gray-400 font-mono text-xs mt-2 leading-relaxed">{grid.description}</p>
        )}
      </div>

      {/* Grid Canvas with Zoom/Pan */}
      <ZoomableGridCanvas
        grid={grid}
        cells={cells}
        onCellClick={handleCellClick}
        onCellSwap={editMode && isOwner ? handleCellSwap : undefined}
        editMode={editMode}
      />

      {/* Add Cell Modal */}
      {showAddCellModal && selectedCell && grid && (
        <AddCellModal
          gridId={gridId}
          gridSize={grid.size}
          row={selectedCell.row}
          col={selectedCell.col}
          existingCell={cells.find(
            (c) => c.row === selectedCell.row && c.col === selectedCell.col
          )}
          existingCells={cells}
          onClose={() => {
            setShowAddCellModal(false);
            setSelectedCell(null);
          }}
          onSaved={() => {
            refresh();
            setShowAddCellModal(false);
            setSelectedCell(null);
          }}
        />
      )}

      {/* Archive Modal */}
      {showArchiveModal && grid && (
        <GridArchiveModal
          isOpen={showArchiveModal}
          onClose={() => setShowArchiveModal(false)}
          grid={grid}
          cells={cells}
          onArchived={() => {
            setShowArchiveModal(false);
            refreshArchives(); // Refresh archive list to show CDN link button
          }}
        />
      )}

      {/* CDN Link Modal for Archived Grid */}
      {showCdnLinkModal && archiveCdnUrl && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80">
          <div className="bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl p-4 max-w-md w-full">
            <div className="flex justify-between items-center mb-3">
              <h3 className="text-[#00ff00] font-mono font-bold">Archive CDN Link</h3>
              <button
                onClick={() => setShowCdnLinkModal(false)}
                className="text-gray-500 hover:text-white"
              >
                ✕
              </button>
            </div>
            <p className="text-gray-400 text-xs font-mono mb-3">
              This grid is archived onchain. Copy the permanent link below:
            </p>
            <div className="bg-black rounded-lg p-3 border border-[#00ff00]/20">
              <code className="text-[#00ff00] text-xs font-mono break-all">
                {archiveCdnUrl}
              </code>
            </div>
            <button
              onClick={async () => {
                try {
                  await navigator.clipboard.writeText(archiveCdnUrl);
                  setCdnLinkCopied(true);
                  setTimeout(() => setCdnLinkCopied(false), 2000);
                } catch {
                  // Fallback
                  const textarea = document.createElement("textarea");
                  textarea.value = archiveCdnUrl;
                  document.body.appendChild(textarea);
                  textarea.select();
                  document.execCommand("copy");
                  document.body.removeChild(textarea);
                  setCdnLinkCopied(true);
                  setTimeout(() => setCdnLinkCopied(false), 2000);
                }
              }}
              className={`w-full mt-3 py-2 px-4 rounded-lg font-mono text-sm flex items-center justify-center gap-2 transition-colors ${
                cdnLinkCopied
                  ? "bg-green-500/20 border border-green-500/50 text-green-400"
                  : "bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/20"
              }`}
            >
              {cdnLinkCopied ? (
                <>
                  <CheckIcon size={14} /> Copied!
                </>
              ) : (
                <>
                  <ClipboardIcon size={14} /> Copy Link
                </>
              )}
            </button>
            {latestArchive && (
              <p className="text-gray-500 text-[10px] font-mono mt-2 text-center">
                Archived {new Date(latestArchive.archivedAt).toLocaleDateString()}
              </p>
            )}
          </div>
        </div>
      )}

      {/* Cell Viewer Modal */}
      {viewingCell && (
        <GridCellViewer
          cell={viewingCell}
          cells={sortedFilledCells}
          currentIndex={viewingCellIndex}
          onClose={() => setViewingCell(null)}
          onNavigate={(index) => {
            setViewingCellIndex(index);
            setViewingCell(sortedFilledCells[index]);
          }}
          isOwner={!!isOwner}
          onEdit={handleEditCell}
          onViewItemDetail={onViewItemDetail}
        />
      )}

      {/* Edit Grid Modal */}
      {showEditModal && grid && (
        <EditGridModal
          grid={grid}
          onClose={() => setShowEditModal(false)}
          onSaved={() => {
            refresh();
            setShowEditModal(false);
          }}
        />
      )}
    </div>
  );
}

// Zoomable Grid Canvas with pan, pinch-to-zoom, and mini-map
function ZoomableGridCanvas({
  grid,
  cells,
  onCellClick,
  onCellSwap,
  editMode,
}: {
  grid: GridWithStats;
  cells: GridCell[];
  onCellClick?: (row: number, col: number) => void;
  onCellSwap?: (fromRow: number, fromCol: number, toRow: number, toCol: number) => void;
  editMode?: boolean;
}) {
  const containerRef = useRef<HTMLDivElement>(null);
  const contentRef = useRef<HTMLDivElement>(null);

  // Zoom and pan state
  const [scale, setScale] = useState(1);
  const [position, setPosition] = useState({ x: 0, y: 0 });
  const [isPanning, setIsPanning] = useState(false);
  const [lastPanPoint, setLastPanPoint] = useState({ x: 0, y: 0 });

  // Double-tap detection
  const lastTapRef = useRef<{ time: number; row: number; col: number } | null>(null);

  // Drag state for cell rearrangement
  const [dragFrom, setDragFrom] = useState<{ row: number; col: number } | null>(null);
  const [dragOver, setDragOver] = useState<{ row: number; col: number } | null>(null);

  // Create cell map - memoized to prevent unnecessary re-renders
  const cellMap = useMemo(() => {
    const map = new Map<string, GridCell>();
    cells.forEach((cell) => {
      map.set(`${cell.row}-${cell.col}`, cell);
    });
    return map;
  }, [cells]);

  // Calculate base cell size - use fallback if size is missing
  const gridSize = grid.size || 3;
  const maxCellSize = 120;
  const minCellSize = 40;
  const baseCellSize = Math.max(minCellSize, Math.min(maxCellSize, 320 / gridSize));

  // Zoom constraints
  const minScale = 0.5;
  const maxScale = 3;

  // Handle mouse wheel zoom - gentler factor for smoother feel
  // Note: We use useEffect to attach this as a non-passive listener to allow preventDefault
  const handleWheel = useCallback((e: WheelEvent) => {
    e.preventDefault();
    // Use smaller zoom factor (3% per tick instead of 10%) for smoother zooming
    // Trackpads and scroll wheels fire many events quickly, so this feels more controlled
    const delta = e.deltaY > 0 ? 0.97 : 1.03;
    const newScale = Math.max(minScale, Math.min(maxScale, scale * delta));

    // Zoom toward cursor position
    if (containerRef.current) {
      const rect = containerRef.current.getBoundingClientRect();
      const cursorX = e.clientX - rect.left;
      const cursorY = e.clientY - rect.top;

      const scaleChange = newScale / scale;
      const newX = cursorX - (cursorX - position.x) * scaleChange;
      const newY = cursorY - (cursorY - position.y) * scaleChange;

      setPosition({ x: newX, y: newY });
    }

    setScale(newScale);
  }, [scale, position]);

  // Attach wheel event listener with { passive: false } to allow preventDefault
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    container.addEventListener("wheel", handleWheel, { passive: false });
    return () => container.removeEventListener("wheel", handleWheel);
  }, [handleWheel]);

  // Handle touch pinch-to-zoom
  // Note: We use useEffect to attach touch listeners as non-passive to allow preventDefault
  const lastTouchDistRef = useRef<number | null>(null);
  const lastTouchCenterRef = useRef<{ x: number; y: number } | null>(null);

  const handleTouchStart = useCallback((e: TouchEvent) => {
    if (e.touches.length === 2) {
      // Pinch start
      const touch1 = e.touches[0];
      const touch2 = e.touches[1];
      const dist = Math.hypot(touch2.clientX - touch1.clientX, touch2.clientY - touch1.clientY);
      lastTouchDistRef.current = dist;
      lastTouchCenterRef.current = {
        x: (touch1.clientX + touch2.clientX) / 2,
        y: (touch1.clientY + touch2.clientY) / 2,
      };
    } else if (e.touches.length === 1 && scale > 1) {
      // Only enable panning when zoomed in - don't interfere with normal taps
      setLastPanPoint({ x: e.touches[0].clientX, y: e.touches[0].clientY });
      // Don't set isPanning yet - wait for actual movement
    }
  }, [scale]);

  const handleTouchMove = useCallback((e: TouchEvent) => {
    if (e.touches.length === 2 && lastTouchDistRef.current !== null) {
      // Pinch zoom - prevent default to stop page scroll/zoom
      e.preventDefault();
      const touch1 = e.touches[0];
      const touch2 = e.touches[1];
      const dist = Math.hypot(touch2.clientX - touch1.clientX, touch2.clientY - touch1.clientY);
      const scaleChange = dist / lastTouchDistRef.current;
      const newScale = Math.max(minScale, Math.min(maxScale, scale * scaleChange));

      // Zoom toward pinch center
      if (containerRef.current && lastTouchCenterRef.current) {
        const rect = containerRef.current.getBoundingClientRect();
        const centerX = (touch1.clientX + touch2.clientX) / 2 - rect.left;
        const centerY = (touch1.clientY + touch2.clientY) / 2 - rect.top;

        const actualScaleChange = newScale / scale;
        const newX = centerX - (centerX - position.x) * actualScaleChange;
        const newY = centerY - (centerY - position.y) * actualScaleChange;

        setPosition({ x: newX, y: newY });
      }

      setScale(newScale);
      lastTouchDistRef.current = dist;
    } else if (e.touches.length === 1 && scale > 1) {
      // Pan when zoomed - start panning on movement
      const dx = e.touches[0].clientX - lastPanPoint.x;
      const dy = e.touches[0].clientY - lastPanPoint.y;

      // Only start panning if there's meaningful movement (> 5px)
      if (!isPanning && (Math.abs(dx) > 5 || Math.abs(dy) > 5)) {
        setIsPanning(true);
      }

      if (isPanning) {
        e.preventDefault(); // Prevent scroll when panning
        setPosition(prev => ({ x: prev.x + dx, y: prev.y + dy }));
        setLastPanPoint({ x: e.touches[0].clientX, y: e.touches[0].clientY });
      }
    }
  }, [scale, position, isPanning, lastPanPoint]);

  const handleTouchEnd = useCallback(() => {
    lastTouchDistRef.current = null;
    lastTouchCenterRef.current = null;
    setIsPanning(false);
  }, []);

  // Attach touch event listeners with { passive: false } to allow preventDefault
  useEffect(() => {
    const container = containerRef.current;
    if (!container) return;

    container.addEventListener("touchstart", handleTouchStart, { passive: true });
    container.addEventListener("touchmove", handleTouchMove, { passive: false });
    container.addEventListener("touchend", handleTouchEnd, { passive: true });

    return () => {
      container.removeEventListener("touchstart", handleTouchStart);
      container.removeEventListener("touchmove", handleTouchMove);
      container.removeEventListener("touchend", handleTouchEnd);
    };
  }, [handleTouchStart, handleTouchMove, handleTouchEnd]);

  // Handle mouse pan
  const handleMouseDown = useCallback((e: React.MouseEvent) => {
    if (scale > 1 && e.button === 0) {
      setIsPanning(true);
      setLastPanPoint({ x: e.clientX, y: e.clientY });
    }
  }, [scale]);

  const handleMouseMove = useCallback((e: React.MouseEvent) => {
    if (isPanning && scale > 1) {
      const dx = e.clientX - lastPanPoint.x;
      const dy = e.clientY - lastPanPoint.y;
      setPosition(prev => ({ x: prev.x + dx, y: prev.y + dy }));
      setLastPanPoint({ x: e.clientX, y: e.clientY });
    }
  }, [isPanning, lastPanPoint, scale]);

  const handleMouseUp = useCallback(() => {
    setIsPanning(false);
  }, []);

  // Handle cell tap - everyone views content the same way, owners can edit via viewer
  const handleCellTap = useCallback((row: number, col: number) => {
    const now = Date.now();
    const lastTap = lastTapRef.current;

    // Double-tap detection for zoom (works for everyone)
    if (lastTap && now - lastTap.time < 300 && lastTap.row === row && lastTap.col === col) {
      // Double-tap detected - zoom to cell
      if (scale < 2) {
        // Zoom in centered on cell
        const newScale = 2;
        if (containerRef.current) {
          const rect = containerRef.current.getBoundingClientRect();
          const cellX = col * (baseCellSize + 4) + baseCellSize / 2 + 8;
          const cellY = row * (baseCellSize + 4) + baseCellSize / 2 + 8;
          const centerX = rect.width / 2;
          const centerY = rect.height / 2;

          setPosition({
            x: centerX - cellX * newScale,
            y: centerY - cellY * newScale,
          });
        }
        setScale(newScale);
      } else {
        // Zoom out
        setScale(1);
        setPosition({ x: 0, y: 0 });
      }
      lastTapRef.current = null;
    } else {
      // Single tap - record it for double-tap detection
      lastTapRef.current = { time: now, row, col };

      // Single tap triggers onCellClick for everyone
      // - Filled cells: opens viewer (owners see edit button in viewer)
      // - Empty cells: owners can add content, non-owners nothing happens
      if (onCellClick) {
        onCellClick(row, col);
      }
    }
  }, [scale, baseCellSize, onCellClick]);

  // Drag handlers for cell rearrangement
  const handleDragStart = (row: number, col: number) => {
    if (cellMap.has(`${row}-${col}`)) {
      setDragFrom({ row, col });
    }
  };

  const handleDragOver = (row: number, col: number) => {
    if (dragFrom && (dragFrom.row !== row || dragFrom.col !== col)) {
      setDragOver({ row, col });
    }
  };

  const handleDrop = (row: number, col: number) => {
    if (dragFrom && onCellSwap) {
      onCellSwap(dragFrom.row, dragFrom.col, row, col);
    }
    setDragFrom(null);
    setDragOver(null);
  };

  const handleDragEnd = () => {
    setDragFrom(null);
    setDragOver(null);
  };

  // Jump to position from mini-map
  const handleMiniMapClick = useCallback((row: number, col: number) => {
    if (containerRef.current) {
      const rect = containerRef.current.getBoundingClientRect();
      const cellX = col * (baseCellSize + 4) + baseCellSize / 2 + 8;
      const cellY = row * (baseCellSize + 4) + baseCellSize / 2 + 8;
      const centerX = rect.width / 2;
      const centerY = rect.height / 2;

      setPosition({
        x: centerX - cellX * scale,
        y: centerY - cellY * scale,
      });
    }
  }, [baseCellSize, scale]);

  // Calculate viewport for mini-map
  const getViewport = useCallback(() => {
    if (!containerRef.current) return null;

    const rect = containerRef.current.getBoundingClientRect();
    const gridWidth = gridSize * (baseCellSize + 4) + 16;
    const gridHeight = gridSize * (baseCellSize + 4) + 16;

    // Calculate visible area in grid coordinates
    const visibleLeft = Math.max(0, -position.x / scale);
    const visibleTop = Math.max(0, -position.y / scale);
    const visibleWidth = Math.min(gridWidth, rect.width / scale);
    const visibleHeight = Math.min(gridHeight, rect.height / scale);

    return {
      left: visibleLeft / gridWidth,
      top: visibleTop / gridHeight,
      width: visibleWidth / gridWidth,
      height: visibleHeight / gridHeight,
    };
  }, [gridSize, baseCellSize, position, scale]);

  return (
    <div className="flex-1 relative overflow-hidden min-h-[300px]">
      {/* Infinite diamond background - fills entire canvas area */}
      <div
        className="absolute inset-0"
        style={{
          background: `
            linear-gradient(135deg, #0d0d0d 25%, transparent 25%),
            linear-gradient(225deg, #0d0d0d 25%, transparent 25%),
            linear-gradient(45deg, #0d0d0d 25%, transparent 25%),
            linear-gradient(315deg, #0d0d0d 25%, #0a0a0a 25%)
          `,
          backgroundSize: "20px 20px",
          backgroundPosition: "0 0, 10px 0, 10px -10px, 0px 10px",
        }}
      />

      {/* Main canvas container */}
      {/* Note: wheel and touch events are attached via useEffect with { passive: false } */}
      <div
        ref={containerRef}
        className="absolute inset-0 overflow-hidden touch-manipulation"
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
        onMouseLeave={handleMouseUp}
        style={{ cursor: isPanning ? "grabbing" : scale > 1 ? "grab" : "default" }}
      >
        {/* Zoomable content - short transition for smooth but responsive zoom */}
        <div
          ref={contentRef}
          className="absolute origin-top-left transition-transform duration-75 ease-out"
          style={{
            transform: `translate(${position.x}px, ${position.y}px) scale(${scale})`,
            transformOrigin: "0 0",
          }}
        >
          {/* Grid cells container */}
          <div className="relative m-4">
            <div
              className="grid gap-1 p-2"
              style={{
                gridTemplateColumns: `repeat(${gridSize}, ${baseCellSize}px)`,
                gridTemplateRows: `repeat(${gridSize}, ${baseCellSize}px)`,
              }}
            >
              {Array.from({ length: gridSize * gridSize }).map((_, index) => {
                const row = Math.floor(index / gridSize);
                const col = index % gridSize;
                const cell = cellMap.get(`${row}-${col}`);
                const isDragSource = dragFrom?.row === row && dragFrom?.col === col;
                const isDragTarget = dragOver?.row === row && dragOver?.col === col;

                return (
                  <GridCellComponent
                    key={`${row}-${col}`}
                    cell={cell}
                    row={row}
                    col={col}
                    size={baseCellSize}
                    onClick={() => handleCellTap(row, col)}
                    isInteractive={!!onCellClick || !!cell}
                    isDraggable={editMode && !!cell && !!onCellSwap}
                    isDragSource={isDragSource}
                    isDragTarget={isDragTarget}
                    onDragStart={() => handleDragStart(row, col)}
                    onDragOver={() => handleDragOver(row, col)}
                    onDrop={() => handleDrop(row, col)}
                    onDragEnd={handleDragEnd}
                    editMode={editMode}
                  />
                );
              })}
            </div>
          </div>
        </div>
      </div>

      {/* Zoom controls - responsive sizing with minimum touch targets */}
      <div className="absolute top-2 right-2 z-10 flex flex-col gap-1.5 sm:gap-1">
        <button
          onClick={() => setScale(Math.min(maxScale, scale * 1.2))}
          className="w-11 h-11 sm:w-9 sm:h-9 md:w-10 md:h-10 rounded-lg bg-black/80 border border-[#00ff00]/30 text-[#00ff00] font-mono text-xl sm:text-lg flex items-center justify-center hover:bg-[#00ff00]/20 active:bg-[#00ff00]/30 transition-colors"
          aria-label="Zoom in"
        >
          +
        </button>
        <button
          onClick={() => {
            setScale(Math.max(minScale, scale * 0.8));
            if (scale <= 1) setPosition({ x: 0, y: 0 });
          }}
          className="w-11 h-11 sm:w-9 sm:h-9 md:w-10 md:h-10 rounded-lg bg-black/80 border border-[#00ff00]/30 text-[#00ff00] font-mono text-xl sm:text-lg flex items-center justify-center hover:bg-[#00ff00]/20 active:bg-[#00ff00]/30 transition-colors"
          aria-label="Zoom out"
        >
          −
        </button>
        {scale !== 1 && (
          <button
            onClick={() => {
              setScale(1);
              setPosition({ x: 0, y: 0 });
            }}
            className="w-11 h-11 sm:w-9 sm:h-9 md:w-10 md:h-10 rounded-lg bg-black/80 border border-[#00ff00]/30 text-[#00ff00] font-mono text-xs flex items-center justify-center hover:bg-[#00ff00]/20 active:bg-[#00ff00]/30 transition-colors"
            aria-label="Reset zoom"
          >
            1:1
          </button>
        )}
      </div>

      {/* Mini-map for large grids (6×6+) */}
      {gridSize >= 6 && (
        <InteractiveMiniMap
          grid={grid}
          cells={cells}
          viewport={getViewport()}
          onCellClick={handleMiniMapClick}
        />
      )}
    </div>
  );
}

// Interactive Mini-map with viewport indicator and tap-to-jump
function InteractiveMiniMap({
  grid,
  cells,
  viewport,
  onCellClick,
}: {
  grid: GridWithStats;
  cells: GridCell[];
  viewport: { left: number; top: number; width: number; height: number } | null;
  onCellClick: (row: number, col: number) => void;
}) {
  const mapRef = useRef<HTMLDivElement>(null);

  // Create a map of position to cell for quick lookup
  const cellMap = new Map<string, GridCell>();
  cells.forEach(c => cellMap.set(`${c.row}-${c.col}`, c));

  const gridSize = grid.size || 3;
  const cellSize = 6;
  const mapSize = gridSize * cellSize + (gridSize - 1);

  const handleMapClick = useCallback((e: React.MouseEvent) => {
    if (!mapRef.current) return;

    const rect = mapRef.current.getBoundingClientRect();
    const x = e.clientX - rect.left - 6; // Subtract padding
    const y = e.clientY - rect.top - 6;

    const col = Math.floor(x / (cellSize + 1));
    const row = Math.floor(y / (cellSize + 1));

    if (row >= 0 && row < gridSize && col >= 0 && col < gridSize) {
      onCellClick(row, col);
    }
  }, [gridSize, onCellClick]);

  return (
    <div className="absolute bottom-2 right-2 z-10">
      <div
        ref={mapRef}
        onClick={handleMapClick}
        className="rounded-lg bg-black/80 border border-[#00ff00]/30 p-1.5 backdrop-blur-sm cursor-pointer relative"
        style={{ width: mapSize + 12, height: mapSize + 12 }}
      >
        {/* Grid cells */}
        <div
          className="grid gap-px relative"
          style={{
            gridTemplateColumns: `repeat(${gridSize}, ${cellSize}px)`,
            gridTemplateRows: `repeat(${gridSize}, ${cellSize}px)`,
          }}
        >
          {Array.from({ length: gridSize * gridSize }).map((_, index) => {
            const row = Math.floor(index / gridSize);
            const col = index % gridSize;
            const cell = cellMap.get(`${row}-${col}`);

            // Get color based on media type
            let bgColor = "#1a1a1a"; // Empty cell
            if (cell) {
              const mediaType = cell.mediaType || detectGridMediaType(cell.cdnUrl, cell.contentType);
              bgColor = getMediaTypeBorderColor(mediaType);
            }

            return (
              <div
                key={`mini-${row}-${col}`}
                className="rounded-sm"
                style={{ width: cellSize, height: cellSize, backgroundColor: bgColor }}
              />
            );
          })}
        </div>

        {/* Viewport indicator */}
        {viewport && viewport.width < 1 && viewport.height < 1 && (
          <div
            className="absolute border-2 border-white rounded-sm pointer-events-none"
            style={{
              left: 6 + viewport.left * mapSize,
              top: 6 + viewport.top * mapSize,
              width: Math.max(8, viewport.width * mapSize),
              height: Math.max(8, viewport.height * mapSize),
              boxShadow: "0 0 4px rgba(255, 255, 255, 0.5)",
            }}
          />
        )}
      </div>

      {/* Label */}
      <div className="text-center mt-1">
        <span className="text-[#00ff00]/50 font-mono text-[8px]">tap to jump</span>
      </div>
    </div>
  );
}

// Individual Grid Cell
function GridCellComponent({
  cell,
  row: _row,
  col: _col,
  size,
  onClick,
  isInteractive,
  isDraggable,
  isDragSource,
  isDragTarget,
  onDragStart,
  onDragOver,
  onDrop,
  onDragEnd,
  editMode,
}: {
  cell?: GridCell;
  row: number;
  col: number;
  size: number;
  onClick?: () => void;
  isInteractive: boolean;
  isDraggable?: boolean;
  isDragSource?: boolean;
  isDragTarget?: boolean;
  onDragStart?: () => void;
  onDragOver?: () => void;
  onDrop?: () => void;
  onDragEnd?: () => void;
  editMode?: boolean;
}) {
  const [imageError, setImageError] = useState(false);

  if (cell && !imageError) {
    // Filled cell with content
    // Determine media type - use stored value or detect from URL/contentType
    const mediaType: GridMediaType = cell.mediaType || detectGridMediaType(cell.cdnUrl, cell.contentType);
    const borderColor = getMediaTypeBorderColor(mediaType);

    // Create shadow color from border color (with alpha for glow effect)
    const shadowColor = borderColor.replace("#", "");
    const r = parseInt(shadowColor.substring(0, 2), 16);
    const g = parseInt(shadowColor.substring(2, 4), 16);
    const b = parseInt(shadowColor.substring(4, 6), 16);

    // Use coverUrl if available, otherwise fall back to cdnUrl
    const displayUrl = toGatewayUrl(cell.coverUrl || cell.cdnUrl);

    return (
      <div
        draggable={isDraggable}
        onDragStart={(e) => {
          if (isDraggable && onDragStart) {
            e.dataTransfer.effectAllowed = "move";
            onDragStart();
          }
        }}
        onDragOver={(e) => {
          e.preventDefault();
          e.dataTransfer.dropEffect = "move";
          onDragOver?.();
        }}
        onDrop={(e) => {
          e.preventDefault();
          onDrop?.();
        }}
        onDragEnd={onDragEnd}
        onClick={() => onClick?.()}
        className={`relative rounded-lg overflow-hidden bg-black border-2 transition-all ${
          isDragSource
            ? "opacity-50 scale-95"
            : ""
        } ${
          isInteractive ? "cursor-pointer" : ""
        } ${isDraggable ? "cursor-grab active:cursor-grabbing" : ""}`}
        style={{
          width: size,
          height: size,
          borderColor: isDragSource || isDragTarget ? "#00ff00" : borderColor,
          boxShadow: isDragTarget
            ? `0 0 10px rgba(0, 255, 0, 0.5)`
            : `0 0 6px rgba(${r}, ${g}, ${b}, 0.3)`,
        }}
      >
        {/* Always use cover image for cell preview (videos use coverUrl, not the video itself) */}
        <img
          src={displayUrl}
          alt={cell.title || "Grid cell"}
          className="w-full h-full object-cover pointer-events-none"
          loading="lazy"
          onError={() => setImageError(true)}
        />

        {/* Media type indicator badge */}
        {mediaType !== "image" && (
          <div
            className="absolute top-1 right-1 px-1 py-0.5 rounded text-[8px] font-mono font-bold uppercase"
            style={{
              backgroundColor: `rgba(${r}, ${g}, ${b}, 0.9)`,
              color: "#000", // All badge colors (yellow, green, white) need black text for contrast
            }}
          >
            {mediaType === "gif" ? "GIF" : mediaType === "video" ? "▶" : mediaType === "audio" ? "♪" : "TXT"}
          </div>
        )}

        {/* Hover overlay for interactive cells - only show in View Mode (not Edit Mode) */}
        {isInteractive && !isDragSource && !editMode && (
          <div className="absolute inset-0 bg-black/50 opacity-0 hover:opacity-100 transition-opacity flex flex-col items-center justify-center gap-0.5">
            <span className="text-white font-mono text-xs">Tap to view</span>
          </div>
        )}

        {/* Edit mode overlay - show edit hints and drag capability */}
        {isInteractive && !isDragSource && editMode && (
          <div className="absolute inset-0 bg-black/50 opacity-0 hover:opacity-100 transition-opacity flex flex-col items-center justify-center gap-0.5">
            <span className="text-white font-mono text-xs">Tap to edit</span>
            {isDraggable && (
              <span className="text-white/60 font-mono text-[10px]">Drag to move</span>
            )}
          </div>
        )}

        {/* Drag indicator */}
        {isDragTarget && (
          <div className="absolute inset-0 bg-[#00ff00]/20 flex items-center justify-center">
            <span className="text-[#00ff00] font-mono text-xs font-bold">Drop here</span>
          </div>
        )}
      </div>
    );
  }

  // Empty cell - only interactive in Edit Mode
  const isEmptyInteractive = editMode && isInteractive;

  return (
    <div
      onDragOver={(e) => {
        if (!editMode) return; // Only allow drag in Edit Mode
        e.preventDefault();
        e.dataTransfer.dropEffect = "move";
        onDragOver?.();
      }}
      onDrop={(e) => {
        if (!editMode) return;
        e.preventDefault();
        onDrop?.();
      }}
      onClick={editMode ? onClick : undefined}
      className={`rounded-lg bg-[#0a0a0a] border-2 transition-all ${
        isDragTarget
          ? "border-[#00ff00] bg-[#00ff00]/10 shadow-[0_0_10px_rgba(0,255,0,0.3)]"
          : "border-[#00ff00]/20"
      } ${
        isEmptyInteractive
          ? "cursor-pointer hover:border-[#00ff00]/50 hover:bg-[#00ff00]/10"
          : ""
      } flex items-center justify-center`}
      style={{ width: size, height: size }}
    >
      {isDragTarget ? (
        <span className="text-[#00ff00] font-mono text-xs">Drop</span>
      ) : isEmptyInteractive ? (
        <span className="text-[#00ff00]/50 text-2xl font-light">+</span>
      ) : null}
    </div>
  );
}

// Add/Edit Cell Modal - Clean, spacious design with library picker
function AddCellModal({
  gridId,
  gridSize,
  row: initialRow,
  col: initialCol,
  existingCell,
  existingCells,
  onClose,
  onSaved,
}: {
  gridId: string;
  gridSize: number;
  row: number;
  col: number;
  existingCell?: GridCell;
  existingCells?: GridCell[];
  onClose: () => void;
  onSaved: () => void;
}) {
  const { address } = useAccount();
  const { entries } = useDiscoveryContext();
  const [cdnUrl, setCdnUrl] = useState(existingCell?.cdnUrl || "");
  const [title, setTitle] = useState(existingCell?.title || "");
  const [coverUrl, setCoverUrl] = useState(existingCell?.coverUrl || "");
  const [contentKey, setContentKey] = useState(existingCell?.contentKey || "");
  const [mediaType, setMediaType] = useState(existingCell?.mediaType || "");
  const [operator, setOperator] = useState(existingCell?.operator || "");
  const [storageType, setStorageType] = useState(existingCell?.storageType || "");
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [mode, setMode] = useState<"edit" | "browse" | "confirm-remove" | "change-position">(existingCell ? "edit" : "browse");
  const [searchQuery, setSearchQuery] = useState("");

  // Position state - can be changed for existing cells
  const [targetRow, setTargetRow] = useState(initialRow);
  const [targetCol, setTargetCol] = useState(initialCol);

  // Check if target position has a cell
  const targetHasCell = useMemo(() => {
    if (!existingCells) return false;
    if (targetRow === initialRow && targetCol === initialCol) return false; // Same position
    return existingCells.some(c => c.row === targetRow && c.col === targetCol);
  }, [existingCells, targetRow, targetCol, initialRow, initialCol]);

  // Position changed from original?
  const positionChanged = targetRow !== initialRow || targetCol !== initialCol;

  // Filter library items for browsing
  const filteredLibraryItems = useMemo(() => {
    if (!entries) return [];
    let items = entries.filter(e => !e.hidden);
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase();
      items = items.filter(e =>
        e.title?.toLowerCase().includes(query) ||
        e.author?.toLowerCase().includes(query)
      );
    }
    return items.slice(0, 50); // Limit for performance
  }, [entries, searchQuery]);

  // Select item from library
  const handleSelectFromLibrary = (item: DiscoveryEntry) => {
    // Build the CDN URL from the item
    // Prefer stored cdnUrl > /storage/load/ with fileName > fallback to title
    const itemCdnUrl = item.cdnUrl ||
      `https://storedon.net/net/8453/storage/load/${item.operator}/${encodeURIComponent(item.fileName || item.title)}`;
    setCdnUrl(itemCdnUrl);
    setTitle(item.title);
    setCoverUrl(item.coverUrl || "");
    setContentKey(item.contentKey);
    setMediaType(item.mediaType || "");
    setOperator(item.operator);
    setStorageType(item.storageType || "");
    setMode("edit");
  };

  const handleSave = async () => {
    if (!address || !cdnUrl.trim()) return;

    setIsSaving(true);
    setError(null);

    try {
      const response = await fetch("/api/grids", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          gridId,
          action: "add-cell",
          creator: address,
          row: targetRow,
          col: targetCol,
          cdnUrl: cdnUrl.trim(),
          title: title.trim() || undefined,
          coverUrl: coverUrl || undefined,
          contentKey: contentKey || undefined,
          mediaType: mediaType || undefined,
          operator: operator || undefined,
          storageType: storageType || undefined,
        }),
      });

      const data = await response.json();
      if (!data.success) throw new Error(data.error || "Failed to save cell");
      onSaved();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to save cell");
    } finally {
      setIsSaving(false);
    }
  };

  const handleMove = async () => {
    if (!address || !existingCell || !positionChanged) return;

    setIsSaving(true);
    setError(null);

    try {
      const response = await fetch("/api/grids", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          gridId,
          action: "move-cell",
          creator: address,
          fromRow: initialRow,
          fromCol: initialCol,
          toRow: targetRow,
          toCol: targetCol,
        }),
      });

      const data = await response.json();
      if (!data.success) throw new Error(data.error || "Failed to move cell");
      onSaved();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to move cell");
    } finally {
      setIsSaving(false);
    }
  };

  const handleRemove = async () => {
    if (!address || !existingCell) return;

    setIsSaving(true);
    setError(null);

    try {
      const response = await fetch("/api/grids", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          gridId,
          action: "remove-cell",
          creator: address,
          row: initialRow,
          col: initialCol,
        }),
      });

      const data = await response.json();
      if (!data.success) throw new Error(data.error || "Failed to remove cell");
      onSaved();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to remove cell");
    } finally {
      setIsSaving(false);
    }
  };

  const handleClearCell = () => {
    setCdnUrl("");
    setTitle("");
    setCoverUrl("");
    setContentKey("");
    setMediaType("");
    setOperator("");
    setStorageType("");
  };

  // Render via portal to escape any stacking context issues
  return createPortal(
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/90"
      onClick={onClose}
    >
      <div
        className="w-full max-w-md mx-4 bg-[#0a0a0a] border border-[#00ff00]/20 rounded-2xl overflow-hidden flex flex-col max-h-[85vh]"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-[#1a1a1a] shrink-0">
          <div>
            <h2 className="text-[#00ff00] font-mono text-lg font-medium">
              {mode === "change-position" ? "Move Cell" : existingCell ? "Edit Cell" : "Add to Grid"}
            </h2>
            {/* Clickable position - only for existing cells */}
            {existingCell ? (
              <button
                onClick={() => setMode("change-position")}
                className="text-gray-400 font-mono text-xs mt-0.5 hover:text-[#00ff00] transition-colors flex items-center gap-1"
              >
                <span>Row {targetRow + 1}, Col {targetCol + 1}</span>
                <EditIcon size={12} />
              </button>
            ) : (
              <p className="text-gray-500 font-mono text-xs mt-0.5">
                Row {targetRow + 1}, Col {targetCol + 1}
              </p>
            )}
          </div>
          <button
            onClick={onClose}
            className="w-10 h-10 rounded-full bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white hover:bg-[#2a2a2a] transition-colors shrink-0"
          >
            ✕
          </button>
        </div>

        {/* Change Position Mode */}
        {mode === "change-position" && (
          <div className="p-5 flex-1 overflow-y-auto">
            <p className="text-gray-400 font-mono text-sm mb-4">
              Select new position for this cell
            </p>

            {/* Row/Col inputs */}
            <div className="flex gap-4 mb-5">
              <div className="flex-1">
                <label className="block text-gray-500 font-mono text-xs mb-2">Row</label>
                <select
                  value={targetRow}
                  onChange={(e) => setTargetRow(Number(e.target.value))}
                  className="w-full px-4 py-3 rounded-xl bg-black border border-[#1a1a1a] text-white font-mono focus:border-[#00ff00]/30 focus:outline-none transition-colors"
                  style={{ fontSize: "16px" }}
                >
                  {Array.from({ length: gridSize }, (_, i) => (
                    <option key={i} value={i}>{i + 1}</option>
                  ))}
                </select>
              </div>
              <div className="flex-1">
                <label className="block text-gray-500 font-mono text-xs mb-2">Column</label>
                <select
                  value={targetCol}
                  onChange={(e) => setTargetCol(Number(e.target.value))}
                  className="w-full px-4 py-3 rounded-xl bg-black border border-[#1a1a1a] text-white font-mono focus:border-[#00ff00]/30 focus:outline-none transition-colors"
                  style={{ fontSize: "16px" }}
                >
                  {Array.from({ length: gridSize }, (_, i) => (
                    <option key={i} value={i}>{i + 1}</option>
                  ))}
                </select>
              </div>
            </div>

            {/* Warning if target has content */}
            {targetHasCell && (
              <div className="p-3 rounded-xl bg-yellow-500/10 border border-yellow-500/30 mb-5">
                <p className="text-yellow-400 font-mono text-sm flex items-center gap-1">
                  <WarningIcon size={14} /> This position already has content. Moving here will replace it.
                </p>
              </div>
            )}

            {/* No change notice */}
            {!positionChanged && (
              <div className="p-3 rounded-xl bg-[#1a1a1a] mb-5">
                <p className="text-gray-500 font-mono text-sm text-center">
                  Same position as current
                </p>
              </div>
            )}

            {/* Error */}
            {error && (
              <div className="p-3 rounded-xl bg-red-500/10 border border-red-500/30 mb-5">
                <p className="text-red-400 font-mono text-sm">{error}</p>
              </div>
            )}

            {/* Actions */}
            <div className="flex gap-3">
              <button
                onClick={() => {
                  setTargetRow(initialRow);
                  setTargetCol(initialCol);
                  setMode("edit");
                }}
                className="flex-1 py-3.5 rounded-xl font-mono text-sm bg-[#1a1a1a] text-gray-400 hover:text-white transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleMove}
                disabled={!positionChanged || isSaving}
                className="flex-1 py-3.5 rounded-xl font-mono text-sm bg-[#00ff00] text-black font-medium hover:bg-[#00dd00] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isSaving ? "Moving..." : targetHasCell ? "Replace & Move" : "Move"}
              </button>
            </div>
          </div>
        )}

        {/* Remove Confirmation */}
        {mode === "confirm-remove" && (
          <div className="p-6 flex-1 flex flex-col items-center justify-center">
            <TrashIcon size={40} className="text-red-400 mb-4" />
            <p className="text-white font-mono text-center mb-2">Remove this cell?</p>
            <p className="text-gray-500 font-mono text-sm text-center mb-6">
              The item will be removed from this grid position.
            </p>
            <div className="flex gap-3 w-full max-w-xs">
              <button
                onClick={() => setMode("edit")}
                className="flex-1 py-3 rounded-xl font-mono text-sm bg-[#1a1a1a] text-gray-400 hover:text-white transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleRemove}
                disabled={isSaving}
                className="flex-1 py-3 rounded-xl font-mono text-sm bg-red-500/20 border border-red-500/40 text-red-400 hover:bg-red-500/30 transition-colors disabled:opacity-50"
              >
                {isSaving ? "Removing..." : "Remove"}
              </button>
            </div>
          </div>
        )}

        {/* Browse Library Mode */}
        {mode === "browse" && (
          <>
            <div className="p-4 border-b border-[#1a1a1a]">
              {/* Search */}
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search your library..."
                className="w-full px-4 py-3 rounded-xl bg-black border border-[#1a1a1a] text-white font-mono placeholder:text-gray-600 focus:border-[#00ff00]/30 focus:outline-none transition-colors"
                style={{ fontSize: "16px" }}
              />
              {/* Or paste link option */}
              <button
                onClick={() => setMode("edit")}
                className="w-full mt-3 py-2.5 text-[#00ff00]/70 font-mono text-sm hover:text-[#00ff00] transition-colors"
              >
                Or paste a link manually →
              </button>
            </div>

            {/* Library Items */}
            <div className="flex-1 overflow-y-auto p-3">
              {filteredLibraryItems.length === 0 ? (
                <div className="text-center py-8">
                  <p className="text-gray-500 font-mono text-sm">
                    {searchQuery ? "No items match your search" : "No items in library"}
                  </p>
                </div>
              ) : (
                <div className="grid grid-cols-3 gap-2">
                  {filteredLibraryItems.map((item) => {
                    // Build local cover URL - extract cover ID from any format and use local endpoint
                    let coverSrc: string | undefined;
                    if (item.coverUrl) {
                      // Extract cover ID from URL (handles both /api/covers/xxx and full URLs)
                      const coverIdMatch = item.coverUrl.match(/\/api\/covers\/([^/]+)$/);
                      if (coverIdMatch) {
                        // Use relative path for local/production compatibility
                        coverSrc = `/api/covers/${coverIdMatch[1]}`;
                      } else if (item.coverUrl.startsWith('/api/covers/')) {
                        // Already a relative path
                        coverSrc = item.coverUrl;
                      } else {
                        // External URL (storedon.net etc) - use as-is
                        coverSrc = item.coverUrl;
                      }
                    }
                    return (
                      <button
                        key={item.contentKey}
                        onClick={() => handleSelectFromLibrary(item)}
                        className="aspect-square rounded-lg overflow-hidden border border-[#1a1a1a] hover:border-[#00ff00]/50 transition-all hover:scale-[1.02] bg-black relative group"
                      >
                        {coverSrc ? (
                          <>
                            <img
                              src={coverSrc}
                              alt={item.title}
                              className="w-full h-full object-cover"
                              onError={(e) => {
                                // Hide broken image and show fallback
                                e.currentTarget.style.display = 'none';
                                const fallback = e.currentTarget.nextElementSibling as HTMLElement;
                                if (fallback) fallback.style.display = 'flex';
                              }}
                            />
                            {/* Fallback for broken images - same as no-cover style */}
                            <div className="w-full h-full relative bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] hidden">
                              <div className="absolute inset-0 flex items-center justify-center">
                                <img
                                  src="/app-logo.png"
                                  alt="Net Library"
                                  className="w-10 h-10 object-contain opacity-40"
                                />
                              </div>
                              <div className="absolute inset-x-0 bottom-0 p-1.5 bg-gradient-to-t from-black/90 via-black/60 to-transparent">
                                <p className="text-gray-300 font-mono text-[8px] text-center line-clamp-2 leading-tight">
                                  {item.title}
                                </p>
                              </div>
                            </div>
                            {/* Title overlay on hover - only for items with covers */}
                            <div className="absolute inset-x-0 bottom-0 p-1.5 bg-gradient-to-t from-black/90 to-transparent opacity-0 group-hover:opacity-100 transition-opacity">
                              <p className="text-white font-mono text-[9px] truncate">{item.title}</p>
                            </div>
                          </>
                        ) : (
                          /* No cover - app logo placeholder with title overlay */
                          <div className="w-full h-full relative bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a]">
                            <div className="absolute inset-0 flex items-center justify-center">
                              <img
                                src="/app-logo.png"
                                alt="Net Library"
                                className="w-10 h-10 object-contain opacity-40"
                              />
                            </div>
                            {/* Title overlay - always visible for items without covers */}
                            <div className="absolute inset-x-0 bottom-0 p-1.5 bg-gradient-to-t from-black/90 via-black/60 to-transparent">
                              <p className="text-gray-300 font-mono text-[8px] text-center line-clamp-2 leading-tight">
                                {item.title}
                              </p>
                            </div>
                          </div>
                        )}
                      </button>
                    );
                  })}
                </div>
              )}
            </div>
          </>
        )}

        {/* Edit Mode */}
        {mode === "edit" && (
          <>
            <div className="p-4 flex-1 overflow-y-auto space-y-5">
              {/* Current Selection / Preview */}
              {cdnUrl ? (
                <div className="flex gap-4 items-start">
                  {/* Preview thumbnail */}
                  <div className="w-20 h-20 rounded-xl overflow-hidden bg-black border border-[#00ff00]/30 shrink-0">
                    {coverUrl ? (
                      <img src={coverUrl} alt="" className="w-full h-full object-cover" />
                    ) : (
                      <PreviewImage
                        url={cdnUrl}
                        onMetadataFound={(foundTitle, foundCoverUrl, foundContentKey, foundMediaType, foundOperator, foundStorageType) => {
                          if (!title.trim()) setTitle(foundTitle);
                          setCoverUrl(foundCoverUrl);
                          if (foundContentKey) setContentKey(foundContentKey);
                          if (foundMediaType) setMediaType(foundMediaType);
                          if (foundOperator) setOperator(foundOperator);
                          if (foundStorageType) setStorageType(foundStorageType);
                        }}
                      />
                    )}
                  </div>
                  {/* Info */}
                  <div className="flex-1 min-w-0">
                    <p className="text-white font-mono text-sm font-medium truncate">
                      {title || "Untitled"}
                    </p>
                    <p className="text-gray-500 font-mono text-xs mt-1 truncate">
                      {cdnUrl.slice(0, 40)}...
                    </p>
                    {mediaType && (
                      <span className="inline-block mt-2 px-2 py-0.5 bg-purple-500/20 text-purple-400 font-mono text-[10px] rounded">
                        {mediaType}
                      </span>
                    )}
                  </div>
                  {/* Change button */}
                  <button
                    onClick={() => {
                      handleClearCell();
                      setMode("browse");
                    }}
                    className="px-3 py-1.5 rounded-lg bg-[#1a1a1a] text-gray-400 hover:text-white font-mono text-xs transition-colors shrink-0"
                  >
                    Change
                  </button>
                </div>
              ) : (
                /* Empty state - prompt to browse */
                <button
                  onClick={() => setMode("browse")}
                  className="w-full py-8 rounded-xl border-2 border-dashed border-[#1a1a1a] hover:border-[#00ff00]/30 transition-colors flex flex-col items-center"
                >
                  <LibraryIcon size={32} className="text-[#00ff00] mb-2" />
                  <p className="text-gray-400 font-mono text-sm">Browse Library</p>
                  <p className="text-gray-600 font-mono text-xs mt-1">Select an item to add</p>
                </button>
              )}

              {/* URL Input (for manual entry) */}
              <div>
                <label className="block text-gray-400 font-mono text-xs mb-2">
                  Link URL
                </label>
                <input
                  type="url"
                  value={cdnUrl}
                  onChange={(e) => setCdnUrl(e.target.value)}
                  placeholder="https://... or ipfs://..."
                  className="w-full px-4 py-3 rounded-xl bg-black border border-[#1a1a1a] text-white font-mono text-sm placeholder:text-gray-600 focus:border-[#00ff00]/30 focus:outline-none transition-colors"
                  style={{ fontSize: "16px" }}
                />
              </div>

              {/* Title Input */}
              <div>
                <label className="block text-gray-400 font-mono text-xs mb-2">
                  Title <span className="text-gray-600">(optional)</span>
                </label>
                <input
                  type="text"
                  value={title}
                  onChange={(e) => setTitle(e.target.value)}
                  placeholder="Give it a name..."
                  maxLength={100}
                  className="w-full px-4 py-3 rounded-xl bg-black border border-[#1a1a1a] text-white font-mono text-sm placeholder:text-gray-600 focus:border-[#00ff00]/30 focus:outline-none transition-colors"
                  style={{ fontSize: "16px" }}
                />
              </div>

              {/* Error */}
              {error && (
                <div className="p-3 rounded-xl bg-red-500/10 border border-red-500/30">
                  <p className="text-red-400 font-mono text-sm">{error}</p>
                </div>
              )}
            </div>

            {/* Footer Actions */}
            <div className="p-4 border-t border-[#1a1a1a] space-y-3">
              {/* Main actions */}
              <div className="flex gap-3">
                <button
                  onClick={onClose}
                  className="flex-1 py-3.5 rounded-xl font-mono text-sm bg-[#1a1a1a] text-gray-400 hover:text-white transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleSave}
                  disabled={!cdnUrl.trim() || isSaving}
                  className="flex-1 py-3.5 rounded-xl font-mono text-sm bg-[#00ff00] text-black font-medium hover:bg-[#00dd00] transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isSaving ? "Saving..." : existingCell ? "Update" : "Add"}
                </button>
              </div>

              {/* Remove option for existing cells */}
              {existingCell && (
                <button
                  onClick={() => setMode("confirm-remove")}
                  className="w-full py-2.5 text-red-400/70 font-mono text-sm hover:text-red-400 transition-colors"
                >
                  Remove from grid
                </button>
              )}
            </div>
          </>
        )}
      </div>
    </div>,
    document.body
  );
}

// Auto-advance timing by media type (in milliseconds)
const AUTO_ADVANCE_TIMING: Record<GridMediaType, number> = {
  image: 4000,   // 4 seconds for static images
  gif: 6000,     // 6 seconds for GIFs (let animation play)
  video: 0,      // Don't auto-advance videos (wait for end)
  audio: 0,      // Don't auto-advance audio (wait for end)
  text: 8000,    // 8 seconds for text files (give time to read)
};

// Full-screen Grid Cell Viewer with navigation and auto-advance
function GridCellViewer({
  cell,
  cells,
  currentIndex,
  onClose,
  onNavigate,
  isOwner,
  onEdit,
  onViewItemDetail,
}: {
  cell: GridCell;
  cells: GridCell[];
  currentIndex: number;
  onClose: () => void;
  onNavigate: (index: number) => void;
  isOwner?: boolean;
  onEdit?: (row: number, col: number) => void;
  /** Called when user taps on the title to view the full item detail page */
  onViewItemDetail?: (contentKey: string) => void;
}) {
  const mediaType: GridMediaType = cell.mediaType || detectGridMediaType(cell.cdnUrl, cell.contentType);
  const borderColor = getMediaTypeBorderColor(mediaType);
  const isVideo = (cell.contentType || '').startsWith("video/") || mediaType === "video";
  const isAudio = mediaType === "audio";
  const isText = mediaType === "text";

  // Build raw media URL for playback
  const rawMediaUrl = toRawMediaUrl(cell);

  // Debug: log media and navigation data for troubleshooting
  console.log("[GridCellViewer] Cell:", {
    cdnUrl: cell.cdnUrl,
    rawMediaUrl,
    operator: cell.operator,
    contentKey: cell.contentKey,
    storageType: cell.storageType,
    contentType: cell.contentType,
    cellMediaType: cell.mediaType,
    detectedMediaType: mediaType,
    isVideo,
    isAudio,
    isText,
    title: cell.title,
    coverUrl: cell.coverUrl,
    hasOnViewItemDetail: !!onViewItemDetail,
  });

  // Animation state
  const [isTransitioning, setIsTransitioning] = useState(false);
  const [slideDirection, setSlideDirection] = useState<"left" | "right" | null>(null);
  const [isEntering, setIsEntering] = useState(true);

  // Fullscreen video state (for proper aspect ratio viewing)
  const [isVideoFullscreen, setIsVideoFullscreen] = useState(false);
  const videoRef = useRef<HTMLVideoElement>(null);

  // Portal mount state - ensures we only render portal on client
  const [portalContainer, setPortalContainer] = useState<HTMLElement | null>(null);

  // Setup portal container and scroll handling
  useEffect(() => {
    // Set portal container to document body for true fixed positioning
    setPortalContainer(document.body);

    const timer = setTimeout(() => setIsEntering(false), 50);

    // Scroll ALL potential scroll containers to top
    window.scrollTo({ top: 0, behavior: 'instant' });
    document.documentElement.scrollTop = 0;
    document.body.scrollTop = 0;

    // Also scroll any overflow containers in the DOM tree
    const scrollContainers = document.querySelectorAll('[class*="overflow"]');
    scrollContainers.forEach(el => {
      if (el instanceof HTMLElement) {
        el.scrollTop = 0;
      }
    });

    // Lock body scroll
    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';

    return () => {
      clearTimeout(timer);
      document.body.style.overflow = originalOverflow;
    };
  }, []);

  // Auto-advance state
  const [autoAdvanceEnabled, setAutoAdvanceEnabled] = useState(true);
  const [autoAdvanceProgress, setAutoAdvanceProgress] = useState(0);
  const autoAdvanceTimerRef = useRef<NodeJS.Timeout | null>(null);
  const progressIntervalRef = useRef<NodeJS.Timeout | null>(null);

  // Navigation - with media-only mode for auto-advance
  const hasPrev = currentIndex > 0;
  const hasNext = currentIndex < cells.length - 1;

  // Find next playable media cell (for auto-advance)
  const findNextPlayableIndex = useCallback((fromIndex: number): number | null => {
    for (let i = fromIndex + 1; i < cells.length; i++) {
      const cellMediaType = cells[i].mediaType || detectGridMediaType(cells[i].cdnUrl, cells[i].contentType);
      if (isPlayableMedia(cellMediaType)) {
        return i;
      }
    }
    return null;
  }, [cells]);

  // Find previous playable media cell
  const findPrevPlayableIndex = useCallback((fromIndex: number): number | null => {
    for (let i = fromIndex - 1; i >= 0; i--) {
      const cellMediaType = cells[i].mediaType || detectGridMediaType(cells[i].cdnUrl, cells[i].contentType);
      if (isPlayableMedia(cellMediaType)) {
        return i;
      }
    }
    return null;
  }, [cells]);

  // Check if there are more playable cells
  const hasNextPlayable = findNextPlayableIndex(currentIndex) !== null;
  const _hasPrevPlayable = findPrevPlayableIndex(currentIndex) !== null;

  // Clear auto-advance timers
  const clearAutoAdvance = useCallback(() => {
    if (autoAdvanceTimerRef.current) {
      clearTimeout(autoAdvanceTimerRef.current);
      autoAdvanceTimerRef.current = null;
    }
    if (progressIntervalRef.current) {
      clearInterval(progressIntervalRef.current);
      progressIntervalRef.current = null;
    }
    setAutoAdvanceProgress(0);
  }, []);

  // Navigate with animation
  const navigateWithAnimation = useCallback((index: number, direction: "left" | "right") => {
    if (isTransitioning) return;

    clearAutoAdvance();
    setSlideDirection(direction);
    setIsTransitioning(true);

    // Wait for exit animation, then navigate
    setTimeout(() => {
      onNavigate(index);
      setIsTransitioning(false);
      setSlideDirection(null);
    }, 200);
  }, [isTransitioning, clearAutoAdvance, onNavigate]);

  const handlePrev = useCallback(() => {
    if (hasPrev) {
      navigateWithAnimation(currentIndex - 1, "right");
    }
  }, [hasPrev, currentIndex, navigateWithAnimation]);

  const handleNext = useCallback(() => {
    if (hasNext) {
      navigateWithAnimation(currentIndex + 1, "left");
    }
  }, [hasNext, currentIndex, navigateWithAnimation]);

  // Navigate to next playable cell (skips non-playable media)
  const handleNextPlayable = useCallback(() => {
    const nextIndex = findNextPlayableIndex(currentIndex);
    if (nextIndex !== null) {
      navigateWithAnimation(nextIndex, "left");
    }
  }, [currentIndex, findNextPlayableIndex, navigateWithAnimation]);

  // Auto-advance effect - skips to next playable cell when current is playable
  useEffect(() => {
    if (!autoAdvanceEnabled || isTransitioning) {
      clearAutoAdvance();
      return;
    }

    const timing = AUTO_ADVANCE_TIMING[mediaType];
    if (timing === 0) {
      // Don't auto-advance for video/audio - they have their own end handlers
      return;
    }

    // Check if there's a next playable cell to advance to
    if (!hasNextPlayable && !hasNext) {
      return;
    }

    // Start progress animation
    const startTime = Date.now();
    progressIntervalRef.current = setInterval(() => {
      const elapsed = Date.now() - startTime;
      const progress = Math.min((elapsed / timing) * 100, 100);
      setAutoAdvanceProgress(progress);
    }, 50);

    // Set auto-advance timer - skip to next playable if current is playable media
    autoAdvanceTimerRef.current = setTimeout(() => {
      if (isPlayableMedia(mediaType) && hasNextPlayable) {
        // Skip non-playable cells
        handleNextPlayable();
      } else if (hasNext) {
        // Normal advance for non-playable content
        handleNext();
      }
    }, timing);

    return () => clearAutoAdvance();
  }, [currentIndex, mediaType, autoAdvanceEnabled, hasNext, hasNextPlayable, isTransitioning, clearAutoAdvance, handleNext, handleNextPlayable]);

  // Handle video/audio end - auto-advance to next playable when media finishes
  const handleMediaEnded = useCallback(() => {
    if (autoAdvanceEnabled) {
      if (hasNextPlayable) {
        // Skip to next playable cell
        handleNextPlayable();
      } else if (hasNext) {
        // Fallback to next cell if no more playable cells
        handleNext();
      }
    }
  }, [autoAdvanceEnabled, hasNext, hasNextPlayable, handleNext, handleNextPlayable]);

  // Pause auto-advance on user interaction
  const pauseAutoAdvance = useCallback(() => {
    setAutoAdvanceEnabled(false);
    clearAutoAdvance();
  }, [clearAutoAdvance]);

  // Keyboard navigation
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      pauseAutoAdvance();
      if (e.key === "ArrowLeft") {
        handlePrev();
      } else if (e.key === "ArrowRight") {
        handleNext();
      } else if (e.key === "Escape") {
        onClose();
      } else if (e.key === " ") {
        // Space toggles auto-advance
        e.preventDefault();
        setAutoAdvanceEnabled(prev => !prev);
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [handlePrev, handleNext, onClose, pauseAutoAdvance]);

  // Swipe handling for mobile
  const touchStartX = useRef<number | null>(null);

  const handleTouchStart = (e: React.TouchEvent) => {
    touchStartX.current = e.touches[0].clientX;
    pauseAutoAdvance();
  };

  const handleTouchEnd = (e: React.TouchEvent) => {
    if (touchStartX.current === null) return;

    const touchEndX = e.changedTouches[0].clientX;
    const diff = touchStartX.current - touchEndX;

    if (Math.abs(diff) > 50) {
      if (diff > 0 && hasNext) {
        handleNext();
      } else if (diff < 0 && hasPrev) {
        handlePrev();
      }
    }

    touchStartX.current = null;
  };

  // Animation classes
  const getAnimationClass = () => {
    if (!isTransitioning) return "opacity-100 scale-100";
    if (slideDirection === "left") return "opacity-0 -translate-x-8 scale-95";
    if (slideDirection === "right") return "opacity-0 translate-x-8 scale-95";
    return "opacity-100 scale-100";
  };

  // Render via portal to document.body to escape any CSS containment/transforms
  // that might affect fixed positioning from ancestor elements
  const viewerContent = (
    <div
      className={`fixed inset-0 z-[100] flex flex-col transition-all duration-300 ${
        isEntering ? "bg-black/0" : "bg-black"
      }`}
      style={{ paddingTop: 'env(safe-area-inset-top, 0px)' }}
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
    >
      {/* Header - responsive padding, accounts for Farcaster frame chrome */}
      <div className={`shrink-0 p-3 sm:p-4 md:p-6 flex items-center justify-between transition-all duration-300 ${
        isEntering ? "opacity-0 -translate-y-4" : "opacity-100 translate-y-0"
      }`}>
        <button
          onClick={onClose}
          className="w-11 h-11 sm:w-10 sm:h-10 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#2a2a2a] transition-colors"
          aria-label="Close viewer"
        >
          ←
        </button>

        <div className="text-center flex-1 mx-2">
          {/* Title - clickable if has contentKey, otherwise just text */}
          {cell.title && cell.contentKey && onViewItemDetail ? (
            <button
              onClick={() => {
                pauseAutoAdvance();
                onViewItemDetail(cell.contentKey!);
              }}
              className="text-white font-mono text-sm truncate max-w-[150px] sm:max-w-[200px] md:max-w-[300px] mx-auto hover:text-[#00ff00] underline underline-offset-2 transition-colors"
            >
              {cell.title}
            </button>
          ) : cell.title ? (
            <p className="text-white font-mono text-sm truncate max-w-[150px] sm:max-w-[200px] md:max-w-[300px] mx-auto">{cell.title}</p>
          ) : null}
          <p className="text-gray-500 font-mono text-xs">
            {currentIndex + 1} of {cells.length}
          </p>
        </div>

        <div className="flex items-center gap-1.5 sm:gap-2">
          {/* Auto-advance toggle - minimum touch target size */}
          <button
            onClick={() => setAutoAdvanceEnabled(prev => !prev)}
            className={`w-11 h-11 sm:w-10 sm:h-10 rounded-full flex items-center justify-center text-sm transition-colors ${
              autoAdvanceEnabled
                ? "bg-[#00ff00]/20 text-[#00ff00]"
                : "bg-[#1a1a1a] text-gray-500"
            }`}
            title={autoAdvanceEnabled ? "Auto-advance ON" : "Auto-advance OFF"}
            aria-label={autoAdvanceEnabled ? "Pause auto-advance" : "Enable auto-advance"}
          >
            {autoAdvanceEnabled ? <PlayIcon size={16} /> : <PauseIcon size={16} />}
          </button>

          {/* Edit button for owners */}
          {isOwner && onEdit && (
            <button
              onClick={() => onEdit(cell.row, cell.col)}
              className="w-11 h-11 sm:w-10 sm:h-10 rounded-full bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-[#00ff00] hover:bg-[#2a2a2a] transition-colors"
              title="Edit this cell"
              aria-label="Edit cell"
            >
              <PencilIcon size={16} />
            </button>
          )}
        </div>
      </div>

      {/* Auto-advance progress bar */}
      {autoAdvanceEnabled && hasNext && AUTO_ADVANCE_TIMING[mediaType] > 0 && (
        <div className="shrink-0 h-1 bg-[#1a1a1a]">
          <div
            className="h-full bg-[#00ff00] transition-all duration-100"
            style={{ width: `${autoAdvanceProgress}%` }}
          />
        </div>
      )}

      {/* Main content area - responsive padding and sizing */}
      <div className="flex-1 flex items-center justify-center p-2 sm:p-4 md:p-6 relative min-h-0">
        {/* Previous button - responsive size and position */}
        {hasPrev && (
          <button
            onClick={() => {
              pauseAutoAdvance();
              handlePrev();
            }}
            className="absolute left-1 sm:left-2 md:left-4 top-1/2 -translate-y-1/2 w-11 h-11 sm:w-12 sm:h-12 md:w-14 md:h-14 rounded-full bg-black/50 border border-white/20 flex items-center justify-center text-white text-lg sm:text-xl md:text-2xl hover:bg-black/70 transition-colors z-10"
            aria-label="Previous"
          >
            ‹
          </button>
        )}

        {/* Media display with animation - responsive max heights */}
        <div
          className={`max-w-full max-h-full rounded-lg sm:rounded-xl overflow-hidden border-2 transition-all ${
            isEntering ? "duration-300 scale-90 opacity-0" : "duration-200"
          } ${getAnimationClass()}`}
          style={{ borderColor, boxShadow: `0 0 40px ${borderColor}40` }}
        >
          {isVideo ? (
            <div className="relative">
              <video
                ref={videoRef}
                key={cell.cdnUrl}
                src={toRawMediaUrl(cell)}
                className="max-w-full max-h-[60vh] sm:max-h-[65vh] md:max-h-[70vh] lg:max-h-[75vh] object-contain"
                controls
                autoPlay
                playsInline
                onEnded={handleMediaEnded}
                onError={(e) => console.error("[GridCellViewer] Video error:", e.currentTarget.error?.message, "src:", toRawMediaUrl(cell))}
                onLoadStart={() => console.log("[GridCellViewer] Video loading:", toRawMediaUrl(cell))}
              />
              {/* Expand to native ratio button */}
              <button
                onClick={() => setIsVideoFullscreen(true)}
                className="absolute top-2 right-2 w-10 h-10 rounded-lg bg-black/70 border border-white/30 text-white flex items-center justify-center hover:bg-black/90 transition-colors"
                title="View at native ratio"
              >
                <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <polyline points="15 3 21 3 21 9"></polyline>
                  <polyline points="9 21 3 21 3 15"></polyline>
                  <line x1="21" y1="3" x2="14" y2="10"></line>
                  <line x1="3" y1="21" x2="10" y2="14"></line>
                </svg>
              </button>
            </div>
          ) : isAudio ? (
            <div className="w-64 sm:w-80 md:w-96 p-4 sm:p-6 bg-[#1a1a1a] flex flex-col items-center gap-3 sm:gap-4">
              {/* Show cover art if available, otherwise show music icon */}
              {cell.coverUrl ? (
                <img
                  src={toGatewayUrl(cell.coverUrl)}
                  alt={cell.title || "Audio"}
                  className="w-24 h-24 sm:w-32 sm:h-32 rounded-xl object-cover"
                />
              ) : (
                <div className="w-24 h-24 sm:w-32 sm:h-32 rounded-xl bg-gradient-to-br from-purple-500/30 to-purple-900/30 flex items-center justify-center">
                  <span className="text-4xl sm:text-5xl">♪</span>
                </div>
              )}
              <p className="text-white font-mono text-xs sm:text-sm text-center truncate max-w-full">
                {cell.title || "Audio"}
              </p>
              <audio
                key={cell.cdnUrl}
                src={toRawMediaUrl(cell)}
                className="w-full"
                controls
                autoPlay
                onEnded={handleMediaEnded}
                onError={(e) => console.error("[GridCellViewer] Audio error:", e.currentTarget.error?.message, "src:", toRawMediaUrl(cell))}
                onLoadStart={() => console.log("[GridCellViewer] Audio loading:", toRawMediaUrl(cell))}
              />
            </div>
          ) : isText ? (
            <div className="w-64 sm:w-80 md:w-96 p-4 sm:p-6 bg-[#1a1a1a] flex flex-col items-center gap-3 sm:gap-4">
              <div className="w-24 h-24 sm:w-32 sm:h-32 rounded-xl bg-gradient-to-br from-white/20 to-gray-500/20 flex items-center justify-center">
                <DocumentIcon size={48} className="text-white" />
              </div>
              <p className="text-white font-mono text-xs sm:text-sm text-center truncate max-w-full">
                {cell.title || "Text File"}
              </p>
              <a
                href={toGatewayUrl(cell.cdnUrl)}
                target="_blank"
                rel="noopener noreferrer"
                className="px-4 py-2.5 sm:py-2 rounded-lg bg-white/10 border border-white/30 text-white font-mono text-sm hover:bg-white/20 transition-colors min-h-[44px] flex items-center justify-center"
              >
                Open File
              </a>
            </div>
          ) : (
            <img
              key={cell.cdnUrl}
              src={toGatewayUrl(cell.coverUrl || cell.cdnUrl)}
              alt={cell.title || "Grid cell"}
              className="max-w-full max-h-[60vh] sm:max-h-[65vh] md:max-h-[70vh] lg:max-h-[75vh] object-contain"
            />
          )}
        </div>

        {/* Next button - responsive size and position */}
        {hasNext && (
          <button
            onClick={() => {
              pauseAutoAdvance();
              handleNext();
            }}
            className="absolute right-1 sm:right-2 md:right-4 top-1/2 -translate-y-1/2 w-11 h-11 sm:w-12 sm:h-12 md:w-14 md:h-14 rounded-full bg-black/50 border border-white/20 flex items-center justify-center text-white text-lg sm:text-xl md:text-2xl hover:bg-black/70 transition-colors z-10"
            aria-label="Next"
          >
            ›
          </button>
        )}
      </div>

      {/* Progress indicator - responsive padding */}
      <div className={`shrink-0 p-3 sm:p-4 pb-6 sm:pb-4 transition-all duration-300 ${
        isEntering ? "opacity-0 translate-y-4" : "opacity-100 translate-y-0"
      }`}>
        <div className="flex justify-center gap-1 sm:gap-1.5 flex-wrap max-w-xs sm:max-w-sm md:max-w-md mx-auto">
          {cells.length <= 20 ? (
            // Show dots for smaller grids - larger touch targets on mobile
            cells.map((c, index) => {
              const dotMediaType = c.mediaType || detectGridMediaType(c.cdnUrl, c.contentType);
              const dotColor = getMediaTypeBorderColor(dotMediaType);
              return (
                <button
                  key={index}
                  onClick={() => {
                    pauseAutoAdvance();
                    onNavigate(index);
                  }}
                  className={`rounded-full transition-all min-w-[24px] min-h-[24px] sm:min-w-0 sm:min-h-0 flex items-center justify-center ${
                    index === currentIndex ? "w-6 sm:w-6 h-2.5 sm:h-2" : "w-2.5 sm:w-2 h-2.5 sm:h-2 hover:scale-125"
                  }`}
                  style={{
                    backgroundColor: index === currentIndex ? dotColor : `${dotColor}50`,
                  }}
                  aria-label={`Go to item ${index + 1}`}
                />
              );
            })
          ) : (
            // Show compact progress for larger grids - responsive sizing
            <div className="flex items-center gap-2 sm:gap-3">
              <span className="text-white font-mono text-xs sm:text-sm">{currentIndex + 1}</span>
              <div className="w-24 sm:w-32 md:w-40 h-1.5 sm:h-1 bg-[#1a1a1a] rounded-full overflow-hidden">
                <div
                  className="h-full bg-white transition-all"
                  style={{ width: `${cells.length > 0 ? ((currentIndex + 1) / cells.length) * 100 : 0}%` }}
                />
              </div>
              <span className="text-gray-500 font-mono text-xs sm:text-sm">{cells.length}</span>
            </div>
          )}
        </div>
      </div>

      {/* Fullscreen video overlay - shows video at native aspect ratio */}
      {isVideoFullscreen && isVideo && (
        <div
          className="fixed inset-0 z-[110] bg-black flex items-center justify-center"
          style={{ paddingTop: 'env(safe-area-inset-top, 0px)' }}
          onClick={() => setIsVideoFullscreen(false)}
        >
          {/* Close button */}
          <button
            onClick={() => setIsVideoFullscreen(false)}
            className="absolute top-4 right-4 w-12 h-12 rounded-full bg-white/10 border border-white/30 text-white flex items-center justify-center hover:bg-white/20 transition-colors z-10"
            title="Close fullscreen"
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <line x1="18" y1="6" x2="6" y2="18"></line>
              <line x1="6" y1="6" x2="18" y2="18"></line>
            </svg>
          </button>

          {/* Video at native ratio - click on video doesn't close */}
          <video
            src={toRawMediaUrl(cell)}
            className="max-w-[98vw] max-h-[98vh] object-contain"
            controls
            autoPlay
            playsInline
            onClick={(e) => e.stopPropagation()}
            onEnded={handleMediaEnded}
          />
        </div>
      )}
    </div>
  );

  // Use portal to render at document.body level, escaping any ancestor CSS containment
  // This ensures the fixed positioning works correctly regardless of scroll position
  if (!portalContainer) {
    return null; // Don't render until portal container is ready (client-side only)
  }

  return createPortal(viewerContent, portalContainer);
}

// Edit Grid Modal - for editing name, subtitle, description, visibility
function EditGridModal({
  grid,
  onClose,
  onSaved,
}: {
  grid: GridWithStats;
  onClose: () => void;
  onSaved: () => void;
}) {
  const { address } = useAccount();
  const [name, setName] = useState(grid.name);
  const [subtitle, setSubtitle] = useState(grid.subtitle || "");
  const [description, setDescription] = useState(grid.description || "");
  const [visibility, setVisibility] = useState(grid.visibility);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSave = async () => {
    if (!address || !name.trim()) return;

    setIsSaving(true);
    setError(null);

    try {
      const response = await fetch("/api/grids", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          gridId: grid.id,
          action: "update-metadata",
          creator: address,
          name: name.trim(),
          subtitle: subtitle.trim() || undefined,
          description: description.trim() || undefined,
          visibility,
        }),
      });

      const data = await response.json();

      if (!data.success) {
        throw new Error(data.error || "Failed to update grid");
      }

      onSaved();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to update grid");
    } finally {
      setIsSaving(false);
    }
  };

  return (
    <div className="fixed inset-0 z-50 flex items-start justify-center p-3 sm:p-4 pt-16 sm:pt-20 pb-20 sm:pb-24 bg-black/80 overflow-y-auto">
      <div className="w-full max-w-[calc(100%-1.5rem)] sm:max-w-sm md:max-w-md bg-[#0a0a0a] border border-[#1a1a1a] rounded-xl sm:rounded-2xl overflow-hidden max-h-[80vh] sm:max-h-[75vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center p-3 sm:p-4 border-b border-[#1a1a1a] shrink-0">
          <h2 className="text-[#00ff00] font-mono text-base sm:text-lg">Edit Grid</h2>
        </div>

        {/* Content */}
        <div className="p-3 sm:p-4 space-y-4 overflow-y-auto flex-1">
          {/* Name input */}
          <div>
            <label className="block text-gray-400 font-mono text-sm mb-2">
              Grid Name *
            </label>
            <input
              type="text"
              value={name}
              onChange={(e) => setName(e.target.value)}
              placeholder="My Collection"
              maxLength={50}
              className="w-full px-4 py-3 rounded-lg bg-black border border-[#1a1a1a] text-white font-mono placeholder:text-gray-600 focus:border-[#00ff00]/30 focus:outline-none transition-colors"
              style={{ fontSize: "16px" }}
            />
          </div>

          {/* Subtitle input */}
          <div>
            <label className="block text-gray-400 font-mono text-sm mb-2">
              Subtitle <span className="text-gray-600">(optional)</span>
            </label>
            <input
              type="text"
              value={subtitle}
              onChange={(e) => setSubtitle(e.target.value)}
              placeholder="A short tagline..."
              maxLength={100}
              className="w-full px-4 py-3 rounded-lg bg-black border border-[#1a1a1a] text-white font-mono placeholder:text-gray-600 focus:border-[#00ff00]/30 focus:outline-none transition-colors"
              style={{ fontSize: "16px" }}
            />
          </div>

          {/* Description input */}
          <div>
            <label className="block text-gray-400 font-mono text-sm mb-2">
              Description <span className="text-gray-600">(optional)</span>
            </label>
            <textarea
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="Tell people what this grid is about..."
              maxLength={500}
              rows={3}
              className="w-full px-4 py-3 rounded-lg bg-black border border-[#1a1a1a] text-white font-mono placeholder:text-gray-600 focus:border-[#00ff00]/30 focus:outline-none transition-colors resize-none"
              style={{ fontSize: "16px" }}
            />
            <p className="text-gray-600 font-mono text-xs mt-1 text-right">
              {description.length}/500
            </p>
          </div>

          {/* Visibility toggle */}
          <div>
            <label className="block text-gray-400 font-mono text-sm mb-2">
              Visibility
            </label>
            <div className="flex gap-2">
              <button
                onClick={() => setVisibility("public")}
                className={`flex-1 py-3 px-3 rounded-lg font-mono text-sm border transition-all min-h-[48px] ${
                  visibility === "public"
                    ? "bg-[#00ff00]/10 border-[#00ff00]/30 text-[#00ff00]"
                    : "bg-black border-[#1a1a1a] text-gray-400 hover:border-[#00ff00]/20"
                }`}
              >
                Public
              </button>
              <button
                onClick={() => setVisibility("hidden")}
                className={`flex-1 py-3 px-3 rounded-lg font-mono text-sm border transition-all min-h-[48px] ${
                  visibility === "hidden"
                    ? "bg-[#00ff00]/10 border-[#00ff00]/30 text-[#00ff00]"
                    : "bg-black border-[#1a1a1a] text-gray-400 hover:border-[#00ff00]/20"
                }`}
              >
                Hidden
              </button>
            </div>
          </div>

          {/* Error */}
          {error && (
            <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30">
              <p className="text-red-400 font-mono text-sm">{error}</p>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-3 sm:p-4 border-t border-[#1a1a1a] shrink-0">
          <div className="flex gap-2">
            <button
              onClick={onClose}
              className="flex-1 py-3.5 sm:py-3 rounded-lg font-mono text-sm bg-[#1a1a1a] text-gray-400 hover:text-white active:bg-[#2a2a2a] transition-colors min-h-[48px] sm:min-h-0"
            >
              Cancel
            </button>
            <button
              onClick={handleSave}
              disabled={!name.trim() || isSaving}
              className="flex-1 py-3.5 sm:py-3 rounded-lg font-mono text-sm bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/20 active:bg-[#00ff00]/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed min-h-[48px] sm:min-h-0"
            >
              {isSaving ? "Saving..." : "Save"}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}
src/features/app/components/grid-import-modal.tsx
"use client";

import { useState, useCallback, useRef, useEffect } from "react";
import { createPortal } from "react-dom";
import { useAccount } from "wagmi";
import { useFarcasterLaunchParams } from "@/neynar-farcaster-sdk/mini";
import { useGrids } from "@/hooks/use-grids";
import { calculateGridSize, requiresGridUnlock, GRID_UNLOCK_PRICE_USD } from "@/lib/net-protocol";
import type { GridVisibility, GridWithStats } from "@/lib/net-protocol";

interface GridImportModalProps {
  isOpen: boolean;
  onClose: () => void;
  existingGrids?: GridWithStats[];
  onImported?: (gridId: string) => void;
}

interface ParsedLink {
  url: string;
  title?: string;
  isValid: boolean;
  error?: string;
}

interface ParseResult {
  links: ParsedLink[];
  validCount: number;
  invalidCount: number;
  duplicateCount: number;
}

type ImportStep = "upload" | "destination" | "new-grid" | "select-grid" | "importing";
type ImportDestination = "new" | "existing";

export function GridImportModal({ isOpen, onClose, existingGrids = [], onImported }: GridImportModalProps) {
  const { address } = useAccount();
  const farcasterLaunchParams = useFarcasterLaunchParams();
  const { createGrid } = useGrids({ autoFetch: false });

  const fileInputRef = useRef<HTMLInputElement | null>(null);

  const [step, setStep] = useState<ImportStep>("upload");
  const [parseResult, setParseResult] = useState<ParseResult | null>(null);
  const [destination, setDestination] = useState<ImportDestination>("new");
  const [selectedGridId, setSelectedGridId] = useState<string | null>(null);

  // New grid settings
  const [gridName, setGridName] = useState("");
  const [visibility, setVisibility] = useState<GridVisibility>("public");

  const [_isImporting, setIsImporting] = useState(false);
  const [importProgress, setImportProgress] = useState(0);
  const [error, setError] = useState<string | null>(null);

  const handleFileSelect = useCallback(async (file: File) => {
    setError(null);

    try {
      const text = await file.text();
      const result = parseImportFile(text, file.name);
      setParseResult(result);

      if (result.validCount > 0) {
        setStep("destination");
      } else {
        setError("No valid links found in file");
      }
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to parse file");
    }
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    const file = e.dataTransfer.files[0];
    if (file) handleFileSelect(file);
  }, [handleFileSelect]);

  // Use portal to render modal at document root
  const [mounted, setMounted] = useState(false);
  useEffect(() => {
    setMounted(true);
  }, []);

  if (!isOpen || !mounted) return null;

  const handleDestinationSelect = (dest: ImportDestination) => {
    setDestination(dest);
    if (dest === "new") {
      setStep("new-grid");
    } else {
      setStep("select-grid");
    }
  };

  const handleImport = async () => {
    if (!address || !parseResult) return;

    setIsImporting(true);
    setStep("importing");
    setError(null);

    try {
      let targetGridId: string;

      // Create new grid if needed
      if (destination === "new") {
        const calculatedSize = calculateGridSize(parseResult.validCount);
        const fidString = farcasterLaunchParams?.get('fid');
        const grid = await createGrid({
          name: gridName.trim() || "Imported Grid",
          size: calculatedSize,
          visibility,
          creator: address,
          creatorFid: fidString ? parseInt(fidString, 10) : undefined,
        });

        if (!grid) {
          throw new Error("Failed to create grid");
        }

        targetGridId = grid.id;
      } else {
        if (!selectedGridId) {
          throw new Error("No grid selected");
        }
        targetGridId = selectedGridId;
      }

      // Import cells in batches
      const validLinks = parseResult.links.filter((l) => l.isValid);
      const batchSize = 10;
      let processed = 0;

      for (let i = 0; i < validLinks.length; i += batchSize) {
        const batch = validLinks.slice(i, i + batchSize);

        await Promise.all(
          batch.map(async (link, batchIndex) => {
            const index = i + batchIndex;
            const gridSize = calculateGridSize(validLinks.length);
            const row = Math.floor(index / gridSize);
            const col = index % gridSize;

            await fetch("/api/grids", {
              method: "PUT",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                gridId: targetGridId,
                action: "add-cell",
                creator: address,
                row,
                col,
                cdnUrl: link.url,
                title: link.title,
              }),
            });
          })
        );

        processed += batch.length;
        setImportProgress(Math.round((processed / validLinks.length) * 100));
      }

      onImported?.(targetGridId);
      handleClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Import failed");
      setStep("destination");
    } finally {
      setIsImporting(false);
    }
  };

  const handleClose = () => {
    setStep("upload");
    setParseResult(null);
    setDestination("new");
    setSelectedGridId(null);
    setGridName("");
    setVisibility("public");
    setImportProgress(0);
    setError(null);
    onClose();
  };

  const calculatedSize = parseResult ? calculateGridSize(parseResult.validCount) : 0;
  const needsUnlock = requiresGridUnlock(calculatedSize);

  const modalContent = (
    <div className="fixed inset-0 z-[9999] flex items-start justify-center p-3 sm:p-4 pt-16 sm:pt-20 pb-20 sm:pb-24 bg-black/80 overflow-y-auto">
      <div className="w-full max-w-[calc(100%-1.5rem)] sm:max-w-md md:max-w-lg bg-[#0a0a0a] border border-[#1a1a1a] rounded-xl sm:rounded-2xl overflow-hidden max-h-[80vh] sm:max-h-[75vh] flex flex-col">
        {/* Header - responsive */}
        <div className="shrink-0 flex items-center p-3 sm:p-4 border-b border-[#1a1a1a]">
          <div className="flex items-center gap-2">
            {step !== "upload" && step !== "importing" && (
              <button
                onClick={() => {
                  if (step === "destination") setStep("upload");
                  else if (step === "new-grid" || step === "select-grid") setStep("destination");
                }}
                className="w-10 h-10 sm:w-8 sm:h-8 rounded-lg bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white transition-colors"
                aria-label="Go back"
              >
                ←
              </button>
            )}
            <h2 className="text-[#00ff00] font-mono text-base sm:text-lg">
              {step === "upload" && "Bulk Import"}
              {step === "destination" && `Import ${parseResult?.validCount} Items`}
              {step === "new-grid" && "New Grid Settings"}
              {step === "select-grid" && "Select Grid"}
              {step === "importing" && "Importing..."}
            </h2>
          </div>
        </div>

        {/* Content - responsive padding */}
        <div className="flex-1 overflow-y-auto p-3 sm:p-4">
          {step === "upload" && (
            <UploadStep
              onFileSelect={handleFileSelect}
              onDrop={handleDrop}
              fileInputRef={fileInputRef}
              error={error}
            />
          )}

          {step === "destination" && parseResult && (
            <DestinationStep
              parseResult={parseResult}
              calculatedSize={calculatedSize}
              needsUnlock={needsUnlock}
              onSelect={handleDestinationSelect}
              error={error}
            />
          )}

          {step === "new-grid" && parseResult && (
            <NewGridStep
              name={gridName}
              onNameChange={setGridName}
              visibility={visibility}
              onVisibilityChange={setVisibility}
              calculatedSize={calculatedSize}
              needsUnlock={needsUnlock}
            />
          )}

          {step === "select-grid" && parseResult && (
            <SelectGridStep
              grids={existingGrids}
              selectedId={selectedGridId}
              onSelect={setSelectedGridId}
              itemCount={parseResult.validCount}
            />
          )}

          {step === "importing" && (
            <ImportingStep
              progress={importProgress}
              error={error}
              totalItems={parseResult?.validCount || 0}
            />
          )}
        </div>

        {/* Footer - responsive with touch targets */}
        {step !== "importing" && (
          <div className="shrink-0 p-3 sm:p-4 border-t border-[#1a1a1a]">
            {(step === "new-grid" || step === "select-grid") && (
              <button
                onClick={handleImport}
                disabled={
                  (step === "new-grid" && !gridName.trim()) ||
                  (step === "select-grid" && !selectedGridId)
                }
                className="w-full py-3.5 sm:py-3 rounded-lg font-mono text-sm bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/20 active:bg-[#00ff00]/30 transition-all disabled:opacity-50 disabled:cursor-not-allowed min-h-[48px] sm:min-h-0"
              >
                {step === "new-grid" ? `Create & Import` : `Import`}
              </button>
            )}

            {(step === "upload" || step === "destination") && (
              <button
                onClick={handleClose}
                className="w-full py-3.5 sm:py-3 rounded-lg font-mono text-sm bg-[#1a1a1a] text-gray-400 hover:text-white active:bg-[#2a2a2a] transition-colors min-h-[48px] sm:min-h-0"
              >
                Cancel
              </button>
            )}
          </div>
        )}
      </div>
    </div>
  );

  return createPortal(modalContent, document.body);
}

// Parse import file (TXT, CSV, JSON)
function parseImportFile(content: string, filename: string): ParseResult {
  const ext = filename.toLowerCase().split(".").pop();
  let rawLinks: Array<{ url: string; title?: string }> = [];

  if (ext === "json") {
    try {
      const data = JSON.parse(content);
      if (Array.isArray(data)) {
        rawLinks = data.map((item) => {
          if (typeof item === "string") return { url: item };
          if (typeof item === "object" && item.url) return { url: item.url, title: item.title };
          return { url: "" };
        });
      }
    } catch {
      throw new Error("Invalid JSON format");
    }
  } else if (ext === "csv") {
    const lines = content.split("\n").filter((l) => l.trim());
    const hasHeader = lines[0]?.toLowerCase().includes("url");
    const dataLines = hasHeader ? lines.slice(1) : lines;

    rawLinks = dataLines.map((line) => {
      const parts = line.split(",").map((p) => p.trim().replace(/^["']|["']$/g, ""));
      return { url: parts[0] || "", title: parts[1] };
    });
  } else {
    // TXT: one URL per line
    rawLinks = content
      .split("\n")
      .filter((l) => l.trim())
      .map((url) => ({ url: url.trim() }));
  }

  // Validate and check duplicates
  const seenUrls = new Set<string>();
  let duplicateCount = 0;
  const links: ParsedLink[] = [];

  for (const item of rawLinks) {
    if (!item.url) continue;

    const isValid = isValidUrl(item.url);
    const isDuplicate = seenUrls.has(item.url);

    if (isDuplicate) {
      duplicateCount++;
    }

    seenUrls.add(item.url);

    links.push({
      url: item.url,
      title: item.title,
      isValid,
      error: !isValid ? "Invalid URL format" : undefined,
    });
  }

  return {
    links,
    validCount: links.filter((l) => l.isValid).length,
    invalidCount: links.filter((l) => !l.isValid).length,
    duplicateCount,
  };
}

function isValidUrl(url: string): boolean {
  if (url.startsWith("ipfs://") || url.startsWith("ar://")) return true;

  try {
    const parsed = new URL(url);
    return ["http:", "https:"].includes(parsed.protocol);
  } catch {
    return false;
  }
}

// Step Components
function UploadStep({
  onFileSelect,
  onDrop,
  fileInputRef,
  error,
}: {
  onFileSelect: (file: File) => void;
  onDrop: (e: React.DragEvent) => void;
  fileInputRef: React.RefObject<HTMLInputElement | null>;
  error: string | null;
}) {
  return (
    <div className="space-y-4">
      <div
        onDrop={onDrop}
        onDragOver={(e) => e.preventDefault()}
        onClick={() => fileInputRef.current?.click()}
        className="border-2 border-dashed border-[#1a1a1a] rounded-xl p-8 text-center cursor-pointer hover:border-[#00ff00]/30 transition-colors"
      >
        <div className="w-12 h-12 mx-auto mb-4 rounded-xl bg-[#00ff00]/10 border border-[#00ff00]/20 flex items-center justify-center">
          <span className="text-2xl">📁</span>
        </div>
        <p className="text-gray-400 font-mono text-sm mb-2">
          Drop file here or tap to browse
        </p>
        <p className="text-gray-600 font-mono text-xs">
          Supported: .txt, .csv, .json
        </p>
      </div>

      <input
        ref={fileInputRef}
        type="file"
        accept=".txt,.csv,.json"
        onChange={(e) => e.target.files?.[0] && onFileSelect(e.target.files[0])}
        className="hidden"
      />

      {error && (
        <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30">
          <p className="text-red-400 font-mono text-sm">{error}</p>
        </div>
      )}

      <div className="text-gray-600 font-mono text-xs space-y-1">
        <p><strong>TXT:</strong> One URL per line</p>
        <p><strong>CSV:</strong> url,title columns</p>
        <p><strong>JSON:</strong> Array of URLs or objects</p>
      </div>
    </div>
  );
}

function DestinationStep({
  parseResult,
  calculatedSize,
  needsUnlock,
  onSelect,
  error,
}: {
  parseResult: ParseResult;
  calculatedSize: number;
  needsUnlock: boolean;
  onSelect: (dest: ImportDestination) => void;
  error: string | null;
}) {
  // Calculate preview grid cell size
  const maxPreviewSize = 200;
  const previewCellSize = Math.max(4, Math.floor(maxPreviewSize / calculatedSize));
  const previewSize = previewCellSize * calculatedSize;

  return (
    <div className="space-y-4">
      {/* Visual Preview Grid */}
      <div className="flex flex-col items-center">
        <p className="text-gray-400 font-mono text-xs mb-2">Preview Layout</p>
        <div
          className="rounded-lg overflow-hidden border border-[#1a1a1a]"
          style={{
            width: previewSize,
            height: previewSize,
            background: "#0a0a0a",
          }}
        >
          <div
            className="grid"
            style={{
              gridTemplateColumns: `repeat(${calculatedSize}, ${previewCellSize}px)`,
              gridTemplateRows: `repeat(${calculatedSize}, ${previewCellSize}px)`,
            }}
          >
            {Array.from({ length: calculatedSize * calculatedSize }).map((_, index) => {
              const isFilled = index < parseResult.validCount;
              return (
                <div
                  key={index}
                  className={`border border-[#1a1a1a]/50 ${
                    isFilled ? "bg-[#00ff00]/40" : "bg-[#111]"
                  }`}
                  style={{
                    width: previewCellSize,
                    height: previewCellSize,
                  }}
                />
              );
            })}
          </div>
        </div>
        <p className="text-gray-500 font-mono text-xs mt-2">
          {parseResult.validCount} items → {calculatedSize}×{calculatedSize} grid
        </p>
      </div>

      {/* Stats */}
      <div className="p-3 rounded-lg bg-black border border-[#1a1a1a]">
        <div className="flex justify-between text-sm font-mono">
          <span className="text-gray-400">Valid links</span>
          <span className="text-[#00ff00]">{parseResult.validCount}</span>
        </div>
        {parseResult.invalidCount > 0 && (
          <div className="flex justify-between text-sm font-mono mt-1">
            <span className="text-gray-400">Invalid (skipped)</span>
            <span className="text-red-400">{parseResult.invalidCount}</span>
          </div>
        )}
        {parseResult.duplicateCount > 0 && (
          <div className="flex justify-between text-sm font-mono mt-1">
            <span className="text-gray-400">Duplicates found</span>
            <span className="text-yellow-400">{parseResult.duplicateCount}</span>
          </div>
        )}
        <div className="flex justify-between text-sm font-mono mt-2 pt-2 border-t border-[#1a1a1a]">
          <span className="text-gray-400">Grid size needed</span>
          <span className="text-[#00ff00]">
            {calculatedSize}×{calculatedSize}
            {needsUnlock && <span className="text-yellow-400 ml-1">(${GRID_UNLOCK_PRICE_USD})</span>}
          </span>
        </div>
      </div>

      {/* Destination selection */}
      <div className="space-y-2">
        <p className="text-gray-400 font-mono text-sm">Import to:</p>

        <button
          onClick={() => onSelect("new")}
          className="w-full p-4 rounded-xl bg-black border border-[#1a1a1a] hover:border-[#00ff00]/30 transition-colors text-left"
        >
          <div className="text-[#00ff00] font-mono text-sm mb-1">Create new grid</div>
          <p className="text-gray-500 font-mono text-xs">
            {calculatedSize}×{calculatedSize} grid ({calculatedSize * calculatedSize} cells)
          </p>
        </button>

        <button
          onClick={() => onSelect("existing")}
          className="w-full p-4 rounded-xl bg-black border border-[#1a1a1a] hover:border-[#00ff00]/30 transition-colors text-left"
        >
          <div className="text-[#00ff00] font-mono text-sm mb-1">Add to existing grid</div>
          <p className="text-gray-500 font-mono text-xs">
            Fill empty cells or expand an existing grid
          </p>
        </button>
      </div>

      {error && (
        <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30">
          <p className="text-red-400 font-mono text-sm">{error}</p>
        </div>
      )}
    </div>
  );
}

function NewGridStep({
  name,
  onNameChange,
  visibility,
  onVisibilityChange,
  calculatedSize,
  needsUnlock,
}: {
  name: string;
  onNameChange: (name: string) => void;
  visibility: GridVisibility;
  onVisibilityChange: (visibility: GridVisibility) => void;
  calculatedSize: number;
  needsUnlock: boolean;
}) {
  return (
    <div className="space-y-4">
      {/* Size info */}
      <div className="p-3 rounded-lg bg-black border border-[#1a1a1a]">
        <div className="flex items-center justify-between">
          <span className="text-gray-400 font-mono text-sm">Grid Size</span>
          <span className="text-[#00ff00] font-mono">
            {calculatedSize}×{calculatedSize}
          </span>
        </div>
        {needsUnlock && (
          <p className="text-yellow-400 font-mono text-xs mt-2">
            This size requires a ${GRID_UNLOCK_PRICE_USD} unlock
          </p>
        )}
      </div>

      {/* Name input */}
      <div>
        <label className="block text-gray-400 font-mono text-sm mb-2">
          Grid Name
        </label>
        <input
          type="text"
          value={name}
          onChange={(e) => onNameChange(e.target.value)}
          placeholder="My Collection"
          maxLength={50}
          className="w-full px-4 py-3 rounded-lg bg-black border border-[#1a1a1a] text-white font-mono text-base placeholder:text-gray-600 focus:border-[#00ff00]/30 focus:outline-none transition-colors"
        />
      </div>

      {/* Visibility */}
      <div>
        <label className="block text-gray-400 font-mono text-sm mb-2">
          Visibility
        </label>
        <div className="flex gap-2">
          <button
            onClick={() => onVisibilityChange("public")}
            className={`flex-1 py-2 px-3 rounded-lg font-mono text-sm border transition-all ${
              visibility === "public"
                ? "bg-[#00ff00]/10 border-[#00ff00]/30 text-[#00ff00]"
                : "bg-black border-[#1a1a1a] text-gray-400"
            }`}
          >
            Public
          </button>
          <button
            onClick={() => onVisibilityChange("hidden")}
            className={`flex-1 py-2 px-3 rounded-lg font-mono text-sm border transition-all ${
              visibility === "hidden"
                ? "bg-[#00ff00]/10 border-[#00ff00]/30 text-[#00ff00]"
                : "bg-black border-[#1a1a1a] text-gray-400"
            }`}
          >
            Hidden
          </button>
        </div>
      </div>
    </div>
  );
}

function SelectGridStep({
  grids,
  selectedId,
  onSelect,
  itemCount,
}: {
  grids: GridWithStats[];
  selectedId: string | null;
  onSelect: (id: string) => void;
  itemCount: number;
}) {
  if (grids.length === 0) {
    return (
      <div className="text-center py-8">
        <p className="text-gray-500 font-mono text-sm">
          No existing grids found. Create a new one instead.
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-2">
      <p className="text-gray-400 font-mono text-sm mb-3">
        Select a grid to import {itemCount} items:
      </p>

      {grids.map((grid) => {
        const emptySlots = grid.totalCells - grid.cellCount;
        const needsResize = emptySlots < itemCount;
        const newSize = needsResize ? calculateGridSize(grid.cellCount + itemCount) : grid.size;

        return (
          <button
            key={grid.id}
            onClick={() => onSelect(grid.id)}
            className={`w-full p-3 rounded-xl border transition-all text-left ${
              selectedId === grid.id
                ? "bg-[#00ff00]/10 border-[#00ff00]/30"
                : "bg-black border-[#1a1a1a] hover:border-[#00ff00]/20"
            }`}
          >
            <div className="flex items-center justify-between mb-1">
              <span className="text-[#00ff00] font-mono text-sm truncate">
                {grid.name}
              </span>
              {!needsResize && (
                <span className="text-green-400 font-mono text-xs">✓ Fits</span>
              )}
            </div>
            <p className="text-gray-500 font-mono text-xs">
              {grid.size}×{grid.size} • {emptySlots} empty cells
            </p>
            {needsResize && (
              <p className="text-yellow-400 font-mono text-xs mt-1">
                Will resize to {newSize}×{newSize}
              </p>
            )}
          </button>
        );
      })}
    </div>
  );
}

function ImportingStep({
  progress,
  error,
  totalItems = 0,
}: {
  progress: number;
  error: string | null;
  totalItems?: number;
}) {
  const processedItems = Math.round((progress / 100) * totalItems);

  return (
    <div className="py-8">
      {error ? (
        <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30">
          <p className="text-red-400 font-mono text-sm">{error}</p>
        </div>
      ) : (
        <div className="space-y-4">
          {/* Progress bar */}
          <div className="relative">
            <div className="h-3 rounded-full bg-[#1a1a1a] overflow-hidden">
              <div
                className="h-full bg-[#00ff00] transition-all duration-300 ease-out"
                style={{ width: `${progress}%` }}
              />
            </div>
            {/* Percentage label */}
            <div className="absolute inset-0 flex items-center justify-center">
              <span className="text-xs font-mono text-white drop-shadow-lg">
                {progress}%
              </span>
            </div>
          </div>

          {/* Status text */}
          <div className="text-center">
            <p className="text-[#00ff00] font-mono text-lg mb-1">
              {progress < 100 ? "Importing..." : "Complete!"}
            </p>
            {totalItems > 0 && (
              <p className="text-gray-500 font-mono text-sm">
                {processedItems} / {totalItems} items
              </p>
            )}
          </div>

          {/* Large import warning */}
          {totalItems >= 1000 && progress < 100 && (
            <div className="p-3 rounded-lg bg-yellow-500/10 border border-yellow-500/30">
              <p className="text-yellow-400 font-mono text-xs text-center">
                Large import in progress. This may take a few minutes.
              </p>
            </div>
          )}

          {/* Animated spinner for visual feedback */}
          {progress < 100 && (
            <div className="flex justify-center">
              <div className="w-8 h-8 rounded-full border-2 border-[#1a1a1a] border-t-[#00ff00] animate-spin" />
            </div>
          )}
        </div>
      )}
    </div>
  );
}
src/features/app/components/grid-unlock-modal.tsx
"use client";

import { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { useAccount, useBalance } from "wagmi";
import { P, Small } from "@neynar/ui";
import { useSponsoredTransaction } from "@/hooks/use-sponsored-transaction";
import { formatUnits, type Address } from "viem";
import { base } from "viem/chains";
import { GRID_UNLOCK_PRICE_USD } from "@/lib/net-protocol";
import { useStoragePassModal } from "./unlimited-storage-pass-modal";

// USDC Contract on Base
const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" as Address;
const USDC_ABI = [
  {
    name: "transfer",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "to", type: "address" },
      { name: "value", type: "uint256" },
    ],
    outputs: [{ type: "bool" }],
  },
] as const;

// Treasury address for payments
const TREASURY_ADDRESS = "0xAcAD71e697Ef3bb148093b2DD2fCf0845e957627" as const;

interface GridUnlockModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
  gridSize: number;
}

export function GridUnlockModal({
  isOpen,
  onClose,
  onSuccess,
  gridSize,
}: GridUnlockModalProps) {
  const { address } = useAccount();
  const { openStoragePassModal } = useStoragePassModal();
  const [mounted, setMounted] = useState(false);
  const [paymentState, setPaymentState] = useState<
    "idle" | "paying" | "confirming" | "processing" | "complete" | "error"
  >("idle");
  const [error, setError] = useState<string | null>(null);

  // Track client-side mount for portal
  useEffect(() => {
    setMounted(true);
  }, []);

  // Reset state when modal opens/closes
  useEffect(() => {
    if (!isOpen) {
      setPaymentState("idle");
      setError(null);
    }
  }, [isOpen]);

  // Check USDC balance
  const { data: usdcBalance } = useBalance({
    address: address as Address | undefined,
    token: USDC_ADDRESS,
    chainId: base.id,
  });

  const cost = GRID_UNLOCK_PRICE_USD;
  const usdcBalanceFormatted = usdcBalance
    ? parseFloat(formatUnits(usdcBalance.value, 6))
    : 0;
  const hasEnoughUsdc = usdcBalanceFormatted >= cost;

  // Sponsored transaction hook
  const {
    sendSponsoredTransaction,
    txHash,
    isPending,
    isConfirming,
    isConfirmed,
    error: writeError,
    reset,
    isSponsored,
  } = useSponsoredTransaction();

  // Handle write errors
  useEffect(() => {
    if (writeError && paymentState === "paying") {
      const errMsg = writeError.message?.toLowerCase() || "";
      if (
        errMsg.includes("user rejected") ||
        errMsg.includes("denied") ||
        errMsg.includes("cancelled")
      ) {
        reset();
        setPaymentState("idle");
        return;
      }
      setError(writeError.message?.slice(0, 60) || "Payment failed");
      setPaymentState("error");
    }
  }, [writeError, paymentState, reset]);

  // Handle transaction confirming
  useEffect(() => {
    if (txHash && isConfirming && paymentState === "paying") {
      setPaymentState("confirming");
    }
  }, [txHash, isConfirming, paymentState]);

  // Handle transaction confirmed
  useEffect(() => {
    if (
      isConfirmed &&
      txHash &&
      (paymentState === "paying" || paymentState === "confirming")
    ) {
      handlePaymentComplete(txHash);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isConfirmed, txHash]);

  const handlePaymentComplete = async (hash: string) => {
    setPaymentState("processing");

    try {
      // Record the payment for this specific grid unlock
      const response = await fetch("/api/membership/grid-unlock", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          address,
          txHash: hash,
          gridSize,
        }),
      });

      const data = await response.json();
      if (!response.ok) {
        throw new Error(data.error || "Failed to record unlock");
      }

      setPaymentState("complete");
      reset();
      onSuccess?.();

      // Auto-close after success
      setTimeout(() => {
        onClose();
      }, 2000);
    } catch (err) {
      console.error("Payment processing error:", err);
      setError(
        err instanceof Error ? err.message : "Failed to process payment"
      );
      setPaymentState("error");
    }
  };

  const handlePayment = async () => {
    if (!address) return;

    setError(null);
    setPaymentState("paying");

    try {
      await sendSponsoredTransaction({
        address: USDC_ADDRESS,
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        abi: USDC_ABI as any,
        functionName: "transfer",
        args: [TREASURY_ADDRESS, BigInt(cost * 1_000_000)], // USDC has 6 decimals
      });
    } catch (err) {
      console.error("Transaction failed:", err);
    }
  };

  if (!isOpen || !mounted) return null;

  const modalContent = (
    <div className="fixed inset-0 z-[9999] flex items-start justify-center pt-20 pb-24 px-4 overflow-y-auto">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/80 backdrop-blur-sm"
        onClick={paymentState === "idle" ? onClose : undefined}
      />

      {/* Modal */}
      <div className="relative w-full max-w-sm bg-[#0a0a0a] border border-[#1a1a1a] rounded-2xl overflow-hidden shadow-2xl max-h-[75vh] flex flex-col">
        {/* Header */}
        <div className="flex items-center p-4 border-b border-[#1a1a1a] shrink-0">
          <div className="flex items-center gap-2">
            <span className="text-xl">🔲</span>
            <h2 className="text-[#00ff00] font-mono text-lg">Custom Grid</h2>
          </div>
        </div>

        {/* Content - scrollable */}
        <div className="p-4 space-y-4 overflow-y-auto flex-1">
          {paymentState === "idle" && (
            <>
              <div className="p-4 rounded-xl bg-yellow-500/5 border border-yellow-500/20">
                <P className="text-yellow-400 font-mono text-center">
                  Create {gridSize}×{gridSize} Grid
                </P>
                <Small className="text-gray-400 font-mono text-center block mt-2">
                  Custom grids larger than 5×5 cost ${cost} each
                </Small>
              </div>

              <div className="space-y-2">
                <div className="flex items-center justify-between p-3 rounded-lg bg-black border border-[#1a1a1a]">
                  <span className="text-gray-400 font-mono text-sm">
                    Grid cost
                  </span>
                  <span className="text-yellow-400 font-mono font-bold">
                    ${cost} USDC
                  </span>
                </div>

                <div className="flex items-center justify-between p-3 rounded-lg bg-black border border-[#1a1a1a]">
                  <span className="text-gray-400 font-mono text-sm">
                    Your balance
                  </span>
                  <span
                    className={`font-mono font-bold ${
                      hasEnoughUsdc ? "text-[#00ff00]" : "text-red-400"
                    }`}
                  >
                    ${usdcBalanceFormatted.toFixed(2)} USDC
                  </span>
                </div>
              </div>

              {/* Unlimited Pass upsell */}
              <div className="p-3 rounded-lg bg-[#00ff00]/5 border border-[#00ff00]/20">
                <p className="text-[#00ff00] font-mono text-xs font-semibold">
                  💡 Planning to create more unlocked grids?
                </p>
                <p className="text-gray-500 font-mono text-xs mt-1">
                  <button
                    onClick={openStoragePassModal}
                    className="text-[#00ff00] underline hover:text-[#00ff00]/80 transition-colors"
                  >
                    Get the Unlimited Pass
                  </button>
                  {" "}for unlimited unlocked grids + unlimited items in stacks.
                </p>
              </div>

              {isSponsored && (
                <p className="text-gray-600 font-mono text-xs text-center">
                  Gas fees covered by Net Library
                </p>
              )}

              {!hasEnoughUsdc && (
                <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30">
                  <Small className="text-red-400 font-mono text-center block">
                    Insufficient USDC balance. Need ${cost} USDC on Base.
                  </Small>
                </div>
              )}
            </>
          )}

          {paymentState === "paying" && (
            <div className="py-8 flex flex-col items-center gap-4">
              <div className="w-12 h-12 border-2 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
              <P className="text-[#00ff00] font-mono text-center">
                {isPending ? "Confirm in wallet..." : "Processing payment..."}
              </P>
            </div>
          )}

          {paymentState === "confirming" && (
            <div className="py-8 flex flex-col items-center gap-4">
              <div className="w-12 h-12 border-2 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
              <P className="text-[#00ff00] font-mono text-center">
                Confirming on Base...
              </P>
              {txHash && (
                <Small className="text-gray-500 font-mono text-xs">
                  {txHash.slice(0, 10)}...{txHash.slice(-8)}
                </Small>
              )}
            </div>
          )}

          {paymentState === "processing" && (
            <div className="py-8 flex flex-col items-center gap-4">
              <div className="w-12 h-12 border-2 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
              <P className="text-[#00ff00] font-mono text-center">
                Setting up your grid...
              </P>
            </div>
          )}

          {paymentState === "complete" && (
            <div className="py-8 flex flex-col items-center gap-4">
              <div className="w-16 h-16 rounded-full bg-[#00ff00]/20 flex items-center justify-center">
                <span className="text-3xl">✓</span>
              </div>
              <P className="text-[#00ff00] font-mono text-center">
                Grid Unlocked!
              </P>
              <Small className="text-gray-400 font-mono text-center">
                Your {gridSize}×{gridSize} grid is ready.
              </Small>
            </div>
          )}

          {paymentState === "error" && (
            <div className="py-8 flex flex-col items-center gap-4">
              <div className="w-16 h-16 rounded-full bg-red-500/20 flex items-center justify-center">
                <span className="text-3xl">✕</span>
              </div>
              <P className="text-red-400 font-mono text-center">
                Payment Failed
              </P>
              <Small className="text-gray-400 font-mono text-center">
                {error || "Something went wrong. Please try again."}
              </Small>
              <button
                onClick={() => {
                  reset();
                  setPaymentState("idle");
                  setError(null);
                }}
                className="px-6 py-2 rounded-lg bg-[#1a1a1a] text-white font-mono text-sm hover:bg-[#2a2a2a] transition-colors"
              >
                Try Again
              </button>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-4 border-t border-[#1a1a1a] shrink-0">
          {paymentState === "idle" && (
            <div className="flex gap-2">
              <button
                onClick={onClose}
                className="flex-1 py-3 rounded-lg font-mono text-sm bg-[#1a1a1a] text-gray-400 hover:text-white transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handlePayment}
                disabled={!hasEnoughUsdc || !address}
                className="flex-1 py-3 rounded-lg font-mono text-sm bg-yellow-500/10 border border-yellow-500/30 text-yellow-400 hover:bg-yellow-500/20 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Pay ${cost} USDC
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );

  return createPortal(modalContent, document.body);
}
src/features/app/components/grids-tab.tsx
"use client";

import { useState, useMemo, useEffect } from "react";
import { createPortal } from "react-dom";
import { useAccount } from "wagmi";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { useGrids, useGridFeed } from "@/hooks/use-grids";
import { useGridArchive } from "@/hooks/use-grid-archive";
import { CreateGridModal } from "./create-grid-modal";
import { GridImportModal } from "./grid-import-modal";
import { GridDetail } from "./grid-detail";
import { UserContentPopover } from "./user-content-popover";
import { safeComposeCast, safeOpenUrl, useAppMode } from "@/lib/app-mode";
import type { GridWithStats, ArchivedGrid, GridCell } from "@/lib/net-protocol";
import { LinkIcon, ArchiveIcon, ShareIcon } from "@/components/icons/net-library-icons";

// Convert IPFS/Arweave URLs to gateway URLs for display
function toGatewayUrl(url: string): string {
  if (!url) return url;

  // IPFS URLs
  if (url.startsWith("ipfs://")) {
    const cid = url.slice(7);
    return `https://ipfs.io/ipfs/${cid}`;
  }

  // IPFS gateway URLs that need normalization
  if (url.includes("/ipfs/") && !url.startsWith("https://ipfs.io")) {
    const match = url.match(/\/ipfs\/(.+)/);
    if (match) {
      return `https://ipfs.io/ipfs/${match[1]}`;
    }
  }

  // Arweave URLs
  if (url.startsWith("ar://")) {
    const txId = url.slice(5);
    return `https://arweave.net/${txId}`;
  }

  return url;
}

// Sub-navigation types
type GridsSubNav = "all-grids" | "my-grids";
type MyGridsSection = "public" | "hidden" | "archived";

// Grid Share Modal - for sharing grids via Farcaster/X
function GridShareModal({
  isOpen,
  onClose,
  grid,
}: {
  isOpen: boolean;
  onClose: () => void;
  grid: GridWithStats | null;
}) {
  const [isSharing, setIsSharing] = useState<"farcaster" | "x" | null>(null);
  const [copied, setCopied] = useState(false);
  const appMode = useAppMode();
  const isBaseApp = appMode === "base-app";

  if (!isOpen || !grid) return null;

  // Use current origin for sharing - this works in both dev and production
  const baseUrl = typeof window !== "undefined" ? window.location.origin : "";
  const source = isBaseApp ? "base" : "farcaster";
  const shareUrl = `${baseUrl}/share/grid/${encodeURIComponent(grid.id)}?source=${source}`;
  const shareUrlForX = `${baseUrl}/share/grid/${encodeURIComponent(grid.id)}?source=web`;
  const creatorName = grid.creatorUsername || "a Net Library member";
  const shareText = `Check out "${grid.name}" by ${creatorName} on Net Library!\n\n${grid.size}×${grid.size} grid with ${grid.cellCount || 0} items\n\nExperience the decentralized onchain media library powered by @netprotocol`;
  const shareTextForX = `Check out "${grid.name}" by ${creatorName} on Net Library!\n\n${grid.size}×${grid.size} grid with ${grid.cellCount || 0} items\n\nExperience the decentralized onchain media library powered by @netprotocolapp`;

  const handleShareToFarcaster = async () => {
    setIsSharing("farcaster");
    try {
      const success = await safeComposeCast({
        text: shareText,
        embeds: [shareUrl],
      });

      if (success) {
        onClose();
      } else {
        alert("Failed to create cast. Please try again.");
      }
    } catch (err) {
      console.error("Failed to share to Farcaster:", err);
      alert("Failed to share. Please try again.");
    } finally {
      setIsSharing(null);
    }
  };

  const handleShareToX = async () => {
    setIsSharing("x");
    try {
      // Use twitter.com for better compatibility, and use the web source URL
      const xIntentParams = new URLSearchParams({
        text: shareTextForX,
        url: shareUrlForX,
      });
      const xUrl = `https://twitter.com/intent/tweet?${xIntentParams.toString()}`;
      if (isBaseApp) {
        window.open(xUrl, "_blank", "noopener,noreferrer");
      } else {
        await safeOpenUrl(xUrl);
      }
      setTimeout(onClose, 500);
    } catch (err) {
      console.error("Failed to share to X:", err);
    } finally {
      setIsSharing(null);
    }
  };

  const handleCopyLink = async () => {
    try {
      await navigator.clipboard.writeText(shareUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error("Failed to copy link:", err);
    }
  };

  return createPortal(
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/90"
      onClick={onClose}
    >
      <div
        className="w-full max-w-sm mx-4 bg-[#0a0a0a] border border-[#00ff00]/20 rounded-2xl overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-[#1a1a1a]">
          <h2 className="text-[#00ff00] font-mono text-lg font-medium">Share Grid</h2>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white transition-colors"
          >
            ✕
          </button>
        </div>

        {/* Grid Preview */}
        <div className="p-4 border-b border-[#1a1a1a]">
          <div className="flex items-center gap-3">
            <GridPreview grid={grid} />
            <div className="flex-1 min-w-0">
              <p className="text-white font-mono text-sm truncate">{grid.name}</p>
              <p className="text-gray-500 font-mono text-xs">
                {grid.size}×{grid.size} • {grid.cellCount || 0} items
              </p>
            </div>
          </div>
        </div>

        {/* Share Options */}
        <div className="p-4 space-y-3">
          {/* Farcaster - only in mini app mode */}
          {!isBaseApp && (
            <button
              onClick={handleShareToFarcaster}
              disabled={isSharing !== null}
              className="w-full py-3 px-4 rounded-xl bg-[#8A63D2]/10 border border-[#8A63D2]/30 text-[#8A63D2] font-mono text-sm hover:bg-[#8A63D2]/20 transition-all disabled:opacity-50 flex items-center justify-center gap-2"
            >
              {isSharing === "farcaster" ? (
                <div className="w-4 h-4 border-2 border-[#8A63D2]/30 border-t-[#8A63D2] rounded-full animate-spin" />
              ) : (
                <>
                  <svg width="16" height="16" viewBox="0 0 1000 1000" fill="#8A63D2">
                    <path d="M257.778 155.556H742.222V844.445H671.111V528.889H670.414C662.554 441.677 589.258 373.333 500 373.333C410.742 373.333 337.446 441.677 329.586 528.889H328.889V844.445H257.778V155.556Z"/>
                    <path d="M128.889 253.333L157.778 351.111H182.222V746.667C169.949 746.667 160 756.616 160 768.889V795.556H155.556C143.283 795.556 133.333 805.505 133.333 817.778V844.445H382.222V817.778C382.222 805.505 372.273 795.556 360 795.556H355.556V768.889C355.556 756.616 345.606 746.667 333.333 746.667H306.667V253.333H128.889Z"/>
                    <path d="M675.556 746.667C663.283 746.667 653.333 756.616 653.333 768.889V795.556H648.889C636.616 795.556 626.667 805.505 626.667 817.778V844.445H875.556V817.778C875.556 805.505 865.606 795.556 853.333 795.556H848.889V768.889C848.889 756.616 838.94 746.667 826.667 746.667V351.111H851.111L880 253.333H702.222V746.667H675.556Z"/>
                  </svg>
                  <span>Share to Farcaster</span>
                </>
              )}
            </button>
          )}

          {/* X/Twitter */}
          <button
            onClick={handleShareToX}
            disabled={isSharing !== null}
            className="w-full py-3 px-4 rounded-xl bg-white/5 border border-white/20 text-white font-mono text-sm hover:bg-white/10 transition-all disabled:opacity-50 flex items-center justify-center gap-2"
          >
            {isSharing === "x" ? (
              <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
            ) : (
              <>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="white">
                  <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                </svg>
                <span>Share to X</span>
              </>
            )}
          </button>

          {/* Copy Link */}
          <button
            onClick={handleCopyLink}
            className="w-full py-3 px-4 rounded-xl bg-[#1a1a1a] border border-[#2a2a2a] text-gray-400 font-mono text-sm hover:border-[#00ff00]/30 hover:text-white transition-all flex items-center justify-center gap-2"
          >
            {copied ? (
              <>
                <span>✓</span>
                <span>Copied!</span>
              </>
            ) : (
              <>
                <LinkIcon className="w-4 h-4" />
                <span>Copy Link</span>
              </>
            )}
          </button>
        </div>
      </div>
    </div>,
    document.body
  );
}

export function GridsTab() {
  const { address } = useAccount();
  const { isMember } = useMembershipStatus();

  // Sub-navigation state
  const [subNav, setSubNav] = useState<GridsSubNav>("all-grids");
  const [myGridsSection, setMyGridsSection] = useState<MyGridsSection>("public");

  // Detail view state
  const [selectedGridId, setSelectedGridId] = useState<string | null>(null);

  // Modal states
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showImportModal, setShowImportModal] = useState(false);
  const [shareGrid, setShareGrid] = useState<GridWithStats | null>(null);

  // Handle share grid callback
  const handleShareGrid = (grid: GridWithStats) => {
    setShareGrid(grid);
  };

  // Listen for show-grid-detail event (from profile tab navigation)
  useEffect(() => {
    const handleShowGridDetail = (event: Event) => {
      const customEvent = event as CustomEvent<string>;
      if (customEvent.detail) {
        setSelectedGridId(customEvent.detail);
      }
    };
    window.addEventListener("show-grid-detail", handleShowGridDetail);
    return () => window.removeEventListener("show-grid-detail", handleShowGridDetail);
  }, []);

  // Handle navigating to a book/item detail page from the grid viewer
  const handleViewItemDetail = (contentKey: string) => {
    // Store current grid ID for back navigation before closing
    const fromGridId = selectedGridId;
    // Close the grid detail view first
    setSelectedGridId(null);
    // Dispatch event to navigate to the book detail page
    // Include gridId so back button can return to the grid
    window.dispatchEvent(new CustomEvent("navigate-to-book", {
      detail: { contentKey, fromGridId }
    }));
  };

  // If viewing a grid detail, show that
  if (selectedGridId) {
    return (
      <div className="h-full flex flex-col">
        <GridDetail
          gridId={selectedGridId}
          onBack={() => setSelectedGridId(null)}
          onViewItemDetail={handleViewItemDetail}
        />
      </div>
    );
  }

  return (
    <div className="flex flex-col h-full">
      {/* Sub-navigation: All Grids / My Grids */}
      <div className="flex gap-2 mb-4">
        <button
          onClick={() => setSubNav("all-grids")}
          className={`flex-1 py-2 px-3 rounded-lg font-mono text-sm border transition-all ${
            subNav === "all-grids"
              ? "bg-[#00ff00]/10 border-[#00ff00]/30 text-[#00ff00]"
              : "bg-[#0a0a0a] border-[#1a1a1a] text-gray-400 hover:border-[#00ff00]/20"
          }`}
        >
          All Grids
        </button>
        <button
          onClick={() => setSubNav("my-grids")}
          className={`flex-1 py-2 px-3 rounded-lg font-mono text-sm border transition-all ${
            subNav === "my-grids"
              ? "bg-[#00ff00]/10 border-[#00ff00]/30 text-[#00ff00]"
              : "bg-[#0a0a0a] border-[#1a1a1a] text-gray-400 hover:border-[#00ff00]/20"
          }`}
        >
          My Grids
        </button>
      </div>

      {/* Content based on sub-nav */}
      {subNav === "all-grids" ? (
        <AllGridsFeed onSelectGrid={setSelectedGridId} onShareGrid={handleShareGrid} />
      ) : (
        <MyGridsView
          section={myGridsSection}
          onSectionChange={setMyGridsSection}
          address={address}
          isMember={isMember}
          onSelectGrid={setSelectedGridId}
          onShareGrid={handleShareGrid}
          onCreateGrid={() => setShowCreateModal(true)}
          onImportGrid={() => setShowImportModal(true)}
        />
      )}

      {/* Modals */}
      <CreateGridModal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        onCreated={(gridId) => setSelectedGridId(gridId)}
      />

      <GridImportModal
        isOpen={showImportModal}
        onClose={() => setShowImportModal(false)}
        onImported={(gridId) => setSelectedGridId(gridId)}
      />

      <GridShareModal
        isOpen={!!shareGrid}
        onClose={() => setShareGrid(null)}
        grid={shareGrid}
      />
    </div>
  );
}

// All Grids - Public feed sorted by upvotes
function AllGridsFeed({ onSelectGrid, onShareGrid }: { onSelectGrid: (id: string) => void; onShareGrid: (grid: GridWithStats) => void }) {
  const { grids, isLoading, error, hasMore, loadMore, refresh } = useGridFeed("upvotes");

  if (isLoading && grids.length === 0) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <div className="w-8 h-8 border-2 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex-1 flex flex-col items-center justify-center py-16 text-center">
        <p className="text-red-400 font-mono text-sm mb-4">{error}</p>
        <button
          onClick={refresh}
          className="px-4 py-2 rounded-lg font-mono text-sm bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00]"
        >
          Retry
        </button>
      </div>
    );
  }

  if (grids.length === 0) {
    return (
      <div className="flex-1 overflow-y-auto">
        <div className="flex flex-col items-center justify-center py-16 text-center">
          <div className="w-16 h-16 mb-4 rounded-xl bg-[#00ff00]/10 border border-[#00ff00]/20 flex items-center justify-center">
            <GridIcon className="w-8 h-8 text-[#00ff00]" />
          </div>
          <h3 className="text-[#00ff00] font-mono text-lg mb-2">
            No Grids Yet
          </h3>
          <p className="text-gray-500 font-mono text-sm max-w-[280px]">
            Be the first to create a visual curation board. Switch to &quot;My Grids&quot; to get started.
          </p>
        </div>
      </div>
    );
  }

  return (
    <div className="flex-1 overflow-y-auto space-y-3">
      {grids.map((grid) => (
        <GridCard key={grid.id} grid={grid} onClick={() => onSelectGrid(grid.id)} onShare={() => onShareGrid(grid)} />
      ))}

      {hasMore && (
        <button
          onClick={loadMore}
          disabled={isLoading}
          className="w-full py-3 font-mono text-sm text-[#00ff00]/60 hover:text-[#00ff00] transition-colors"
        >
          {isLoading ? "Loading..." : "Load more"}
        </button>
      )}
    </div>
  );
}

// My Grids - Personal grid management
function MyGridsView({
  section,
  onSectionChange,
  address,
  isMember,
  onSelectGrid,
  onShareGrid,
  onCreateGrid,
  onImportGrid,
}: {
  section: MyGridsSection;
  onSectionChange: (section: MyGridsSection) => void;
  address?: string;
  isMember: boolean;
  onSelectGrid: (id: string) => void;
  onShareGrid: (grid: GridWithStats) => void;
  onCreateGrid: () => void;
  onImportGrid: () => void;
}) {
  // Not connected state
  if (!address) {
    return (
      <div className="flex-1 flex flex-col items-center justify-center py-16 text-center">
        <div className="w-16 h-16 mb-4 rounded-xl bg-[#0a0a0a] border border-[#1a1a1a] flex items-center justify-center">
          <GridIcon className="w-8 h-8 text-gray-600" />
        </div>
        <h3 className="text-gray-400 font-mono text-lg mb-2">
          Connect Wallet
        </h3>
        <p className="text-gray-600 font-mono text-sm max-w-[280px]">
          Connect your wallet to create and manage grids.
        </p>
      </div>
    );
  }

  // Not a member state
  if (!isMember) {
    return (
      <div className="flex-1 flex flex-col items-center justify-center py-16 text-center">
        <div className="w-16 h-16 mb-4 rounded-xl bg-[#0a0a0a] border border-[#1a1a1a] flex items-center justify-center">
          <GridIcon className="w-8 h-8 text-gray-600" />
        </div>
        <h3 className="text-gray-400 font-mono text-lg mb-2">
          Members Only
        </h3>
        <p className="text-gray-600 font-mono text-sm max-w-[280px]">
          Grids are a member-exclusive feature. Join Net Library to start creating.
        </p>
      </div>
    );
  }

  return (
    <div className="flex-1 flex flex-col overflow-hidden">
      {/* Section tabs: Public / Hidden / Archived */}
      <div className="flex gap-1 mb-4">
        {(["public", "hidden", "archived"] as MyGridsSection[]).map((s) => (
          <button
            key={s}
            onClick={() => onSectionChange(s)}
            className={`flex-1 py-1.5 px-2 rounded font-mono text-xs border transition-all capitalize ${
              section === s
                ? "bg-[#00ff00]/10 border-[#00ff00]/30 text-[#00ff00]"
                : "bg-[#0a0a0a] border-[#1a1a1a] text-gray-500 hover:border-[#00ff00]/20"
            }`}
          >
            {s}
          </button>
        ))}
      </div>

      {/* Action buttons */}
      <div className="flex gap-2 mb-4">
        <button
          onClick={onCreateGrid}
          className="flex-1 py-2 px-3 rounded-lg font-mono text-sm bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/20 transition-all"
        >
          + New Grid
        </button>
        <button
          onClick={onImportGrid}
          className="flex-1 py-2 px-3 rounded-lg font-mono text-sm bg-[#0a0a0a] border border-[#1a1a1a] text-gray-400 hover:border-[#00ff00]/20 transition-all"
        >
          Import
        </button>
      </div>

      {/* Grid list content */}
      <div className="flex-1 overflow-y-auto">
        <MyGridsContent
          section={section}
          address={address}
          onSelectGrid={onSelectGrid}
          onShareGrid={onShareGrid}
        />
      </div>
    </div>
  );
}

// Content for each My Grids section
function MyGridsContent({
  section,
  address,
  onSelectGrid,
  onShareGrid,
}: {
  section: MyGridsSection;
  address: string;
  onSelectGrid: (id: string) => void;
  onShareGrid: (grid: GridWithStats) => void;
}) {
  // For archived section, use archive hook
  if (section === "archived") {
    return <ArchivedGridsContent address={address} onSelectGrid={onSelectGrid} onShareGrid={onShareGrid} />;
  }

  return <LiveGridsContent section={section} address={address} onSelectGrid={onSelectGrid} onShareGrid={onShareGrid} />;
}

// Live grids (public/hidden)
function LiveGridsContent({
  section,
  address,
  onSelectGrid,
  onShareGrid,
}: {
  section: "public" | "hidden";
  address: string;
  onSelectGrid: (id: string) => void;
  onShareGrid: (grid: GridWithStats) => void;
}) {
  const { grids, isLoading, error, refresh } = useGrids({
    creator: address,
    visibility: section,
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="w-6 h-6 border-2 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center py-12 text-center">
        <p className="text-red-400 font-mono text-sm mb-4">{error}</p>
        <button
          onClick={refresh}
          className="px-4 py-2 rounded-lg font-mono text-sm bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00]"
        >
          Retry
        </button>
      </div>
    );
  }

  const emptyMessages = {
    public: "Your public grids will appear here. Create one to get started!",
    hidden: "Hidden grids are only visible to you. Use this for work in progress.",
  };

  if (grids.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-12 text-center">
        <div className="w-12 h-12 mb-3 rounded-lg bg-[#0a0a0a] border border-[#1a1a1a] flex items-center justify-center">
          <GridIcon className="w-6 h-6 text-gray-600" />
        </div>
        <p className="text-gray-500 font-mono text-sm max-w-[260px]">
          {emptyMessages[section]}
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {grids.map((grid) => (
        <GridCard
          key={grid.id}
          grid={grid}
          onClick={() => onSelectGrid(grid.id)}
          onShare={() => onShareGrid(grid)}
          showVisibility
        />
      ))}
    </div>
  );
}

// Archived grids with search
function ArchivedGridsContent({
  address,
  onSelectGrid,
  onShareGrid: _onShareGrid,
}: {
  address: string;
  onSelectGrid: (id: string) => void;
  onShareGrid: (grid: GridWithStats) => void;
}) {
  const [searchQuery, setSearchQuery] = useState("");
  const { archives, isLoading, error, refresh } = useGridArchive({ creator: address });

  // Filter archives by search query
  const filteredArchives = useMemo(() => {
    if (!searchQuery.trim()) return archives;

    const query = searchQuery.toLowerCase();
    return archives.filter((archive) => {
      // Search by grid name
      if (archive.gridName?.toLowerCase().includes(query)) return true;
      // Search by date
      const date = new Date(archive.archivedAt).toLocaleDateString();
      if (date.toLowerCase().includes(query)) return true;
      // Search by grid ID
      if (archive.gridId?.toLowerCase().includes(query)) return true;
      // Search by cell content metadata (titles, filenames)
      if (archive.searchText?.includes(query)) return true;
      return false;
    });
  }, [archives, searchQuery]);

  if (isLoading) {
    return (
      <div className="flex items-center justify-center py-12">
        <div className="w-6 h-6 border-2 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
      </div>
    );
  }

  if (error) {
    return (
      <div className="flex flex-col items-center justify-center py-12 text-center">
        <p className="text-red-400 font-mono text-sm mb-4">{error}</p>
        <button
          onClick={refresh}
          className="px-4 py-2 rounded-lg font-mono text-sm bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00]"
        >
          Retry
        </button>
      </div>
    );
  }

  return (
    <div className="space-y-3">
      {/* Search bar */}
      {archives.length > 0 && (
        <div className="relative">
          <input
            type="text"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            placeholder="Search archives..."
            className="w-full px-3 py-2 pl-8 rounded-lg bg-black border border-[#1a1a1a] text-white font-mono text-sm placeholder:text-gray-600 focus:border-[#00ff00]/30 focus:outline-none transition-colors"
            style={{ fontSize: "16px" }}
          />
          <SearchIcon className="absolute left-2.5 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-600" />
          {searchQuery && (
            <button
              onClick={() => setSearchQuery("")}
              className="absolute right-2.5 top-1/2 -translate-y-1/2 text-gray-500 hover:text-white"
            >
              ×
            </button>
          )}
        </div>
      )}

      {/* Empty state */}
      {archives.length === 0 && (
        <div className="flex flex-col items-center justify-center py-12 text-center">
          <div className="w-12 h-12 mb-3 rounded-lg bg-[#0a0a0a] border border-[#1a1a1a] flex items-center justify-center">
            <ArchiveIcon size={24} className="text-gray-600" />
          </div>
          <p className="text-gray-500 font-mono text-sm max-w-[260px]">
            Archives are permanent onchain snapshots of your grids. Use the Archive button on any grid to create one.
          </p>
        </div>
      )}

      {/* No search results */}
      {archives.length > 0 && filteredArchives.length === 0 && (
        <div className="flex flex-col items-center justify-center py-8 text-center">
          <p className="text-gray-500 font-mono text-sm">
            No archives match &quot;{searchQuery}&quot;
          </p>
        </div>
      )}

      {/* Archive list */}
      {filteredArchives.map((archive) => (
        <ArchiveCard
          key={archive.id}
          archive={archive}
          onClick={() => onSelectGrid(archive.gridId)}
        />
      ))}
    </div>
  );
}

// Archive Card Component
function ArchiveCard({
  archive,
  onClick,
}: {
  archive: ArchivedGrid;
  onClick: () => void;
}) {
  const archiveDate = new Date(archive.archivedAt);
  const dateStr = archiveDate.toLocaleDateString("en-US", {
    month: "short",
    year: "numeric",
  });

  return (
    <button
      onClick={onClick}
      className="w-full p-3 rounded-xl bg-[#0a0a0a] border border-[#00ff00]/20 hover:border-[#00ff00]/50 transition-all text-left"
    >
      <div className="flex gap-3">
        {/* Archive icon */}
        <div className="shrink-0 w-14 h-14 rounded-lg bg-black border border-[#00ff00]/20 flex items-center justify-center">
          <ArchiveIcon size={24} className="text-[#00ff00]" />
        </div>

        {/* Archive info */}
        <div className="flex-1 min-w-0">
          <span className="text-sm font-mono text-[#00ff00] truncate block">
            {archive.gridName || `Grid ${(archive.gridId || '').slice(0, 8)}`}
          </span>
          <span className="text-gray-500 font-mono text-xs mt-1 block">
            {archive.gridSize}×{archive.gridSize} • {archive.cellCount} cells
          </span>
          <span className="text-gray-600 font-mono text-xs mt-1 block">
            Archived {dateStr}
          </span>
        </div>
      </div>
    </button>
  );
}

// Grid Card Component
function GridCard({
  grid,
  onClick,
  showVisibility,
  onShare,
}: {
  grid: GridWithStats;
  onClick: () => void;
  showVisibility?: boolean;
  onShare?: () => void;
}) {
  // Handle share button click
  const handleShare = (e: React.MouseEvent) => {
    e.stopPropagation(); // Prevent card click
    if (onShare) {
      onShare();
    } else {
      // Default: copy link to clipboard
      const shareUrl = `${window.location.origin}/share/grid/${grid.id}`;
      navigator.clipboard.writeText(shareUrl);
    }
  };

  return (
    <button
      onClick={onClick}
      className="w-full p-3 rounded-xl bg-[#0a0a0a] border border-[#00ff00]/20 hover:border-[#00ff00]/50 transition-all text-left"
    >
      <div className="flex items-start gap-3">
        {/* Mini grid preview - tiled thumbnail */}
        <div className="shrink-0">
          <GridPreview grid={grid} />
        </div>

        {/* Grid Info - Title, Subtitle, then User */}
        <div className="flex-1 min-w-0">
          {/* Title row with visibility badge and archive indicator */}
          <div className="flex items-start gap-2">
            <span className="text-sm font-mono text-white truncate flex-1">{grid.name}</span>
            {/* Archive indicator */}
            {grid.isArchived && (
              <span
                className="shrink-0 p-1 rounded bg-[#00ff00]/10 border border-[#00ff00]/30"
                title="Archived onchain"
              >
                <ArchiveIcon size={10} className="text-[#00ff00]" />
              </span>
            )}
            {showVisibility && grid.visibility === "hidden" && (
              <span className="shrink-0 px-1.5 py-0.5 rounded text-[10px] font-mono bg-gray-800 text-gray-400">
                Hidden
              </span>
            )}
          </div>

          {/* Subtitle (if exists) - under title */}
          {grid.subtitle && (
            <p className="text-gray-400 font-mono text-xs mt-0.5 line-clamp-2">
              {grid.subtitle}
            </p>
          )}

          {/* User/pfp + cell count - under subtitle */}
          <div className="flex items-center gap-2 mt-1.5">
            {grid.creator && (
              <ClickableCreatorAvatar
                fid={grid.creatorFid}
                address={grid.creator}
                username={grid.creatorUsername}
              />
            )}
            <span className="text-gray-600 font-mono text-[10px]">•</span>
            <span className="text-gray-500 font-mono text-[10px]">
              {grid.size || 3}×{grid.size || 3} • {grid.cellCount || 0} cell{(grid.cellCount || 0) !== 1 ? "s" : ""}
            </span>
          </div>
        </div>

        {/* Stats / Actions - Right side */}
        <div className="flex flex-col items-end gap-2 shrink-0">
          {/* Upvote count - always show for public grids */}
          {grid.visibility === "public" && (
            <span className="text-[#00ff00] font-mono text-sm">
              ▲ {grid.upvoteCount || 0}
            </span>
          )}

          {/* Share button */}
          <div
            onClick={handleShare}
            className="p-1.5 rounded-lg bg-[#1a1a1a] border border-[#2a2a2a] hover:border-[#00ff00]/30 hover:bg-[#00ff00]/10 transition-all cursor-pointer"
            title="Share grid"
          >
            <ShareIcon size={14} className="text-gray-400" />
          </div>
        </div>
      </div>
    </button>
  );
}

// Clickable Creator Avatar - fetches pfp from Neynar by FID and shows content popover
function ClickableCreatorAvatar({
  fid,
  address,
  username
}: {
  fid?: number;
  address: string;
  username?: string;
}) {
  const [pfpUrl, setPfpUrl] = useState<string | null>(null);
  const [resolvedUsername, setResolvedUsername] = useState<string | undefined>(username);
  const [showPopover, setShowPopover] = useState(false);

  useEffect(() => {
    if (!fid) return;

    // Fetch user info from Neynar via resolve-user endpoint
    fetch("/api/resolve-user", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ fids: [fid] }),
    })
      .then(res => res.json())
      .then(data => {
        if (data.users && data.users.length > 0) {
          setPfpUrl(data.users[0].pfp_url);
          if (!username && data.users[0].username) {
            setResolvedUsername(data.users[0].username);
          }
        }
      })
      .catch(() => {
        // Ignore errors, just won't show avatar
      });
  }, [fid, username]);

  return (
    <>
      <button
        onClick={(e) => {
          e.stopPropagation();
          setShowPopover(true);
        }}
        className="flex items-center gap-1.5 hover:opacity-80 transition-opacity"
      >
        {pfpUrl ? (
          <img
            src={pfpUrl}
            alt=""
            className="w-4 h-4 rounded-full border border-[#00ff00]/30 hover:border-[#00ff00] transition-colors"
          />
        ) : (
          <div className="w-4 h-4 rounded-full bg-[#1a1a1a] border border-[#2a2a2a] hover:border-[#00ff00]/30 transition-colors" />
        )}
        <span className="text-gray-500 font-mono text-[10px] truncate hover:text-[#00ff00] transition-colors">
          {resolvedUsername ? `@${resolvedUsername}` : address.slice(0, 6) + "..."}
        </span>
      </button>

      <UserContentPopover
        isOpen={showPopover}
        onClose={() => setShowPopover(false)}
        address={address}
        username={resolvedUsername}
        pfpUrl={pfpUrl || undefined}
        fid={fid}
      />
    </>
  );
}


// Preview cell image with error handling
function PreviewCellImage({ url }: { url: string }) {
  const [hasError, setHasError] = useState(false);
  const imageUrl = toGatewayUrl(url || '');

  // No URL or error - show placeholder
  if (!imageUrl || hasError) {
    return (
      <div className="rounded-sm bg-[#00ff00]/20 w-full h-full flex items-center justify-center">
        <span className="text-[6px] text-[#00ff00]/50">!</span>
      </div>
    );
  }

  return (
    <div className="rounded-sm overflow-hidden bg-[#1a1a1a]">
      <img
        src={imageUrl}
        alt=""
        className="w-full h-full object-cover"
        loading="lazy"
        onError={() => setHasError(true)}
      />
    </div>
  );
}

// Mini grid preview (shows first 9 cells in 3x3 with actual cover images)
function GridPreview({ grid }: { grid: GridWithStats }) {
  const previewSize = Math.min(grid.size || 3, 3);
  const cells = grid.previewCells || [];

  // Create a map of filled cells with their data
  const filledCells = new Map<string, GridCell>();
  cells.forEach((cell) => {
    if (cell && cell.row < previewSize && cell.col < previewSize) {
      filledCells.set(`${cell.row}-${cell.col}`, cell);
    }
  });

  // If no cells, show empty grid placeholder
  const hasCells = cells.length > 0;

  return (
    <div
      className={`w-14 h-14 rounded-lg bg-black border p-0.5 grid gap-0.5 overflow-hidden ${
        hasCells ? "border-[#00ff00]/30" : "border-[#00ff00]/10"
      }`}
      style={{
        gridTemplateColumns: `repeat(${previewSize}, 1fr)`,
        gridTemplateRows: `repeat(${previewSize}, 1fr)`,
      }}
    >
      {Array.from({ length: previewSize * previewSize }).map((_, i) => {
        const row = Math.floor(i / previewSize);
        const col = i % previewSize;
        const cell = filledCells.get(`${row}-${col}`);

        if (cell) {
          return (
            <PreviewCellImage
              key={i}
              url={cell.coverUrl || cell.cdnUrl || ''}
            />
          );
        }

        return (
          <div
            key={i}
            className="rounded-sm bg-[#1a1a1a]"
          />
        );
      })}
    </div>
  );
}

// Icons
function GridIcon({ className }: { className?: string }) {
  return (
    <svg
      className={className}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <rect x="3" y="3" width="7" height="7" />
      <rect x="14" y="3" width="7" height="7" />
      <rect x="14" y="14" width="7" height="7" />
      <rect x="3" y="14" width="7" height="7" />
    </svg>
  );
}

// ArchiveIcon is now imported from net-library-icons

function SearchIcon({ className }: { className?: string }) {
  return (
    <svg
      className={className}
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <circle cx="11" cy="11" r="8" />
      <line x1="21" y1="21" x2="16.65" y2="16.65" />
    </svg>
  );
}

src/features/app/components/header.tsx
"use client";

import { useState, useMemo, useRef, useEffect } from "react";
import { H3 } from "@neynar/ui";
import { useDiscoveryContext } from "@/contexts/discovery-context";
import { useActiveMembers } from "@/hooks/use-active-members";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { useUpvoteCounts } from "@/hooks/use-upvotes";
import { useAccount, useDisconnect } from "wagmi";
import { UserLibraryCardModal } from "./user-library-card-modal";
import { ConnectWalletButton } from "./connect-wallet-button";
import { useAppMode } from "@/lib/app-mode";
import { useDesktopMode } from "@/hooks/use-desktop-mode";
import { usePlatformStatus } from "@/hooks/use-platform-status";
import { useUserProfile } from "@/hooks/use-user-profile";
import {
  getSavedWalletAddress,
  setWalletPreference,
  getWalletPreference,
  clearWalletPreference,
} from "@/neynar-web-sdk/src/blockchain/app/neynar-wagmi-provider";
import { LibraryIcon } from "@/components/icons/net-library-icons";


interface HeaderProps {
  /** Called when user taps "Net Library" title to return home */
  onHomeClick?: () => void;
}

export function Header({ onHomeClick }: HeaderProps = {}) {
  const { address } = useAccount();
  const { disconnect } = useDisconnect();
  const appMode = useAppMode();
  const { isDesktop } = useDesktopMode();
  const { entries } = useDiscoveryContext();
  const { activeCount, farcasterCount, baseAppCount, webCount } = useActiveMembers();
  const { isMember, memberId, ensSubname, username: memberUsername, registeredAddress, linkedAddresses, allMemberships, fid: memberFid, isLoading: isMembershipLoading } = useMembershipStatus();
  const { isFarcasterVerified, isBaseAppVerified, isWebVerified } = usePlatformStatus();
  const { profile: userProfile } = useUserProfile();
  const [showLibraryCard, setShowLibraryCard] = useState(false);

  // Track previous addresses to prevent flashing during refresh
  const prevAddressesRef = useRef<Set<string>>(new Set());

  // Build set of all addresses that belong to this user (for cross-platform identity)
  // Includes: connected wallet, registered membership address, linked addresses, and all membership addresses
  const computedAddresses = useMemo(() => {
    const addresses = new Set<string>();
    if (address) addresses.add(address.toLowerCase());
    if (registeredAddress) addresses.add(registeredAddress.toLowerCase());
    if (linkedAddresses) {
      for (const linked of linkedAddresses) {
        if (linked) addresses.add(linked.toLowerCase());
      }
    }
    // Also include addresses from all memberships (for cross-platform identity)
    if (allMemberships) {
      for (const membership of allMemberships) {
        if (membership.address) addresses.add(membership.address.toLowerCase());
      }
    }
    return addresses;
  }, [address, registeredAddress, linkedAddresses, allMemberships]);

  // Preserve previous addresses during loading to prevent upvote counter from flashing to 0
  const myAddresses = useMemo(() => {
    // During loading, use previous addresses if we had any
    if (isMembershipLoading && prevAddressesRef.current.size > 0) {
      return prevAddressesRef.current;
    }
    return computedAddresses;
  }, [isMembershipLoading, computedAddresses]);

  // Update ref when we have valid addresses
  useEffect(() => {
    if (!isMembershipLoading && computedAddresses.size > 0) {
      prevAddressesRef.current = computedAddresses;
    }
  }, [isMembershipLoading, computedAddresses]);

  // Sync wallet address to localStorage when it changes (e.g., user switches accounts in wallet)
  // This ensures stacks and other user data stay associated with the correct address
  // Only applies to web mode (not Farcaster mode where wallet is managed by the SDK)
  useEffect(() => {
    if (!address || appMode === "farcaster" || appMode === "detecting") return;

    const savedAddress = getSavedWalletAddress();
    const currentConnector = getWalletPreference();

    // If we have a connector preference but address differs or was never saved, update it
    if (currentConnector) {
      if (!savedAddress) {
        // First time saving address for this connector
        console.log(`[Header] Saving initial wallet address: ${address.slice(0, 6)}...`);
        setWalletPreference(currentConnector, address);
      } else if (savedAddress !== address.toLowerCase()) {
        // Address changed (user switched accounts in wallet app)
        console.log(`[Header] Wallet address changed from ${savedAddress.slice(0, 6)}... to ${address.slice(0, 6)}..., updating preference`);
        setWalletPreference(currentConnector, address);
      }
    }
  }, [address, appMode]);

  // Count user's uploads across ALL their addresses (memoized to prevent dependency issues).
  // Hidden items are invisible everywhere except the owner's hidden feed — not counted here.
  // Check uploaderAddress first — relay uploads store the backend wallet as `operator`
  // and the actual user's wallet as `uploaderAddress`. Fall back to operator for legacy entries.
  const myUploads = useMemo(() =>
    myAddresses.size > 0
      ? entries.filter((e) =>
          !e.hidden && (
            (e.uploaderAddress && myAddresses.has(e.uploaderAddress.toLowerCase())) ||
            (e.operator && myAddresses.has(e.operator.toLowerCase()))
          )
        )
      : [],
    [myAddresses, entries]
  );

  // Prepare items for upvote count fetching (only user's uploads)
  // Use uploaderAddress (user's actual wallet) if present, falling back to operator
  // (backend relay wallet) — must match the address used when casting upvotes
  const upvoteItems = useMemo(() =>
    myUploads.map(upload => ({
      contentKey: upload.contentKey,
      operator: upload.uploaderAddress || upload.operator,
    })),
    [myUploads]
  );

  // Fetch upvote counts for user's uploads
  const { getCount: getUpvoteCount, isLoading: isUpvotesLoading } = useUpvoteCounts(upvoteItems);

  // Track previous upvote count to prevent flashing to 0 during load
  // Initialize from localStorage
  const prevUpvoteCountRef = useRef<number>(
    typeof window !== "undefined" ? parseInt(localStorage.getItem("nl_upvote_count") || "0", 10) : 0
  );

  // Calculate total upvotes received
  const computedUpvotes = useMemo(() =>
    myUploads.reduce((total, upload) => total + getUpvoteCount(upload.contentKey), 0),
    [myUploads, getUpvoteCount]
  );

  // Persist upvote count when loaded
  useEffect(() => {
    if (!isUpvotesLoading && computedUpvotes > 0) {
      prevUpvoteCountRef.current = computedUpvotes;
      try {
        localStorage.setItem("nl_upvote_count", String(computedUpvotes));
      } catch {
        // Ignore storage errors
      }
    }
  }, [isUpvotesLoading, computedUpvotes]);

  // Invalidate cache when user's upload count changes (new upload or content removed)
  // This ensures the cached value doesn't show stale counts across sessions
  const uploadCountRef = useRef(myUploads.length);
  useEffect(() => {
    if (myUploads.length !== uploadCountRef.current) {
      // Upload count changed - clear cached value so we show fresh data
      uploadCountRef.current = myUploads.length;
      if (myUploads.length === 0) {
        // User has no uploads anymore, clear the cache
        prevUpvoteCountRef.current = 0;
        try {
          localStorage.removeItem("nl_upvote_count");
        } catch {
          // Ignore storage errors
        }
      }
    }
  }, [myUploads.length]);

  // Use cached value during loading OR when computed drops to 0 temporarily
  // This prevents flash to 0 when membership/verification refreshes cause myUploads to briefly empty
  const totalUpvotesReceived = (isUpvotesLoading || (computedUpvotes === 0 && prevUpvoteCountRef.current > 0))
    ? prevUpvoteCountRef.current
    : computedUpvotes;

  // Desktop: more spacious header with additional stats
  const headerPadding = isDesktop ? "px-6 py-4" : "px-4 py-3";

  return (
    <div className="shrink-0">
      <header className={`${headerPadding} border-b-2 border-[#00ff00]/30 flex items-start justify-between bg-black`}>
        <div className="flex flex-col">
          {onHomeClick ? (
            <button
              onClick={onHomeClick}
              className="focus:outline-none active:opacity-70 transition-opacity"
            >
              <H3 className="text-[#00ff00] font-mono tracking-tight leading-tight hover:text-[#00ff00]/80">Net Library</H3>
            </button>
          ) : (
            <H3 className="text-[#00ff00] font-mono tracking-tight leading-tight">Net Library</H3>
          )}
          {/* Subtitle - sized to align online tracker with verification badges on right */}
          <span className="text-base text-gray-400 font-mono mt-1">powered by Net Protocol</span>
          {/* Online tracker only */}
          <div className="flex items-center gap-2 mt-1">
            <div className="w-1.5 h-1.5 rounded-full bg-[#00ff00] animate-pulse shadow-[0_0_6px_#00ff00]" />
            <span className="text-[10px] text-[#00ff00] font-mono">{activeCount} online</span>
            <span className="text-[9px] font-mono text-purple-400">{farcasterCount}</span>
            <span className="text-[7px] text-gray-600">/</span>
            <span className="text-[9px] font-mono text-blue-400">{baseAppCount}</span>
            <span className="text-[7px] text-gray-600">/</span>
            <span className="text-[9px] font-mono text-yellow-400">{webCount}</span>
          </div>
          {/* Desktop: additional stats row */}
          {isDesktop && (
            <div className="flex items-center gap-3 mt-1.5 text-[10px] font-mono text-gray-500">
              <span className="flex items-center gap-1"><LibraryIcon size={10} /> {entries.length} items</span>
              <span>•</span>
              <span className="flex items-center gap-1">↑ {myUploads.length} uploads</span>
            </div>
          )}
        </div>
        {/* Desktop: horizontal layout for user info; Mobile: vertical */}
        <div className={isDesktop ? "flex items-center gap-4" : "flex flex-col items-center"}>
          {/* Base App / Web Mode: Show Connect Wallet when not connected */}
          {(appMode === "base-app" || appMode === "web") && !address ? (
            <ConnectWalletButton />
          ) : (
            <>
              {/* PFP - Tappable to view library card */}
              <button
                onClick={() => isMember && setShowLibraryCard(true)}
                className="focus:outline-none focus:ring-2 focus:ring-[#00ff00]/50 rounded-full"
                disabled={!isMember}
              >
                {userProfile?.pfpUrl ? (
                  <img
                    src={userProfile.pfpUrl}
                    alt={userProfile.username || "User"}
                    className={`${isDesktop ? "w-12 h-12" : "w-10 h-10"} rounded-full border-2 border-[#00ff00] object-cover hover:shadow-[0_0_10px_rgba(0,255,0,0.5)] transition-all cursor-pointer`}
                  />
                ) : (
                  <div className={`${isDesktop ? "w-12 h-12" : "w-10 h-10"} rounded-full border-2 border-[#00ff00] bg-[#00ff00]/20 flex items-center justify-center hover:shadow-[0_0_10px_rgba(0,255,0,0.5)] transition-all cursor-pointer`}>
                    <span className="text-[#00ff00] text-sm font-mono">?</span>
                  </div>
                )}
              </button>
              {/* Desktop: user info in a column next to PFP */}
              <div className={isDesktop ? "flex flex-col" : "flex flex-col items-center"}>
                {/* Show username across ALL platforms for unified identity */}
                {/* Priority: stored Farcaster username > userProfile username > truncated address */}
                {(userProfile?.storedFarcasterUsername || userProfile?.username) ? (
                  <span className={`${isDesktop ? "text-sm" : "text-[10px]"} text-[#00ff00] font-mono ${isDesktop ? "" : "mt-1"}`}>
                    @{userProfile?.storedFarcasterUsername || userProfile?.username}
                  </span>
                ) : address ? (
                  <span className={`${isDesktop ? "text-sm" : "text-[10px]"} text-[#00ff00] font-mono ${isDesktop ? "" : "mt-1"}`}>
                    {/* Fallback to truncated address if no username available */}
                    {address.slice(0, 6)}...{address.slice(-4)}
                  </span>
                ) : null}
                {/* Upvote count (icon + number only) */}
                <span className={`${isDesktop ? "text-xs" : "text-[10px]"} text-gray-500 font-mono`}>
                  ▲ {totalUpvotesReceived}
                </span>
                {/* Platform verification badges */}
                <div className="flex items-center gap-0.5 mt-0.5">
                  <span className={`text-[10px] font-mono ${isFarcasterVerified ? "text-purple-400" : "text-purple-400/30"}`}>
                    {isFarcasterVerified ? "✓" : "✕"}
                  </span>
                  <span className="text-[8px] text-gray-600">/</span>
                  <span className={`text-[10px] font-mono ${isBaseAppVerified ? "text-blue-400" : "text-blue-400/30"}`}>
                    {isBaseAppVerified ? "✓" : "✕"}
                  </span>
                  <span className="text-[8px] text-gray-600">/</span>
                  <span className={`text-[10px] font-mono ${isWebVerified ? "text-yellow-400" : "text-yellow-400/30"}`}>
                    {isWebVerified ? "✓" : "✕"}
                  </span>
                </div>
              </div>
              {/* Disconnect button - only show in web mode */}
              {appMode === "web" && address && (
                <button
                  onClick={() => {
                    clearWalletPreference();
                    disconnect();
                  }}
                  className={`${isDesktop ? "px-3 py-1.5 bg-[#1a1a1a] rounded-lg hover:bg-red-500/20" : "mt-1"} text-[9px] text-gray-500 font-mono hover:text-red-400 transition-colors ${isDesktop ? "" : "underline"}`}
                >
                  Disconnect
                </button>
              )}
            </>
          )}
        </div>
      </header>

      {/* User Library Card Modal */}
      {isMember && memberId !== null && (registeredAddress || address) && (
        <UserLibraryCardModal
          isOpen={showLibraryCard}
          onClose={() => setShowLibraryCard(false)}
          member={{
            memberId,
            // Use registered address (primary membership address) not connected wallet
            // This handles smart wallets which may have different addresses
            address: registeredAddress || address!,
            ensSubname: ensSubname || "",
            username: memberUsername || userProfile?.username || "",
            joinedAt: Date.now(),
            pfpUrl: userProfile?.pfpUrl,
            // Include FID and linked addresses for proper verification display
            fid: memberFid || userProfile?.fid,
            linkedAddresses: linkedAddresses,
          }}
          allMemberships={allMemberships}
        />
      )}

    </div>
  );
}
src/features/app/components/image-editor/image-editor.tsx
"use client";

import { useState, useRef, useEffect, useCallback } from "react";
import { Canvas, PencilBrush, SprayBrush, FabricImage, IText } from "fabric";
import { Small, Tooltip, TooltipTrigger, TooltipContent } from "@neynar/ui";
import { RefreshIcon, CheckCircleIcon, UploadIcon, PointerIcon, BrushIcon, EraserIcon, TypeIcon, SmileIcon, CameraIcon, FrogIcon, TrashIcon, UndoIcon, RedoIcon, CrosshairIcon, ZoomIcon, PaletteIcon, MagnetIcon, LayersIcon, RulerIcon, LightbulbIcon, SaveIcon, ArrowUpIcon, ArrowDownIcon, ArrowLeftIcon, ArrowRightIcon, RotateCcwIcon, RotateCwIcon, BringForwardIcon, SendBackwardIcon, AlignLeftIcon, AlignCenterHIcon, AlignRightIcon, AlignTopIcon, AlignCenterVIcon, AlignBottomIcon } from "@/components/icons/net-library-icons";
import { useCanvasHistory } from "./use-canvas-history";
import { fetchMemeTemplates, getMemeTemplateUrl, searchTemplates } from "./meme-templates";
import { safeOpenUrl } from "@/lib/app-mode";
import {
  CANVAS_PRESETS,
  FONT_FAMILIES,
  PRESET_COLORS,
  EDITOR_RECOVERY_KEY,
  EDITOR_AUTOSAVE_INTERVAL,
  type EditorTool,
  type BrushSettings,
  type TextSettings,
  type MemeTemplate,
  type EditorRecoveryData,
  type CanvasPreset,
} from "./types";

// Common emojis for stamps
const EMOJI_LIST = [
  "😀", "😂", "🤣", "😍", "🥰", "😎", "🤩", "🥳",
  "😭", "😤", "🤬", "💀", "👻", "🔥", "💯", "⭐",
  "❤️", "💔", "💪", "👍", "👎", "👀", "🙌", "🎉",
  "🚀", "💰", "🧠", "🤡", "💩", "🐸", "🦍", "🌙",
];

// Toolbar button with tooltip
interface ToolbarButtonProps {
  onClick: () => void;
  isActive?: boolean;
  tooltip: string;
  children: React.ReactNode;
  className?: string;
  disabled?: boolean;
}

function ToolbarButton({ onClick, isActive, tooltip, children, className, disabled }: ToolbarButtonProps) {
  return (
    <Tooltip delayDuration={300}>
      <TooltipTrigger asChild>
        <button
          onClick={onClick}
          disabled={disabled}
          className={`p-1.5 rounded text-base min-h-[36px] ${
            isActive
              ? "bg-[#00ff00]/20 text-[#00ff00]"
              : disabled
                ? "text-gray-700"
                : "text-gray-400 active:bg-gray-800"
          } ${className || ""}`}
        >
          {children}
        </button>
      </TooltipTrigger>
      <TooltipContent side="bottom" sideOffset={4} className="bg-gray-900 text-gray-100 border border-gray-700">
        {tooltip}
      </TooltipContent>
    </Tooltip>
  );
}

// Row 2 toolbar button (smaller) with color variants
interface ToolbarButton2Props {
  onClick: () => void;
  isActive?: boolean;
  tooltip: string;
  children: React.ReactNode;
  variant?: "orange" | "pink" | "yellow" | "green" | "blue" | "cyan";
}

const variantStyles = {
  orange: "bg-orange-500/20 text-orange-400",
  pink: "bg-pink-500/20 text-pink-400",
  yellow: "bg-yellow-500/20 text-yellow-400",
  green: "bg-green-500/20 text-green-400",
  blue: "bg-blue-500/20 text-blue-400",
  cyan: "bg-cyan-500/20 text-cyan-400",
};

function ToolbarButton2({ onClick, isActive, tooltip, children, variant = "green" }: ToolbarButton2Props) {
  return (
    <Tooltip delayDuration={300}>
      <TooltipTrigger asChild>
        <button
          onClick={onClick}
          className={`p-1.5 rounded text-xs font-mono min-h-[32px] flex items-center justify-center gap-1 ${
            isActive ? variantStyles[variant] : "text-gray-400 active:bg-gray-800"
          }`}
        >
          {children}
        </button>
      </TooltipTrigger>
      <TooltipContent side="bottom" sideOffset={4} className="bg-gray-900 text-gray-100 border border-gray-700">
        {tooltip}
      </TooltipContent>
    </Tooltip>
  );
}

// Background color presets (null = transparent)
const BACKGROUND_COLORS: { id: string; color: string | null; label: string; preview: string }[] = [
  { id: "transparent", color: null, label: "None", preview: "🏁" },
  { id: "white", color: "#ffffff", label: "White", preview: "" },
  { id: "black", color: "#000000", label: "Black", preview: "" },
  { id: "dark", color: "#1a1a1a", label: "Dark", preview: "" },
  { id: "green", color: "#00ff00", label: "Matrix", preview: "" },
  { id: "purple", color: "#7c3aed", label: "Purple", preview: "" },
];

interface ImageEditorProps {
  onExport: (dataUrl: string, format: string) => void;
  onCancel: () => void;
  /** Called when user wants to upload after saving/downloading */
  onUploadAfterSave?: (dataUrl: string, format: string) => void;
}

export function ImageEditor({ onExport, onCancel, onUploadAfterSave }: ImageEditorProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const [canvas, setCanvas] = useState<Canvas | null>(null);
  const [tool, setTool] = useState<EditorTool>("select");
  const [showRecoveryPrompt, setShowRecoveryPrompt] = useState(false);
  const [recoveryData, setRecoveryData] = useState<EditorRecoveryData | null>(null);

  // Upload after save prompt
  const [showUploadPrompt, setShowUploadPrompt] = useState(false);
  const [savedImageData, setSavedImageData] = useState<{ dataUrl: string; format: string } | null>(null);

  // Canvas size state - default to mobile-friendly size (scales up on export)
  const [canvasSize, setCanvasSize] = useState({ width: 360, height: 360 });
  const [selectedPreset, setSelectedPreset] = useState<string>("square");
  const [customWidth, setCustomWidth] = useState("1080");
  const [customHeight, setCustomHeight] = useState("1080");
  const [showSizePanel, setShowSizePanel] = useState(false);

  // Background color (null = transparent, shown as checkerboard in editor)
  const [backgroundColor, setBackgroundColor] = useState<string | null>("#1a1a1a");
  const [showBgPanel, setShowBgPanel] = useState(false);

  // Brush settings
  const [brush, setBrush] = useState<BrushSettings>({
    type: "pencil",
    color: "#ffffff",
    size: 5,
    opacity: 1,
  });

  // Text settings
  const [textSettings, setTextSettings] = useState<TextSettings>({
    fontFamily: "Impact",
    fontSize: 48,
    fill: "#ffffff",
    fontWeight: "bold",
    fontStyle: "normal",
    underline: false,
    stroke: "#000000",
    strokeWidth: 2,
    textAlign: "center",
  });

  // Meme templates
  const [memeTemplates, setMemeTemplates] = useState<MemeTemplate[]>([]);
  const [memeSearch, setMemeSearch] = useState("");
  const [showMemePanel, setShowMemePanel] = useState(false);
  const [isLoadingTemplates, setIsLoadingTemplates] = useState(false);

  // UI panels
  const [showBrushPanel, setShowBrushPanel] = useState(false);
  const [showTextPanel, setShowTextPanel] = useState(false);
  const [showEmojiPanel, setShowEmojiPanel] = useState(false);
  const [showLayerPanel, setShowLayerPanel] = useState(false);
  const [_showExportPanel, setShowExportPanel] = useState(false);
  const [showSavePanel, setShowSavePanel] = useState(false);
  const [showNudgePanel, setShowNudgePanel] = useState(false);
  const [showScalePanel, setShowScalePanel] = useState(false);

  // Scale slider state (percentage 10-200%)
  const [scaleValue, setScaleValue] = useState(100);

  // Snap to center toggle
  const [snapEnabled, setSnapEnabled] = useState(true);
  const SNAP_THRESHOLD = 10; // pixels

  // History
  const { saveState, undo, redo, canUndo, canRedo, initHistory, clearHistory } = useCanvasHistory(canvas);

  // Track blob URLs created during the session so they can be revoked on unmount
  const blobUrlsRef = useRef<string[]>([]);

  // Revoke all tracked blob URLs when the component unmounts
  useEffect(() => {
    return () => {
      blobUrlsRef.current.forEach((url) => URL.revokeObjectURL(url));
      blobUrlsRef.current = [];
    };
  }, []);

  // Initialize canvas
  useEffect(() => {
    if (!canvasRef.current || canvas) return;

    const fabricCanvas = new Canvas(canvasRef.current, {
      width: canvasSize.width,
      height: canvasSize.height,
      backgroundColor: "#1a1a1a",
      selection: true,
    });

    setCanvas(fabricCanvas);

    // Check for recovery data
    try {
      const saved = localStorage.getItem(EDITOR_RECOVERY_KEY);
      if (saved) {
        const data = JSON.parse(saved) as EditorRecoveryData;
        // Only offer recovery if less than 24 hours old
        if (Date.now() - data.savedAt < 24 * 60 * 60 * 1000) {
          setRecoveryData(data);
          setShowRecoveryPrompt(true);
        } else {
          localStorage.removeItem(EDITOR_RECOVERY_KEY);
        }
      }
    } catch {
      // Ignore errors
    }

    return () => {
      fabricCanvas.dispose();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Initialize history after canvas is ready
  useEffect(() => {
    if (canvas && !showRecoveryPrompt) {
      initHistory();
    }
  }, [canvas, showRecoveryPrompt, initHistory]);

  // Update canvas background when backgroundColor changes
  useEffect(() => {
    if (!canvas) return;
    // For transparent, we set backgroundColor to undefined/empty so it exports transparent
    // The checkerboard pattern is shown via CSS on the container
    canvas.backgroundColor = backgroundColor || "";
    canvas.renderAll();
  }, [canvas, backgroundColor]);

  // Change background color
  const changeBackgroundColor = useCallback((color: string | null) => {
    setBackgroundColor(color);
    setShowBgPanel(false);
    saveState();
  }, [saveState]);

  // Auto-save
  useEffect(() => {
    if (!canvas) return;

    const interval = setInterval(() => {
      const json = JSON.stringify(canvas.toJSON());
      const data: EditorRecoveryData = {
        canvasJson: json,
        canvasSize,
        savedAt: Date.now(),
      };
      localStorage.setItem(EDITOR_RECOVERY_KEY, JSON.stringify(data));
    }, EDITOR_AUTOSAVE_INTERVAL);

    return () => clearInterval(interval);
  }, [canvas, canvasSize]);

  // Handle recovery
  const handleRecover = useCallback(() => {
    if (!canvas || !recoveryData) return;

    canvas.loadFromJSON(JSON.parse(recoveryData.canvasJson)).then(() => {
      setCanvasSize(recoveryData.canvasSize);
      canvas.setDimensions(recoveryData.canvasSize);
      canvas.renderAll();
      initHistory();
      setShowRecoveryPrompt(false);
      setRecoveryData(null);
    });
  }, [canvas, recoveryData, initHistory]);

  const handleDiscardRecovery = useCallback(() => {
    localStorage.removeItem(EDITOR_RECOVERY_KEY);
    setShowRecoveryPrompt(false);
    setRecoveryData(null);
    initHistory();
  }, [initHistory]);

  // Update brush when tool or settings change
  useEffect(() => {
    if (!canvas) return;

    if (tool === "draw" || tool === "eraser") {
      canvas.isDrawingMode = true;

      let fabricBrush;
      if (brush.type === "spray") {
        fabricBrush = new SprayBrush(canvas);
        fabricBrush.density = 20;
      } else if (brush.type === "marker") {
        // Marker: thicker brush with rounded caps for marker-like strokes
        fabricBrush = new PencilBrush(canvas);
        fabricBrush.strokeLineCap = "round";
        fabricBrush.strokeLineJoin = "round";
      } else {
        // Pencil (default)
        fabricBrush = new PencilBrush(canvas);
      }

      // Eraser: paint with the actual canvas background color so strokes
      // visually "erase" the drawing. Falls back to transparent for transparent
      // backgrounds (note: fabric.js PencilBrush doesn't support true
      // destination-out compositing, so transparent bg erasing is approximate).
      fabricBrush.color = tool === "eraser"
        ? (backgroundColor || "rgba(0,0,0,0)")
        : brush.color;
      // Marker is naturally thicker (2x size)
      fabricBrush.width = brush.type === "marker" ? brush.size * 2 : brush.size;
      canvas.freeDrawingBrush = fabricBrush;
    } else {
      canvas.isDrawingMode = false;
    }
  }, [canvas, tool, brush, backgroundColor]);

  // Save state on object modifications
  useEffect(() => {
    if (!canvas) return;

    // Debounce to prevent duplicate saves from multiple events firing
    let saveTimeout: NodeJS.Timeout | null = null;
    const debouncedSave = () => {
      if (saveTimeout) clearTimeout(saveTimeout);
      saveTimeout = setTimeout(() => {
        saveState();
      }, 50); // Small delay to batch rapid events
    };

    canvas.on("object:modified", debouncedSave);
    canvas.on("object:added", debouncedSave);
    canvas.on("path:created", debouncedSave);

    return () => {
      if (saveTimeout) clearTimeout(saveTimeout);
      canvas.off("object:modified", debouncedSave);
      canvas.off("object:added", debouncedSave);
      canvas.off("path:created", debouncedSave);
    };
  }, [canvas, saveState]);

  // Snap to center guides
  useEffect(() => {
    if (!canvas) return;

    const centerX = canvasSize.width / 2;
    const centerY = canvasSize.height / 2;

    const handleMoving = (e: { target?: { left?: number; top?: number; set: (props: Record<string, number>) => void } }) => {
      if (!snapEnabled || !e.target) return;

      const obj = e.target;
      const left = obj.left ?? 0;
      const top = obj.top ?? 0;

      // Snap to horizontal center
      if (Math.abs(left - centerX) < SNAP_THRESHOLD) {
        obj.set({ left: centerX });
      }

      // Snap to vertical center
      if (Math.abs(top - centerY) < SNAP_THRESHOLD) {
        obj.set({ top: centerY });
      }
    };

    canvas.on("object:moving", handleMoving);

    return () => {
      canvas.off("object:moving", handleMoving);
    };
  }, [canvas, canvasSize, snapEnabled, SNAP_THRESHOLD]);

  // Load meme templates
  useEffect(() => {
    if (showMemePanel && memeTemplates.length === 0) {
      setIsLoadingTemplates(true);
      fetchMemeTemplates().then((templates) => {
        setMemeTemplates(templates);
        setIsLoadingTemplates(false);
      });
    }
  }, [showMemePanel, memeTemplates.length]);

  // Handle canvas resize
  const handleResize = useCallback((preset: CanvasPreset) => {
    if (!canvas) return;

    if (preset.id === "custom") {
      setSelectedPreset("custom");
      setShowSizePanel(true);
      return;
    }

    setCanvasSize({ width: preset.width, height: preset.height });
    canvas.setDimensions({ width: preset.width, height: preset.height });
    canvas.renderAll();
    setSelectedPreset(preset.id);
    saveState();
  }, [canvas, saveState]);

  const applyCustomSize = useCallback(() => {
    if (!canvas) return;

    const width = Math.max(100, Math.min(4096, parseInt(customWidth) || 1080));
    const height = Math.max(100, Math.min(4096, parseInt(customHeight) || 1080));

    setCanvasSize({ width, height });
    canvas.setDimensions({ width, height });
    canvas.renderAll();
    setShowSizePanel(false);
    saveState();
  }, [canvas, customWidth, customHeight, saveState]);

  // Add text
  const addText = useCallback(() => {
    if (!canvas) return;

    const text = new IText("Double-click to edit", {
      left: canvasSize.width / 2,
      top: canvasSize.height / 2,
      originX: "center",
      originY: "center",
      fontFamily: textSettings.fontFamily,
      fontSize: textSettings.fontSize,
      fill: textSettings.fill,
      fontWeight: textSettings.fontWeight,
      fontStyle: textSettings.fontStyle,
      underline: textSettings.underline,
      stroke: textSettings.stroke,
      strokeWidth: textSettings.strokeWidth,
      textAlign: textSettings.textAlign,
      editable: true,
    });

    canvas.add(text);
    canvas.setActiveObject(text);
    canvas.renderAll();
    setTool("select");
  }, [canvas, canvasSize, textSettings]);

  // Add emoji
  const addEmoji = useCallback((emoji: string) => {
    if (!canvas) return;

    const text = new IText(emoji, {
      left: canvasSize.width / 2,
      top: canvasSize.height / 2,
      originX: "center",
      originY: "center",
      fontSize: 72,
      editable: false,
    });

    canvas.add(text);
    canvas.setActiveObject(text);
    canvas.renderAll();
    setShowEmojiPanel(false);
    setTool("select");
  }, [canvas, canvasSize]);

  // Calculate optimal scale to fit image in canvas with visible touch handles
  const calculateFitScale = useCallback((imgWidth: number, imgHeight: number) => {
    // Use 80% of canvas to ensure touch handles are always visible
    // (handles add ~20px on each side, so 80% gives plenty of room)
    const maxWidth = canvasSize.width * 0.8;
    const maxHeight = canvasSize.height * 0.8;

    const scaleX = maxWidth / imgWidth;
    const scaleY = maxHeight / imgHeight;

    // Use the smaller scale to ensure the image fits both dimensions
    return Math.min(scaleX, scaleY, 1); // Also cap at 1 to not upscale small images
  }, [canvasSize]);

  // Import image from device
  const handleImageImport = useCallback(() => {
    const input = document.createElement("input");
    input.type = "file";
    input.accept = "image/*";
    input.onchange = async (e) => {
      const file = (e.target as HTMLInputElement).files?.[0];
      if (!file || !canvas) return;

      const reader = new FileReader();
      reader.onload = async (event) => {
        const dataUrl = event.target?.result as string;
        const img = await FabricImage.fromURL(dataUrl);

        if (!img.width || !img.height) return;

        // Calculate proper scale to fit with visible handles
        const scale = calculateFitScale(img.width, img.height);

        img.scale(scale);
        img.set({
          left: canvasSize.width / 2,
          top: canvasSize.height / 2,
          originX: "center",
          originY: "center",
        });

        canvas.add(img);
        canvas.setActiveObject(img);
        canvas.requestRenderAll();
        saveState();
      };
      reader.readAsDataURL(file);
    };
    input.click();
  }, [canvas, canvasSize, saveState, calculateFitScale]);

  // Load meme template
  const loadMemeTemplate = useCallback(async (template: MemeTemplate) => {
    if (!canvas) return;

    try {
      const url = getMemeTemplateUrl(template.id);
      console.log("[ImageEditor] Loading meme template:", url);

      const img = await FabricImage.fromURL(url, { crossOrigin: "anonymous" });

      if (!img || !img.width || !img.height) {
        console.error("[ImageEditor] Failed to load meme image - invalid dimensions");
        return;
      }

      console.log("[ImageEditor] Meme loaded:", img.width, "x", img.height, "Canvas:", canvasSize.width, "x", canvasSize.height);

      // Calculate proper scale to fit with visible handles
      const scale = calculateFitScale(img.width, img.height);

      console.log("[ImageEditor] Scaling meme by:", scale.toFixed(3));

      img.scale(scale);
      img.set({
        left: canvasSize.width / 2,
        top: canvasSize.height / 2,
        originX: "center",
        originY: "center",
      });

      canvas.add(img);
      canvas.sendObjectToBack(img);
      canvas.setActiveObject(img); // Select it so user knows it was added
      canvas.requestRenderAll(); // Force render
      setShowMemePanel(false);
      saveState();

      console.log("[ImageEditor] Meme added to canvas, objects:", canvas.getObjects().length);
    } catch (error) {
      console.error("Failed to load meme template:", error);
    }
  }, [canvas, canvasSize, saveState, calculateFitScale]);

  // Layer controls
  const bringForward = useCallback(() => {
    if (!canvas) return;
    const active = canvas.getActiveObject();
    if (active) {
      canvas.bringObjectForward(active);
      canvas.renderAll();
      saveState();
    }
  }, [canvas, saveState]);

  const sendBackward = useCallback(() => {
    if (!canvas) return;
    const active = canvas.getActiveObject();
    if (active) {
      canvas.sendObjectBackwards(active);
      canvas.renderAll();
      saveState();
    }
  }, [canvas, saveState]);

  const deleteSelected = useCallback(() => {
    if (!canvas) return;
    const active = canvas.getActiveObjects();
    if (active.length > 0) {
      active.forEach((obj) => canvas.remove(obj));
      canvas.discardActiveObject();
      canvas.renderAll();
      saveState();
    }
  }, [canvas, saveState]);

  // Alignment
  const alignObject = useCallback((alignment: "left" | "center" | "right" | "top" | "middle" | "bottom") => {
    if (!canvas) return;
    const active = canvas.getActiveObject();
    if (!active) return;

    switch (alignment) {
      case "left":
        active.set("left", 0);
        break;
      case "center":
        active.set("left", canvasSize.width / 2);
        active.set("originX", "center");
        break;
      case "right":
        active.set("left", canvasSize.width - (active.width || 0) * (active.scaleX || 1));
        break;
      case "top":
        active.set("top", 0);
        break;
      case "middle":
        active.set("top", canvasSize.height / 2);
        active.set("originY", "center");
        break;
      case "bottom":
        active.set("top", canvasSize.height - (active.height || 0) * (active.scaleY || 1));
        break;
    }

    canvas.renderAll();
    saveState();
  }, [canvas, canvasSize, saveState]);

  // Nudge controls
  const nudgeObject = useCallback((direction: "left" | "right" | "up" | "down", amount = 1) => {
    if (!canvas) return;
    const active = canvas.getActiveObject();
    if (!active) return;

    switch (direction) {
      case "left":
        active.set("left", (active.left || 0) - amount);
        break;
      case "right":
        active.set("left", (active.left || 0) + amount);
        break;
      case "up":
        active.set("top", (active.top || 0) - amount);
        break;
      case "down":
        active.set("top", (active.top || 0) + amount);
        break;
    }
    canvas.renderAll();
    saveState();
  }, [canvas, saveState]);

  const rotateObject = useCallback((degrees: number) => {
    if (!canvas) return;
    const active = canvas.getActiveObject();
    if (!active) return;

    active.rotate((active.angle || 0) + degrees);
    canvas.renderAll();
    saveState();
  }, [canvas, saveState]);

  // Scale selected object by percentage (10-200%)
  const scaleObject = useCallback((percent: number) => {
    if (!canvas) return;
    const active = canvas.getActiveObject();
    if (!active) return;

    // Convert percentage to scale factor (100% = original size when first selected)
    const scaleFactor = percent / 100;

    // Apply uniform scale
    active.scale(scaleFactor);
    canvas.renderAll();
  }, [canvas]);

  // Apply scale and save to history
  const applyScale = useCallback(() => {
    if (!canvas) return;
    saveState();
    setShowScalePanel(false);
  }, [canvas, saveState]);

  // Update scale slider when selection changes
  useEffect(() => {
    if (!canvas) return;

    const updateScaleFromSelection = () => {
      const active = canvas.getActiveObject();
      if (active) {
        // Get current scale as percentage (scaleX and scaleY should be equal for uniform scale)
        const currentScale = Math.round((active.scaleX || 1) * 100);
        setScaleValue(currentScale);
      }
    };

    canvas.on("selection:created", updateScaleFromSelection);
    canvas.on("selection:updated", updateScaleFromSelection);

    return () => {
      canvas.off("selection:created", updateScaleFromSelection);
      canvas.off("selection:updated", updateScaleFromSelection);
    };
  }, [canvas]);

  // Export
  const _handleExport = useCallback((format: string) => {
    if (!canvas) return;

    // Clear selection before export
    canvas.discardActiveObject();
    canvas.renderAll();

    // Scale up to the target export resolution (default 1080px wide).
    // Guard against canvasSize.width === 0 (before canvas init or during resize).
    const targetWidth = parseInt(customWidth) || 1080;
    const multiplier = canvasSize.width > 0 ? targetWidth / canvasSize.width : 1;

    const dataUrl = canvas.toDataURL({
      format: format as "png" | "jpeg" | "webp",
      quality: format === "jpeg" ? 0.9 : 1,
      multiplier,
    });

    // Clear recovery data on successful export
    localStorage.removeItem(EDITOR_RECOVERY_KEY);
    clearHistory();

    onExport(dataUrl, format);
  }, [canvas, clearHistory, onExport, customWidth, canvasSize.width]);

  // Save to photos (direct download as PNG)
  const saveToPhotos = useCallback(() => {
    if (!canvas) return;

    canvas.discardActiveObject();
    canvas.renderAll();

    // Scale up to target export resolution.
    // Guard against canvasSize.width === 0 (before canvas init or during resize).
    const targetWidth = parseInt(customWidth) || 1080;
    const multiplier = canvasSize.width > 0 ? targetWidth / canvasSize.width : 1;
    const dataUrl = canvas.toDataURL({ format: "png", multiplier });

    // Create download link - triggers save to photos on mobile
    const link = document.createElement("a");
    link.download = `net-library-creation-${Date.now()}.png`;
    link.href = dataUrl;
    link.click();

    localStorage.removeItem(EDITOR_RECOVERY_KEY);
    setShowSavePanel(false);

    // Show upload prompt after saving
    setSavedImageData({ dataUrl, format: "png" });
    setShowUploadPrompt(true);
  }, [canvas, customWidth, canvasSize.width]);

  // Save image as specific format (opens in external browser for download)
  const saveImageAs = useCallback(async (format: "png" | "jpeg" | "webp") => {
    if (!canvas) return;

    canvas.discardActiveObject();
    canvas.renderAll();

    // Scale up to target export resolution.
    // Guard against canvasSize.width === 0 (before canvas init or during resize).
    const targetWidth = parseInt(customWidth) || 1080;
    const multiplier = canvasSize.width > 0 ? targetWidth / canvasSize.width : 1;
    const dataUrl = canvas.toDataURL({
      format,
      quality: format === "jpeg" ? 0.9 : 1,
      multiplier,
    });

    // Convert data URL to blob and create object URL for download
    // NOTE: We use manual base64 decoding instead of fetch() because Safari/iOS/Base App
    // can throw "Load failed" when fetch() is called on data: URLs due to WebKit security policies.
    let blob: Blob;
    try {
      const [header, base64Data] = dataUrl.split(",");
      const mimeMatch = header.match(/data:([^;]+)/);
      const mimeType = mimeMatch ? mimeMatch[1] : (format === "jpeg" ? "image/jpeg" : `image/${format}`);
      const binaryString = atob(base64Data);
      const bytes = new Uint8Array(binaryString.length);
      for (let i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
      }
      blob = new Blob([bytes], { type: mimeType });
    } catch (decodeError) {
      console.error("[ImageEditor] Base64 decode failed, falling back to fetch:", decodeError);
      const response = await fetch(dataUrl);
      blob = await response.blob();
    }
    const blobUrl = URL.createObjectURL(blob);
    // Track for cleanup on unmount
    blobUrlsRef.current.push(blobUrl);

    // Open in external browser - this breaks out of the mini app on mobile
    // and allows the user to save the file properly
    await safeOpenUrl(blobUrl);

    localStorage.removeItem(EDITOR_RECOVERY_KEY);
    setShowSavePanel(false);
    setShowExportPanel(false);
  }, [canvas, customWidth, canvasSize.width]);

  // Handle upload after save
  const handleUploadAfterSave = useCallback(() => {
    if (!savedImageData || !onUploadAfterSave) return;
    setShowUploadPrompt(false);
    onUploadAfterSave(savedImageData.dataUrl, savedImageData.format);
  }, [savedImageData, onUploadAfterSave]);

  const dismissUploadPrompt = useCallback(() => {
    setShowUploadPrompt(false);
    setSavedImageData(null);
  }, []);

  // Direct upload without saving first
  const handleDirectUpload = useCallback(() => {
    if (!canvas || !onUploadAfterSave) return;
    canvas.discardActiveObject();
    canvas.renderAll();
    // Scale up to target export resolution.
    // Guard against canvasSize.width === 0 (before canvas init or during resize).
    const targetWidth = parseInt(customWidth) || 1080;
    const multiplier = canvasSize.width > 0 ? targetWidth / canvasSize.width : 1;
    const dataUrl = canvas.toDataURL({ format: "png", multiplier });
    localStorage.removeItem(EDITOR_RECOVERY_KEY);
    clearHistory();
    onUploadAfterSave(dataUrl, "png");
  }, [canvas, clearHistory, onUploadAfterSave, customWidth, canvasSize.width]);

  // Filter templates by search
  const filteredTemplates = memeSearch
    ? searchTemplates(memeTemplates, memeSearch)
    : memeTemplates;

  return (
    <div className="space-y-2 max-h-[600px] overflow-y-auto">
      {/* Recovery Prompt */}
      {showRecoveryPrompt && (
        <div className="p-3 bg-yellow-500/20 border border-yellow-500/50 rounded-lg">
          <Small className="text-yellow-400 font-mono flex items-center gap-1 mb-2">
            <RefreshIcon size={12} /> Found unsaved work from a previous session
          </Small>
          <div className="flex gap-2">
            <button
              onClick={handleRecover}
              className="flex-1 py-2 px-3 bg-yellow-500/30 text-yellow-400 rounded font-mono text-xs hover:bg-yellow-500/40"
            >
              Restore
            </button>
            <button
              onClick={handleDiscardRecovery}
              className="flex-1 py-2 px-3 bg-gray-800 text-gray-400 rounded font-mono text-xs hover:bg-gray-700"
            >
              Start Fresh
            </button>
          </div>
        </div>
      )}

      {/* Tool Bar - Compact grid layout for mobile */}
      <div className="grid grid-cols-10 gap-0.5 p-1 bg-black/50 rounded-lg">
        <ToolbarButton onClick={() => setTool("select")} isActive={tool === "select"} tooltip="Select & Move">
          <PointerIcon size={18} />
        </ToolbarButton>
        <ToolbarButton onClick={() => { setTool("draw"); setShowBrushPanel(!showBrushPanel); }} isActive={tool === "draw"} tooltip="Draw / Brush">
          <BrushIcon size={18} />
        </ToolbarButton>
        <ToolbarButton onClick={() => setTool("eraser")} isActive={tool === "eraser"} tooltip="Eraser">
          <EraserIcon size={18} />
        </ToolbarButton>
        <ToolbarButton onClick={() => { setTool("text"); setShowTextPanel(!showTextPanel); }} isActive={tool === "text"} tooltip="Add Text">
          <TypeIcon size={18} />
        </ToolbarButton>
        <ToolbarButton onClick={() => setShowEmojiPanel(!showEmojiPanel)} isActive={showEmojiPanel} tooltip="Add Emoji">
          <SmileIcon size={18} />
        </ToolbarButton>
        <ToolbarButton onClick={handleImageImport} tooltip="Import Photo">
          <CameraIcon size={18} />
        </ToolbarButton>
        <Tooltip delayDuration={300}>
          <TooltipTrigger asChild>
            <button
              onClick={() => setShowMemePanel(!showMemePanel)}
              className={`p-1.5 rounded min-h-[36px] flex items-center justify-center ${showMemePanel ? "bg-purple-500/20 text-purple-400" : "text-gray-400 active:bg-gray-800"}`}
            >
              <FrogIcon size={18} />
            </button>
          </TooltipTrigger>
          <TooltipContent side="bottom" sideOffset={4} className="bg-gray-900 text-gray-100 border border-gray-700">
            Meme Templates
          </TooltipContent>
        </Tooltip>
        <ToolbarButton onClick={deleteSelected} tooltip="Delete Selected" className="text-red-400 bg-red-500/10 active:bg-red-500/20">
          <TrashIcon size={18} />
        </ToolbarButton>
        <ToolbarButton onClick={undo} disabled={!canUndo} tooltip="Undo">
          <UndoIcon size={18} />
        </ToolbarButton>
        <ToolbarButton onClick={redo} disabled={!canRedo} tooltip="Redo">
          <RedoIcon size={18} />
        </ToolbarButton>
      </div>

      {/* Tool Bar Row 2: Alignment & Settings */}
      <div className="grid grid-cols-6 gap-0.5 p-1 bg-black/30 rounded-lg">
        <ToolbarButton2 onClick={() => setShowNudgePanel(!showNudgePanel)} isActive={showNudgePanel} tooltip="Nudge & Rotate" variant="orange">
          <CrosshairIcon size={16} />
        </ToolbarButton2>
        <ToolbarButton2 onClick={() => setShowScalePanel(!showScalePanel)} isActive={showScalePanel} tooltip="Scale Object" variant="pink">
          <ZoomIcon size={16} />
        </ToolbarButton2>
        <ToolbarButton2 onClick={() => setShowBgPanel(!showBgPanel)} isActive={showBgPanel} tooltip="Background Color" variant="yellow">
          <PaletteIcon size={16} />
        </ToolbarButton2>
        <ToolbarButton2 onClick={() => setSnapEnabled(!snapEnabled)} isActive={snapEnabled} tooltip={snapEnabled ? "Snap to Center: ON" : "Snap to Center: OFF"} variant="green">
          <MagnetIcon size={16} />
        </ToolbarButton2>
        <ToolbarButton2 onClick={() => setShowLayerPanel(!showLayerPanel)} isActive={showLayerPanel} tooltip="Layers & Align" variant="blue">
          <LayersIcon size={16} />
        </ToolbarButton2>
        <ToolbarButton2 onClick={() => setShowSizePanel(!showSizePanel)} isActive={showSizePanel} tooltip="Canvas Size" variant="cyan">
          <RulerIcon size={16} />
        </ToolbarButton2>
      </div>

      {/* Scale Panel */}
      {showScalePanel && (
        <div className="p-3 bg-black/50 rounded-lg space-y-3">
          <Small className="text-gray-400 font-mono text-[10px] uppercase">Scale Object</Small>
          {canvas?.getActiveObject() ? (
            <>
              <div>
                <div className="flex justify-between items-center mb-1">
                  <Small className="text-gray-500 font-mono text-[9px]">Size</Small>
                  <Small className="text-pink-400 font-mono text-sm font-bold">{scaleValue}%</Small>
                </div>
                <input
                  type="range"
                  min="10"
                  max="300"
                  value={scaleValue}
                  onChange={(e) => {
                    const newValue = parseInt(e.target.value);
                    setScaleValue(newValue);
                    scaleObject(newValue);
                  }}
                  className="w-full accent-pink-500"
                />
                <div className="flex justify-between text-[8px] text-gray-600 font-mono mt-1">
                  <span>10%</span>
                  <span>100%</span>
                  <span>300%</span>
                </div>
              </div>
              <div className="grid grid-cols-4 gap-1">
                <button
                  onClick={() => { setScaleValue(50); scaleObject(50); }}
                  className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700"
                >
                  50%
                </button>
                <button
                  onClick={() => { setScaleValue(100); scaleObject(100); }}
                  className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700"
                >
                  100%
                </button>
                <button
                  onClick={() => { setScaleValue(150); scaleObject(150); }}
                  className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700"
                >
                  150%
                </button>
                <button
                  onClick={() => { setScaleValue(200); scaleObject(200); }}
                  className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700"
                >
                  200%
                </button>
              </div>
              <button
                onClick={applyScale}
                className="w-full py-2 bg-pink-500/20 text-pink-400 rounded font-mono text-xs hover:bg-pink-500/30"
              >
                Done
              </button>
            </>
          ) : (
            <div className="text-center py-4">
              <Small className="text-gray-500 font-mono">Select an object first</Small>
            </div>
          )}
        </div>
      )}

      {/* Background Color Panel */}
      {showBgPanel && (
        <div className="p-3 bg-black/50 rounded-lg space-y-3">
          <Small className="text-gray-400 font-mono text-[10px] uppercase">Background Color</Small>
          <div className="grid grid-cols-3 gap-2">
            {BACKGROUND_COLORS.map((bg) => (
              <button
                key={bg.id}
                onClick={() => changeBackgroundColor(bg.color)}
                className={`py-2.5 px-2 rounded-lg text-xs font-mono flex items-center justify-center gap-1.5 transition-all ${
                  backgroundColor === bg.color
                    ? "bg-yellow-500/20 text-yellow-400 border border-yellow-500/50"
                    : "bg-gray-800 text-gray-300 hover:bg-gray-700"
                }`}
              >
                {bg.preview ? (
                  <span className="text-base">{bg.preview}</span>
                ) : (
                  <span
                    className="w-4 h-4 rounded border border-gray-600"
                    style={{ backgroundColor: bg.color || "transparent" }}
                  />
                )}
                {bg.label}
              </button>
            ))}
          </div>
          <div className="flex items-center gap-2">
            <Small className="text-gray-500 font-mono text-[9px]">Custom:</Small>
            <input
              type="color"
              value={backgroundColor || "#1a1a1a"}
              onChange={(e) => changeBackgroundColor(e.target.value)}
              className="w-8 h-8 rounded cursor-pointer border border-gray-600"
            />
            <Small className="text-gray-600 font-mono text-[9px]">{backgroundColor || "transparent"}</Small>
          </div>
          <Small className="text-gray-600 font-mono text-[9px] flex items-center gap-1">
            <LightbulbIcon size={10} className="shrink-0" /> &quot;None&quot; exports with transparent background (PNG only)
          </Small>
        </div>
      )}

      {/* Brush Panel */}
      {showBrushPanel && (
        <div className="p-3 bg-black/50 rounded-lg space-y-3">
          <Small className="text-gray-400 font-mono text-[10px] uppercase">Brush Settings</Small>

          {/* Brush Type */}
          <div className="flex gap-1">
            {(["pencil", "spray", "marker"] as const).map((type) => (
              <button
                key={type}
                onClick={() => setBrush({ ...brush, type })}
                className={`flex-1 py-1.5 px-2 rounded text-xs font-mono capitalize ${brush.type === type ? "bg-[#00ff00]/20 text-[#00ff00]" : "bg-gray-800 text-gray-400"}`}
              >
                {type}
              </button>
            ))}
          </div>

          {/* Size */}
          <div>
            <Small className="text-gray-500 font-mono text-[9px]">Size: {brush.size}px</Small>
            <input
              type="range"
              min="1"
              max="50"
              value={brush.size}
              onChange={(e) => setBrush({ ...brush, size: parseInt(e.target.value) })}
              className="w-full"
            />
          </div>

          {/* Color */}
          <div>
            <Small className="text-gray-500 font-mono text-[9px]">Color</Small>
            <div className="flex flex-wrap gap-1 mt-1">
              {PRESET_COLORS.map((color) => (
                <button
                  key={color}
                  onClick={() => setBrush({ ...brush, color })}
                  className={`w-6 h-6 rounded border-2 ${brush.color === color ? "border-white" : "border-transparent"}`}
                  style={{ backgroundColor: color }}
                />
              ))}
              <input
                type="color"
                value={brush.color}
                onChange={(e) => setBrush({ ...brush, color: e.target.value })}
                className="w-6 h-6 rounded cursor-pointer"
              />
            </div>
          </div>
        </div>
      )}

      {/* Text Panel */}
      {showTextPanel && (
        <div className="p-3 bg-black/50 rounded-lg space-y-3">
          <Small className="text-gray-400 font-mono text-[10px] uppercase">Text Settings</Small>

          {/* Font */}
          <select
            value={textSettings.fontFamily}
            onChange={(e) => setTextSettings({ ...textSettings, fontFamily: e.target.value })}
            className="w-full px-2 py-1.5 bg-gray-800 rounded text-white text-xs font-mono"
          >
            {FONT_FAMILIES.map((f) => (
              <option key={f.id} value={f.id}>{f.label}</option>
            ))}
          </select>

          {/* Size */}
          <div>
            <Small className="text-gray-500 font-mono text-[9px]">Size: {textSettings.fontSize}px</Small>
            <input
              type="range"
              min="12"
              max="120"
              value={textSettings.fontSize}
              onChange={(e) => setTextSettings({ ...textSettings, fontSize: parseInt(e.target.value) })}
              className="w-full"
            />
          </div>

          {/* Style buttons */}
          <div className="flex gap-1">
            <button
              onClick={() => setTextSettings({ ...textSettings, fontWeight: textSettings.fontWeight === "bold" ? "normal" : "bold" })}
              className={`flex-1 py-1.5 px-2 rounded text-xs font-mono ${textSettings.fontWeight === "bold" ? "bg-[#00ff00]/20 text-[#00ff00]" : "bg-gray-800 text-gray-400"}`}
            >
              <strong>B</strong>
            </button>
            <button
              onClick={() => setTextSettings({ ...textSettings, fontStyle: textSettings.fontStyle === "italic" ? "normal" : "italic" })}
              className={`flex-1 py-1.5 px-2 rounded text-xs font-mono ${textSettings.fontStyle === "italic" ? "bg-[#00ff00]/20 text-[#00ff00]" : "bg-gray-800 text-gray-400"}`}
            >
              <em>I</em>
            </button>
            <button
              onClick={() => setTextSettings({ ...textSettings, underline: !textSettings.underline })}
              className={`flex-1 py-1.5 px-2 rounded text-xs font-mono ${textSettings.underline ? "bg-[#00ff00]/20 text-[#00ff00]" : "bg-gray-800 text-gray-400"}`}
            >
              <u>U</u>
            </button>
          </div>

          {/* Colors */}
          <div className="grid grid-cols-2 gap-2">
            <div>
              <Small className="text-gray-500 font-mono text-[9px]">Fill</Small>
              <div className="flex gap-1 mt-1">
                {PRESET_COLORS.slice(0, 5).map((color) => (
                  <button
                    key={color}
                    onClick={() => setTextSettings({ ...textSettings, fill: color })}
                    className={`w-5 h-5 rounded border ${textSettings.fill === color ? "border-white" : "border-transparent"}`}
                    style={{ backgroundColor: color }}
                  />
                ))}
              </div>
            </div>
            <div>
              <Small className="text-gray-500 font-mono text-[9px]">Outline</Small>
              <div className="flex gap-1 mt-1">
                {["#000000", "#ffffff", "#ff0000", "#00ff00", "#0000ff"].map((color) => (
                  <button
                    key={color}
                    onClick={() => setTextSettings({ ...textSettings, stroke: color })}
                    className={`w-5 h-5 rounded border ${textSettings.stroke === color ? "border-white" : "border-transparent"}`}
                    style={{ backgroundColor: color }}
                  />
                ))}
              </div>
            </div>
          </div>

          {/* Outline width */}
          <div>
            <Small className="text-gray-500 font-mono text-[9px]">Outline: {textSettings.strokeWidth}px</Small>
            <input
              type="range"
              min="0"
              max="10"
              value={textSettings.strokeWidth}
              onChange={(e) => setTextSettings({ ...textSettings, strokeWidth: parseInt(e.target.value) })}
              className="w-full"
            />
          </div>

          <button
            onClick={addText}
            className="w-full py-2 bg-[#00ff00]/20 text-[#00ff00] rounded font-mono text-xs hover:bg-[#00ff00]/30"
          >
            + Add Text
          </button>
        </div>
      )}

      {/* Emoji Panel */}
      {showEmojiPanel && (
        <div className="p-3 bg-black/50 rounded-lg">
          <Small className="text-gray-400 font-mono text-[10px] uppercase mb-2 block">Add Emoji</Small>
          <div className="grid grid-cols-8 gap-1 max-h-32 overflow-y-auto">
            {EMOJI_LIST.map((emoji) => (
              <button
                key={emoji}
                onClick={() => addEmoji(emoji)}
                className="text-2xl hover:bg-gray-800 rounded p-1"
              >
                {emoji}
              </button>
            ))}
          </div>
        </div>
      )}

      {/* Layer Panel */}
      {showLayerPanel && (
        <div className="p-3 bg-black/50 rounded-lg space-y-2">
          <Small className="text-gray-400 font-mono text-[10px] uppercase">Layer Controls</Small>
          <div className="grid grid-cols-2 gap-1">
            <button onClick={bringForward} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center gap-1.5">
              <BringForwardIcon size={14} /> Forward
            </button>
            <button onClick={sendBackward} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center gap-1.5">
              <SendBackwardIcon size={14} /> Backward
            </button>
          </div>
          <Small className="text-gray-400 font-mono text-[10px] uppercase mt-2 block">Align</Small>
          <div className="grid grid-cols-3 gap-1">
            <button onClick={() => alignObject("left")} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center"><AlignLeftIcon size={14} /></button>
            <button onClick={() => alignObject("center")} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center"><AlignCenterHIcon size={14} /></button>
            <button onClick={() => alignObject("right")} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center"><AlignRightIcon size={14} /></button>
            <button onClick={() => alignObject("top")} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center"><AlignTopIcon size={14} /></button>
            <button onClick={() => alignObject("middle")} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center"><AlignCenterVIcon size={14} /></button>
            <button onClick={() => alignObject("bottom")} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center"><AlignBottomIcon size={14} /></button>
          </div>
        </div>
      )}

      {/* Nudge & Rotate Panel */}
      {showNudgePanel && (
        <div className="p-3 bg-black/50 rounded-lg space-y-2">
          <Small className="text-gray-400 font-mono text-[10px] uppercase">Nudge (1px)</Small>
          <div className="grid grid-cols-3 gap-1 w-28 mx-auto">
            <div />
            <button onClick={() => nudgeObject("up")} className="py-2 px-3 bg-gray-800 text-gray-300 rounded text-sm hover:bg-gray-700 flex items-center justify-center"><ArrowUpIcon size={16} /></button>
            <div />
            <button onClick={() => nudgeObject("left")} className="py-2 px-3 bg-gray-800 text-gray-300 rounded text-sm hover:bg-gray-700 flex items-center justify-center"><ArrowLeftIcon size={16} /></button>
            <div className="py-2 px-3 bg-gray-900 rounded text-[8px] text-gray-500 font-mono text-center flex items-center justify-center">1px</div>
            <button onClick={() => nudgeObject("right")} className="py-2 px-3 bg-gray-800 text-gray-300 rounded text-sm hover:bg-gray-700 flex items-center justify-center"><ArrowRightIcon size={16} /></button>
            <div />
            <button onClick={() => nudgeObject("down")} className="py-2 px-3 bg-gray-800 text-gray-300 rounded text-sm hover:bg-gray-700 flex items-center justify-center"><ArrowDownIcon size={16} /></button>
            <div />
          </div>
          <Small className="text-gray-400 font-mono text-[10px] uppercase mt-2 block">Nudge (10px)</Small>
          <div className="grid grid-cols-4 gap-1">
            <button onClick={() => nudgeObject("left", 10)} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center gap-1"><ArrowLeftIcon size={12} /> 10</button>
            <button onClick={() => nudgeObject("up", 10)} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center gap-1"><ArrowUpIcon size={12} /> 10</button>
            <button onClick={() => nudgeObject("down", 10)} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center gap-1"><ArrowDownIcon size={12} /> 10</button>
            <button onClick={() => nudgeObject("right", 10)} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center gap-1"><ArrowRightIcon size={12} /> 10</button>
          </div>
          <Small className="text-gray-400 font-mono text-[10px] uppercase mt-2 block">Rotate</Small>
          <div className="grid grid-cols-4 gap-1">
            <button onClick={() => rotateObject(-1)} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center gap-1"><RotateCcwIcon size={12} /> 1°</button>
            <button onClick={() => rotateObject(-15)} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center gap-1"><RotateCcwIcon size={12} /> 15°</button>
            <button onClick={() => rotateObject(15)} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center gap-1"><RotateCwIcon size={12} /> 15°</button>
            <button onClick={() => rotateObject(1)} className="py-1.5 px-2 bg-gray-800 text-gray-300 rounded text-xs font-mono hover:bg-gray-700 flex items-center justify-center gap-1"><RotateCwIcon size={12} /> 1°</button>
          </div>
          <button onClick={() => rotateObject(-((canvas?.getActiveObject()?.angle || 0)))} className="w-full py-1.5 bg-orange-500/20 text-orange-400 rounded text-xs font-mono hover:bg-orange-500/30 mt-1 flex items-center justify-center gap-1">
            <RefreshIcon size={12} /> Reset Rotation
          </button>
        </div>
      )}

      {/* Size Panel */}
      {showSizePanel && (
        <div className="p-3 bg-black/50 rounded-lg space-y-3">
          <Small className="text-gray-400 font-mono text-[10px] uppercase">Canvas Size</Small>
          <div className="grid grid-cols-4 gap-1">
            {CANVAS_PRESETS.slice(0, -1).map((preset) => (
              <button
                key={preset.id}
                onClick={() => handleResize(preset)}
                className={`py-2 px-1 rounded text-center ${selectedPreset === preset.id ? "bg-cyan-500/20 text-cyan-400 border border-cyan-500/50" : "bg-gray-800 text-gray-400"}`}
              >
                <span className="text-sm block">{preset.emoji}</span>
                <Small className="font-mono text-[8px]">{preset.label}</Small>
              </button>
            ))}
          </div>
          <div className="flex gap-2 items-end">
            <div className="flex-1">
              <Small className="text-gray-500 font-mono text-[9px]">Width</Small>
              <input
                type="number"
                value={customWidth}
                onChange={(e) => setCustomWidth(e.target.value)}
                className="w-full px-2 py-1.5 bg-gray-800 rounded text-white text-xs font-mono"
                placeholder="1080"
              />
            </div>
            <span className="text-gray-500 pb-1.5">×</span>
            <div className="flex-1">
              <Small className="text-gray-500 font-mono text-[9px]">Height</Small>
              <input
                type="number"
                value={customHeight}
                onChange={(e) => setCustomHeight(e.target.value)}
                className="w-full px-2 py-1.5 bg-gray-800 rounded text-white text-xs font-mono"
                placeholder="1080"
              />
            </div>
            <button
              onClick={applyCustomSize}
              className="px-3 py-1.5 bg-cyan-500/20 text-cyan-400 rounded text-xs font-mono hover:bg-cyan-500/30"
            >
              Apply
            </button>
          </div>
          <Small className="text-gray-600 font-mono text-[9px] block">
            Current: {canvasSize.width} × {canvasSize.height}px
          </Small>
        </div>
      )}

      {/* Meme Template Modal - Full screen overlay for easier browsing */}
      {showMemePanel && (
        <div className="fixed inset-0 z-50 bg-black/95 flex flex-col">
          {/* Header */}
          <div className="flex items-center justify-between p-4 border-b border-purple-500/30">
            <div className="flex items-center gap-2">
              <FrogIcon size={20} className="text-purple-400" />
              <span className="text-purple-400 font-mono font-bold">Meme Library</span>
            </div>
            <button
              onClick={() => setShowMemePanel(false)}
              className="w-8 h-8 flex items-center justify-center text-gray-400 hover:text-white bg-gray-800 rounded-full transition-colors"
            >
              <span className="text-lg">&times;</span>
            </button>
          </div>

          {/* Search */}
          <div className="p-3">
            <input
              type="text"
              value={memeSearch}
              onChange={(e) => setMemeSearch(e.target.value)}
              placeholder="Search memes..."
              className="w-full px-4 py-3 bg-gray-900 border border-purple-500/30 rounded-lg text-white font-mono focus:outline-none focus:border-purple-500"
              autoFocus
            />
          </div>

          {/* Meme Grid - scrollable */}
          <div className="flex-1 overflow-y-auto p-3">
            {isLoadingTemplates ? (
              <div className="flex items-center justify-center h-32">
                <Small className="text-gray-500">Loading templates...</Small>
              </div>
            ) : filteredTemplates.length === 0 ? (
              <div className="flex items-center justify-center h-32">
                <Small className="text-gray-500">No templates found</Small>
              </div>
            ) : (
              <div className="grid grid-cols-2 gap-3">
                {filteredTemplates.slice(0, 50).map((template) => (
                  <button
                    key={template.id}
                    onClick={() => {
                      loadMemeTemplate(template);
                      setShowMemePanel(false);
                    }}
                    className="bg-gray-900 rounded-lg overflow-hidden border border-gray-800 hover:border-purple-500 transition-all active:scale-95"
                  >
                    <img
                      src={getMemeTemplateUrl(template.id)}
                      alt={template.name}
                      className="w-full aspect-square object-cover"
                      loading="lazy"
                    />
                    <div className="px-3 py-2 bg-black">
                      <Small className="text-gray-300 text-xs font-mono truncate block">{template.name}</Small>
                    </div>
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Footer */}
          <div className="p-3 border-t border-gray-800">
            <button
              onClick={() => setShowMemePanel(false)}
              className="w-full py-3 bg-gray-800 text-gray-300 rounded-lg font-mono text-sm hover:bg-gray-700 transition-colors"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      {/* Canvas Container */}
      <div
        ref={containerRef}
        className="relative bg-[#0d0d0d] rounded-lg overflow-auto border border-[#00ff00]/20 flex items-center justify-center p-2"
        style={{ maxHeight: 400 }}
      >
        {/* Checkerboard pattern shown when background is transparent */}
        <div
          className="relative"
          style={backgroundColor === null ? {
            backgroundImage: `
              linear-gradient(45deg, #333 25%, transparent 25%),
              linear-gradient(-45deg, #333 25%, transparent 25%),
              linear-gradient(45deg, transparent 75%, #333 75%),
              linear-gradient(-45deg, transparent 75%, #333 75%)
            `,
            backgroundSize: "20px 20px",
            backgroundPosition: "0 0, 0 10px, 10px -10px, -10px 0px",
            backgroundColor: "#222",
          } : undefined}
        >
          <canvas ref={canvasRef} />
        </div>
      </div>

      {/* Action Buttons - Two clear options */}
      <div className="flex gap-2">
        <button
          onClick={() => { setShowSavePanel(!showSavePanel); setShowExportPanel(false); }}
          className={`flex-1 py-3 rounded-lg font-mono text-sm transition-colors ${
            showSavePanel
              ? "bg-gray-700 text-white"
              : "bg-gray-800 text-gray-300 hover:bg-gray-700"
          }`}
        >
          Save to Device
        </button>
        {onUploadAfterSave && (
          <button
            onClick={handleDirectUpload}
            className="flex-1 py-3 bg-[#00ff00] text-black rounded-lg font-mono text-sm font-bold hover:bg-[#00ff00]/90 transition-colors"
          >
            Upload to Net
          </button>
        )}
      </div>

      {/* Save Panel - Shows after clicking "Save to Device" */}
      {showSavePanel && (
        <div className="p-3 bg-black/50 rounded-lg space-y-3">
          <button
            onClick={saveToPhotos}
            className="w-full py-3 bg-[#00ff00]/20 text-[#00ff00] rounded-lg font-mono text-sm hover:bg-[#00ff00]/30 transition-colors flex items-center justify-center gap-2"
          >
            <SaveIcon size={16} /> Save to Photos
          </button>
          <div className="border-t border-gray-700 pt-3">
            <Small className="text-gray-400 font-mono text-[10px] uppercase block mb-2">Save Image As</Small>
            <div className="grid grid-cols-3 gap-2">
              {(["png", "jpeg", "webp"] as const).map((format) => (
                <button
                  key={format}
                  onClick={() => saveImageAs(format)}
                  className="py-2.5 px-3 bg-gray-800 text-gray-300 rounded-lg font-mono text-xs hover:bg-gray-700 uppercase transition-colors"
                >
                  .{format}
                </button>
              ))}
            </div>
            <Small className="text-gray-500 font-mono text-[9px] block mt-2">
              Opens in browser to download
            </Small>
          </div>
        </div>
      )}

      {/* Upload After Save Prompt */}
      {showUploadPrompt && onUploadAfterSave && (
        <div className="p-4 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg space-y-3">
          <div className="flex items-start gap-3">
            <CheckCircleIcon size={24} className="text-[#00ff00] shrink-0" />
            <div className="flex-1">
              <Small className="text-[#00ff00] font-mono font-semibold block">
                Saved to Camera Roll!
              </Small>
              <Small className="text-gray-400 font-mono text-[10px] mt-1 block">
                Want to share your creation with the Net Library community?
              </Small>
            </div>
          </div>
          <div className="flex gap-2">
            <button
              onClick={handleUploadAfterSave}
              className="flex-1 py-2.5 bg-[#00ff00]/20 text-[#00ff00] rounded-lg font-mono text-sm hover:bg-[#00ff00]/30 transition-colors flex items-center justify-center gap-2"
            >
              <UploadIcon size={16} />
              <span>Upload to Library</span>
            </button>
            <button
              onClick={dismissUploadPrompt}
              className="px-4 py-2.5 bg-gray-800 text-gray-400 rounded-lg font-mono text-sm hover:bg-gray-700 transition-colors"
            >
              Skip
            </button>
          </div>
        </div>
      )}

      {/* Cancel */}
      <button
        onClick={onCancel}
        className="w-full py-2 text-gray-500 font-mono text-xs hover:text-gray-400"
      >
        Cancel
      </button>
    </div>
  );
}
src/features/app/components/image-editor/index.ts
export { ImageEditor } from "./image-editor";
export * from "./types";
src/features/app/components/image-editor/meme-templates.ts
// Memegen.link API integration
import type { MemeTemplate } from "./types";

const MEMEGEN_API = "https://api.memegen.link";

// Popular meme templates (curated list for quick access)
export const POPULAR_TEMPLATES: MemeTemplate[] = [
  { id: "drake", name: "Drake Hotline Bling", url: "", width: 1200, height: 1200 },
  { id: "doge", name: "Doge", url: "", width: 620, height: 479 },
  { id: "success", name: "Success Kid", url: "", width: 500, height: 500 },
  { id: "afraid", name: "Afraid To Ask Andy", url: "", width: 600, height: 635 },
  { id: "bad", name: "Bad Luck Brian", url: "", width: 300, height: 375 },
  { id: "alien", name: "Ancient Aliens", url: "", width: 500, height: 437 },
  { id: "buzz", name: "Buzz Lightyear", url: "", width: 500, height: 400 },
  { id: "pigeon", name: "Is This A Pigeon", url: "", width: 1280, height: 720 },
  { id: "rollsafe", name: "Roll Safe", url: "", width: 702, height: 395 },
  { id: "woman-cat", name: "Woman Yelling at Cat", url: "", width: 680, height: 440 },
  { id: "fine", name: "This Is Fine", url: "", width: 580, height: 282 },
  { id: "always", name: "Always Has Been", url: "", width: 1125, height: 1394 },
];

// Fetch all available templates from memegen.link
export async function fetchMemeTemplates(): Promise<MemeTemplate[]> {
  try {
    const response = await fetch(`${MEMEGEN_API}/templates`);
    if (!response.ok) throw new Error("Failed to fetch templates");

    const data = await response.json();

    return data.map((template: { id: string; name: string; blank: string; example: { width: number; height: number } }) => ({
      id: template.id,
      name: template.name,
      url: template.blank,
      width: template.example?.width || 800,
      height: template.example?.height || 600,
    }));
  } catch (error) {
    console.error("Error fetching meme templates:", error);
    return POPULAR_TEMPLATES;
  }
}

// Get the blank template URL for a specific meme
export function getMemeTemplateUrl(templateId: string): string {
  return `${MEMEGEN_API}/images/${templateId}.png`;
}

// Search templates by name
export function searchTemplates(templates: MemeTemplate[], query: string): MemeTemplate[] {
  const lowerQuery = query.toLowerCase();
  return templates.filter(t =>
    t.name.toLowerCase().includes(lowerQuery) ||
    t.id.toLowerCase().includes(lowerQuery)
  );
}
src/features/app/components/image-editor/types.ts
// Image Editor Types

export type CanvasPreset = {
  id: string;
  label: string;
  width: number;
  height: number;
  emoji: string;
};

export const CANVAS_PRESETS: CanvasPreset[] = [
  { id: "square", label: "Square", width: 1080, height: 1080, emoji: "⬜" },
  { id: "portrait", label: "Portrait", width: 1080, height: 1350, emoji: "📱" },
  { id: "landscape", label: "Landscape", width: 1920, height: 1080, emoji: "🖼️" },
  { id: "story", label: "Story", width: 1080, height: 1920, emoji: "📲" },
  { id: "twitter", label: "Twitter", width: 1200, height: 675, emoji: "🐦" },
  { id: "facebook", label: "Facebook", width: 1200, height: 630, emoji: "📘" },
  { id: "custom", label: "Custom", width: 0, height: 0, emoji: "✏️" },
];

export type BrushType = "pencil" | "spray" | "marker" | "eraser";

export interface BrushSettings {
  type: BrushType;
  color: string;
  size: number;
  opacity: number;
}

export interface TextSettings {
  fontFamily: string;
  fontSize: number;
  fill: string;
  fontWeight: "normal" | "bold";
  fontStyle: "normal" | "italic";
  underline: boolean;
  stroke: string;
  strokeWidth: number;
  textAlign: "left" | "center" | "right";
}

export const FONT_FAMILIES = [
  { id: "Arial", label: "Arial" },
  { id: "Impact", label: "Impact" },
  { id: "Comic Sans MS", label: "Comic Sans" },
  { id: "Georgia", label: "Georgia" },
  { id: "Times New Roman", label: "Times" },
  { id: "Courier New", label: "Courier" },
  { id: "Verdana", label: "Verdana" },
  { id: "monospace", label: "Mono" },
];

export const PRESET_COLORS = [
  "#ffffff", "#000000", "#ff0000", "#00ff00", "#0000ff",
  "#ffff00", "#ff00ff", "#00ffff", "#ff6600", "#9900ff",
  "#ff69b4", "#808080", "#8b4513", "#006400",
];

export type EditorTool = "select" | "draw" | "text" | "eraser" | "emoji";

export interface EditorState {
  tool: EditorTool;
  brush: BrushSettings;
  text: TextSettings;
  canvasSize: { width: number; height: number };
  zoom: number;
}

export interface HistoryEntry {
  json: string;
  timestamp: number;
}

export interface MemeTemplate {
  id: string;
  name: string;
  url: string;
  width: number;
  height: number;
}

export interface EditorRecoveryData {
  canvasJson: string;
  canvasSize: { width: number; height: number };
  savedAt: number;
}

// Local storage keys
export const EDITOR_RECOVERY_KEY = "net-library-image-editor-recovery";
export const EDITOR_AUTOSAVE_INTERVAL = 30000; // 30 seconds
src/features/app/components/image-editor/use-canvas-history.ts
"use client";

import { useState, useCallback, useRef } from "react";
import type { Canvas } from "fabric";
import type { HistoryEntry } from "./types";

const MAX_HISTORY = 20;

export function useCanvasHistory(canvas: Canvas | null) {
  const [history, setHistory] = useState<HistoryEntry[]>([]);
  const [historyIndex, setHistoryIndex] = useState(-1);
  const isUndoRedoRef = useRef(false);

  // Use ref to track current index to avoid stale closure issues
  const historyIndexRef = useRef(historyIndex);
  historyIndexRef.current = historyIndex;

  // Save current state to history
  const saveState = useCallback(() => {
    if (!canvas || isUndoRedoRef.current) return;

    const json = JSON.stringify(canvas.toJSON());
    const entry: HistoryEntry = {
      json,
      timestamp: Date.now(),
    };

    // Use ref for current index to avoid stale closure
    const currentIndex = historyIndexRef.current;

    setHistory((prev) => {
      // Remove any future states if we're not at the end
      const newHistory = prev.slice(0, currentIndex + 1);
      newHistory.push(entry);

      // Limit history size
      if (newHistory.length > MAX_HISTORY) {
        newHistory.shift();
        return newHistory;
      }

      return newHistory;
    });

    // Update index after history is set
    setHistoryIndex((prev) => {
      const newIndex = Math.min(prev + 1, MAX_HISTORY - 1);
      return newIndex;
    });
  }, [canvas]);

  // Undo
  const undo = useCallback(() => {
    if (!canvas || historyIndex <= 0) return;

    isUndoRedoRef.current = true;
    const newIndex = historyIndex - 1;
    const entry = history[newIndex];

    if (entry) {
      canvas.loadFromJSON(JSON.parse(entry.json)).then(() => {
        canvas.renderAll();
        setHistoryIndex(newIndex);
        isUndoRedoRef.current = false;
      });
    }
  }, [canvas, history, historyIndex]);

  // Redo
  const redo = useCallback(() => {
    if (!canvas || historyIndex >= history.length - 1) return;

    isUndoRedoRef.current = true;
    const newIndex = historyIndex + 1;
    const entry = history[newIndex];

    if (entry) {
      canvas.loadFromJSON(JSON.parse(entry.json)).then(() => {
        canvas.renderAll();
        setHistoryIndex(newIndex);
        isUndoRedoRef.current = false;
      });
    }
  }, [canvas, history, historyIndex]);

  // Clear history
  const clearHistory = useCallback(() => {
    setHistory([]);
    setHistoryIndex(-1);
  }, []);

  // Initialize with current state
  const initHistory = useCallback(() => {
    if (!canvas) return;
    const json = JSON.stringify(canvas.toJSON());
    setHistory([{ json, timestamp: Date.now() }]);
    setHistoryIndex(0);
  }, [canvas]);

  return {
    saveState,
    undo,
    redo,
    clearHistory,
    initHistory,
    canUndo: historyIndex > 0,
    canRedo: historyIndex < history.length - 1,
    historyLength: history.length,
  };
}
src/features/app/components/leaderboard-tab.tsx
"use client";

import { useState, useEffect, useRef } from "react";
import { createPortal } from "react-dom";
import { Card, CardContent, P, Small, H4 } from "@neynar/ui";
import { useLeaderboard } from "@/hooks/use-leaderboard";
import { useDiscoveryContext } from "@/contexts/discovery-context";
import { generateScoreKey } from "@/hooks/use-upvotes";
import { UpvoteButton } from "@/features/app/components/upvote-button";
import { UserLibraryCardModal } from "@/features/app/components/user-library-card-modal";
import type { Category } from "@/features/app/types";
import type { MemberEntry, SignupPlatform } from "@/lib/net-protocol";
import { openInExternalBrowser } from "@/lib/app-mode";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { ChartIcon, SettingsIcon, LibraryIcon, WarningIcon, RefreshIcon, DocumentIcon, MonitorIcon, UserIcon, FolderIcon, ChevronUpIcon, GridIcon, BrowserIcon, ExportIcon, FarcasterIcon, BaseIcon, WebIcon, PaletteIcon } from "@/components/icons/net-library-icons";

// Tech Document Modal Component
function TechDocumentModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
  // Scroll iframe to top when modal opens
  const handleIframeLoad = (e: React.SyntheticEvent<HTMLIFrameElement>) => {
    const iframe = e.currentTarget;
    if (iframe.contentWindow) {
      iframe.contentWindow.scrollTo(0, 0);
    }
  };

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
      return () => {
        document.body.style.overflow = '';
      };
    }
  }, [isOpen]);

  if (!isOpen) return null;

  const modalContent = (
    <div className="fixed inset-0 bg-black z-[9999] flex flex-col" style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0 }}>
      {/* Fixed Close Button - Always visible top right */}
      <button
        onClick={onClose}
        className="fixed top-3 right-3 z-[10000] w-10 h-10 rounded-full bg-black/80 border-2 border-[#00ff00]/50 flex items-center justify-center text-white hover:bg-[#00ff00]/20 hover:border-[#00ff00] transition-colors shadow-lg"
        style={{ position: 'fixed' }}
      >
        ✕
      </button>

      {/* Document Content - Full screen iframe */}
      <iframe
        src="/net-library-overview.html"
        className="w-full h-full border-0"
        title="Net Library Overview Document"
        onLoad={handleIframeLoad}
        style={{ flex: 1 }}
      />
    </div>
  );

  // Render via portal to escape any parent overflow/z-index constraints
  if (typeof document !== 'undefined') {
    return createPortal(modalContent, document.body);
  }
  return modalContent;
}

// Specs Document Modal Component
function SpecsDocumentModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
  // Scroll iframe to top when modal opens
  const handleIframeLoad = (e: React.SyntheticEvent<HTMLIFrameElement>) => {
    const iframe = e.currentTarget;
    if (iframe.contentWindow) {
      iframe.contentWindow.scrollTo(0, 0);
    }
  };

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
      return () => {
        document.body.style.overflow = '';
      };
    }
  }, [isOpen]);

  if (!isOpen) return null;

  const modalContent = (
    <div className="fixed inset-0 bg-black z-[9999] flex flex-col" style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0 }}>
      {/* Fixed Close Button - Always visible top right */}
      <button
        onClick={onClose}
        className="fixed top-3 right-3 z-[10000] w-10 h-10 rounded-full bg-black/80 border-2 border-[#00ff00]/50 flex items-center justify-center text-white hover:bg-[#00ff00]/20 hover:border-[#00ff00] transition-colors shadow-lg"
        style={{ position: 'fixed' }}
      >
        ✕
      </button>

      {/* Document Content - Full screen iframe */}
      <iframe
        src="/net-library-specs.html"
        className="w-full h-full border-0"
        title="Net Library Technical Specs"
        onLoad={handleIframeLoad}
        style={{ flex: 1 }}
      />
    </div>
  );

  // Render via portal to escape any parent overflow/z-index constraints
  if (typeof document !== 'undefined') {
    return createPortal(modalContent, document.body);
  }
  return modalContent;
}

// Code Docs Modal Component
function DocsModal({ isOpen, onClose, isMember, isAdmin }: { isOpen: boolean; onClose: () => void; isMember: boolean; isAdmin: boolean }) {
  // Expose a global function for the iframe to call for downloads
  useEffect(() => {
    if (!isOpen) return;

    // Expose the function globally so iframe can call it
    (window as Window & { __netLibraryOpenExternal?: (url: string) => Promise<void> }).__netLibraryOpenExternal = openInExternalBrowser;

    return () => {
      // Clean up
      delete (window as Window & { __netLibraryOpenExternal?: (url: string) => Promise<void> }).__netLibraryOpenExternal;
    };
  }, [isOpen]);

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
      return () => {
        document.body.style.overflow = '';
      };
    }
  }, [isOpen]);

  const iframeRef = useRef<HTMLIFrameElement>(null);

  // Re-send membership status whenever isAdmin or isMember resolves (async FID fetch)
  useEffect(() => {
    if (!isOpen) return;
    const iframe = iframeRef.current;
    if (iframe?.contentWindow) {
      iframe.contentWindow.postMessage({ type: "membershipStatus", isMember, isAdmin }, "*");
    }
  }, [isOpen, isMember, isAdmin]);

  // Send membership status and scroll to top when iframe finishes loading
  const handleIframeLoad = (e: React.SyntheticEvent<HTMLIFrameElement>) => {
    const iframe = e.currentTarget;
    if (iframe.contentWindow) {
      iframe.contentWindow.scrollTo(0, 0);
      iframe.contentWindow.postMessage({ type: "membershipStatus", isMember, isAdmin }, "*");
    }
  };

  if (!isOpen) return null;

  const modalContent = (
    <div className="fixed inset-0 bg-black z-[9999] flex flex-col" style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0 }}>
      {/* Fixed Close Button - Always visible top right */}
      <button
        onClick={onClose}
        className="fixed top-3 right-3 z-[10000] w-10 h-10 rounded-full bg-black/80 border-2 border-[#00ff00]/50 flex items-center justify-center text-white hover:bg-[#00ff00]/20 hover:border-[#00ff00] transition-colors shadow-lg"
        style={{ position: 'fixed' }}
      >
        ✕
      </button>

      {/* Document Content - Full screen iframe */}
      <iframe
        ref={iframeRef}
        src="/net-library-docs.html"
        className="w-full h-full border-0"
        title="Net Library Code Documentation"
        onLoad={handleIframeLoad}
        style={{ flex: 1 }}
      />
    </div>
  );

  // Render via portal to escape any parent overflow/z-index constraints
  if (typeof document !== 'undefined') {
    return createPortal(modalContent, document.body);
  }
  return modalContent;
}

// Brand Kit Modal Component
function BrandKitModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
  // Scroll iframe to top when modal opens
  const handleIframeLoad = (e: React.SyntheticEvent<HTMLIFrameElement>) => {
    const iframe = e.currentTarget;
    if (iframe.contentWindow) {
      iframe.contentWindow.scrollTo(0, 0);
    }
  };

  // Prevent body scroll when modal is open
  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = 'hidden';
      return () => {
        document.body.style.overflow = '';
      };
    }
  }, [isOpen]);

  if (!isOpen) return null;

  const modalContent = (
    <div className="fixed inset-0 bg-black z-[9999] flex flex-col" style={{ position: 'fixed', top: 0, left: 0, right: 0, bottom: 0 }}>
      {/* Fixed Close Button - Always visible top right */}
      <button
        onClick={onClose}
        className="fixed top-3 right-3 z-[10000] w-10 h-10 rounded-full bg-black/80 border-2 border-[#00ff00]/50 flex items-center justify-center text-white hover:bg-[#00ff00]/20 hover:border-[#00ff00] transition-colors shadow-lg"
        style={{ position: 'fixed' }}
      >
        ✕
      </button>

      {/* Document Content - Full screen iframe */}
      <iframe
        src="/net-library-brand-kit.html"
        className="w-full h-full border-0"
        title="Net Library Brand Kit"
        onLoad={handleIframeLoad}
        style={{ flex: 1 }}
      />
    </div>
  );

  // Render via portal to escape any parent overflow/z-index constraints
  if (typeof document !== 'undefined') {
    return createPortal(modalContent, document.body);
  }
  return modalContent;
}

// Admin Stats Modal — only visible to FID 282520
function AdminStatsModal({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
  const [stats, setStats] = useState<{
    totals?: {
      allEntries: number;
      publicEntries: number;
      hiddenEntries: number;
      totalBytes: number;
      publicBytes: number;
      hiddenBytes: number;
    };
    byUploader?: {
      address: string;
      allUploads: number;
      publicUploads: number;
      hiddenUploads: number;
      allBytes: number;
      firstUploadAt: number;
      lastUploadAt: number;
    }[];
    hiddenEntries?: {
      contentKey: string;
      title: string;
      author: string;
      uploaderAddress?: string;
      operator: string;
      uploadedAt: number;
      fileSize: number;
      hiddenAt?: number;
      hiddenReason?: string;
    }[];
  } | null>(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [activeSection, setActiveSection] = useState<"totals" | "uploaders" | "hidden">("totals");

  useEffect(() => {
    if (!isOpen) return;
    setIsLoading(true);
    setError(null);
    fetch("/api/admin/stats", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      // FID verified server-side — no secret ever sent to the browser
      body: JSON.stringify({ fid: 282520 }),
    })
      .then(r => r.json())
      .then(data => { setStats(data); setIsLoading(false); })
      .catch(() => { setError("Failed to load admin stats."); setIsLoading(false); });
  }, [isOpen]);

  useEffect(() => {
    if (isOpen) {
      document.body.style.overflow = "hidden";
      return () => { document.body.style.overflow = ""; };
    }
  }, [isOpen]);

  if (!isOpen) return null;

  const fmt = (bytes: number) => {
    if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
    if (bytes >= 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${bytes} B`;
  };
  const fmtDate = (ts: number) => ts ? new Date(ts).toLocaleDateString() : "—";

  const modalContent = (
    <div
      className="fixed inset-0 bg-black/90 z-[9999] flex flex-col"
      style={{ position: "fixed", top: 0, left: 0, right: 0, bottom: 0 }}
    >
      {/* Header */}
      <div className="shrink-0 flex items-center justify-between px-4 py-3 border-b border-[#00ff00]/30 bg-black">
        <div>
          <P className="text-[#00ff00] font-mono font-bold text-sm tracking-widest">ADMIN STATS</P>
          <Small className="text-gray-500 font-mono text-[10px]">Full library — including hidden</Small>
        </div>
        <button
          onClick={onClose}
          className="w-9 h-9 rounded-full bg-[#1a1a1a] border border-[#00ff00]/30 flex items-center justify-center text-white hover:bg-[#00ff00]/10 transition-colors"
        >
          ✕
        </button>
      </div>

      {/* Section tabs */}
      <div className="shrink-0 flex border-b border-[#00ff00]/20 bg-black">
        {(["totals", "uploaders", "hidden"] as const).map(tab => (
          <button
            key={tab}
            onClick={() => setActiveSection(tab)}
            className={`flex-1 py-2 font-mono text-xs font-bold uppercase tracking-wider transition-colors ${
              activeSection === tab
                ? "text-[#00ff00] border-b-2 border-[#00ff00]"
                : "text-gray-500 hover:text-gray-300"
            }`}
          >
            {tab === "totals" ? "Totals" : tab === "uploaders" ? "By Uploader" : `Hidden (${stats?.totals?.hiddenEntries ?? "…"})`}
          </button>
        ))}
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto p-4 bg-black">
        {isLoading && (
          <div className="flex items-center justify-center h-40">
            <Small className="text-[#00ff00] font-mono animate-pulse">Loading…</Small>
          </div>
        )}
        {error && (
          <div className="p-3 rounded bg-red-500/10 border border-red-500/30">
            <Small className="text-red-400 font-mono">{error}</Small>
          </div>
        )}

        {stats && activeSection === "totals" && stats.totals && (
          <div className="space-y-3">
            {/* Items */}
            <div className="rounded-lg border border-[#00ff00]/20 overflow-hidden">
              <div className="px-3 py-2 bg-[#00ff00]/5 border-b border-[#00ff00]/20">
                <Small className="text-[#00ff00] font-mono font-bold text-[10px] uppercase tracking-wider">Items</Small>
              </div>
              <div className="grid grid-cols-3 divide-x divide-[#00ff00]/10">
                {[
                  { label: "All", value: stats.totals.allEntries },
                  { label: "Public", value: stats.totals.publicEntries },
                  { label: "Hidden", value: stats.totals.hiddenEntries },
                ].map(({ label, value }) => (
                  <div key={label} className="flex flex-col items-center py-3">
                    <P className="text-xl font-bold text-[#00ff00] font-mono">{value}</P>
                    <Small className="text-gray-400 font-mono text-[10px]">{label}</Small>
                  </div>
                ))}
              </div>
            </div>

            {/* Bytes */}
            <div className="rounded-lg border border-[#00ff00]/20 overflow-hidden">
              <div className="px-3 py-2 bg-[#00ff00]/5 border-b border-[#00ff00]/20">
                <Small className="text-[#00ff00] font-mono font-bold text-[10px] uppercase tracking-wider">Storage</Small>
              </div>
              <div className="grid grid-cols-3 divide-x divide-[#00ff00]/10">
                {[
                  { label: "All", value: fmt(stats.totals.totalBytes) },
                  { label: "Public", value: fmt(stats.totals.publicBytes) },
                  { label: "Hidden", value: fmt(stats.totals.hiddenBytes) },
                ].map(({ label, value }) => (
                  <div key={label} className="flex flex-col items-center py-3">
                    <P className="text-lg font-bold text-[#00ff00] font-mono">{value}</P>
                    <Small className="text-gray-400 font-mono text-[10px]">{label}</Small>
                  </div>
                ))}
              </div>
            </div>
          </div>
        )}

        {stats && activeSection === "uploaders" && stats.byUploader && (
          <div className="space-y-2">
            {stats.byUploader.map((u, i) => (
              <div key={u.address} className="rounded-lg border border-[#00ff00]/20 p-3 bg-[#0a0a0a]">
                <div className="flex items-center gap-2 mb-2">
                  <span className="text-[#00ff00]/50 font-mono text-xs">#{i + 1}</span>
                  <Small className="text-gray-300 font-mono text-[10px] break-all">{u.address}</Small>
                </div>
                <div className="grid grid-cols-3 gap-2 mb-1">
                  {[
                    { label: "All", value: u.allUploads, color: "text-[#00ff00]" },
                    { label: "Public", value: u.publicUploads, color: "text-white" },
                    { label: "Hidden", value: u.hiddenUploads, color: u.hiddenUploads > 0 ? "text-yellow-400" : "text-gray-600" },
                  ].map(({ label, value, color }) => (
                    <div key={label} className="text-center">
                      <P className={`text-base font-bold font-mono ${color}`}>{value}</P>
                      <Small className="text-gray-500 font-mono text-[9px]">{label}</Small>
                    </div>
                  ))}
                </div>
                <div className="flex justify-between mt-1">
                  <Small className="text-gray-600 font-mono text-[9px]">{fmt(u.allBytes)}</Small>
                  <Small className="text-gray-600 font-mono text-[9px]">
                    {fmtDate(u.firstUploadAt)} – {fmtDate(u.lastUploadAt)}
                  </Small>
                </div>
              </div>
            ))}
          </div>
        )}

        {stats && activeSection === "hidden" && (
          stats.hiddenEntries && stats.hiddenEntries.length > 0 ? (
            <div className="space-y-2">
              {stats.hiddenEntries.map(e => (
                <div key={e.contentKey} className="rounded-lg border border-yellow-500/20 p-3 bg-[#0a0a0a]">
                  <P className="text-white font-mono text-xs font-bold mb-0.5 truncate">{e.title}</P>
                  <Small className="text-gray-400 font-mono text-[10px] block mb-1">{e.author}</Small>
                  <div className="flex flex-wrap gap-x-3 gap-y-0.5">
                    <Small className="text-gray-600 font-mono text-[9px]">size: {fmt(e.fileSize || 0)}</Small>
                    <Small className="text-gray-600 font-mono text-[9px]">uploaded: {fmtDate(e.uploadedAt)}</Small>
                    {e.hiddenAt && <Small className="text-yellow-500/70 font-mono text-[9px]">hidden: {fmtDate(e.hiddenAt)}</Small>}
                    {e.hiddenReason && <Small className="text-yellow-500/70 font-mono text-[9px]">reason: {e.hiddenReason}</Small>}
                  </div>
                  <Small className="text-gray-700 font-mono text-[9px] break-all mt-1 block">
                    {e.uploaderAddress || e.operator}
                  </Small>
                </div>
              ))}
            </div>
          ) : (
            <div className="flex items-center justify-center h-40">
              <Small className="text-gray-600 font-mono">No hidden entries</Small>
            </div>
          )
        )}
      </div>
    </div>
  );

  if (typeof document !== "undefined") {
    return createPortal(modalContent, document.body);
  }
  return modalContent;
}

interface LeaderboardTabProps {
  categories?: Category[]; // No longer used but kept for API compatibility
}

// Format bytes for display
function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}

// Shorten address for display
function shortenAddress(address: string): string {
  return `${address.slice(0, 6)}...${address.slice(-4)}`;
}

// Format date
function _formatDate(timestamp: number): string {
  return new Date(timestamp).toLocaleDateString("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
  });
}

type TabType = "uploaders" | "stacks" | "grids" | "books" | "upvoters";

// Type for user click in leaderboard
type LeaderboardUserInfo = { address: string; username?: string; pfpUrl?: string };

// Type for member data from registry
type MemberData = MemberEntry & { pfpUrl?: string };

// Platform verification badge component
// Takes optional resolvedFid for cases where membership doesn't have FID but user does
function PlatformBadges({ member, resolvedFid }: { member: MemberData | null; resolvedFid?: number }) {
  if (!member || member.memberId === 0) return null;

  // Farcaster verified = has FID in membership OR resolved via Neynar
  const isFarcasterVerified = !!member.fid || !!resolvedFid;
  // Base verified = has primary address or linked addresses
  const isBaseVerified = !!member.address || (member.linkedAddresses && member.linkedAddresses.length > 0);
  // Web verified = has WID (web identity) in membership
  const isWebVerified = !!(member as MemberData & { wid?: string }).wid || isBaseVerified;

  return (
    <div className="flex items-center gap-1" title={`Farcaster: ${isFarcasterVerified ? 'Verified' : 'Not linked'} | Base: ${isBaseVerified ? 'Verified' : 'Not linked'} | Web: ${isWebVerified ? 'Verified' : 'Not linked'}`}>
      <FarcasterIcon size={10} className={isFarcasterVerified ? "text-purple-400" : "text-purple-400/30"} />
      <BaseIcon size={10} className={isBaseVerified ? "text-blue-400" : "text-blue-400/30"} />
      <WebIcon size={10} className={isWebVerified ? "text-yellow-400" : "text-yellow-400/30"} />
    </div>
  );
}

// Get signup platform badge color
function getSignupPlatformColor(platform?: SignupPlatform | "web"): string {
  if (platform === "farcaster") return "text-purple-400";
  if (platform === "base-app") return "text-blue-400";
  if (platform === "web") return "text-yellow-400";
  return "text-gray-400";
}

// Get signup platform label
function _getSignupPlatformLabel(platform?: SignupPlatform | "web"): string {
  if (platform === "farcaster") return "FC";
  if (platform === "base-app") return "Base";
  if (platform === "web") return "Web";
  return "";
}

// Pagination constants
const ITEMS_PER_PAGE = 10;

// Pagination component
function Pagination({
  currentPage,
  totalItems,
  itemsPerPage,
  onPageChange,
}: {
  currentPage: number;
  totalItems: number;
  itemsPerPage: number;
  onPageChange: (page: number) => void;
}) {
  const totalPages = Math.ceil(totalItems / itemsPerPage);

  if (totalPages <= 1) return null;

  const startItem = (currentPage - 1) * itemsPerPage + 1;
  const endItem = Math.min(currentPage * itemsPerPage, totalItems);

  return (
    <div className="flex items-center justify-between mt-4 pt-3 border-t border-[#00ff00]/10">
      <Small className="text-gray-500 font-mono text-[10px]">
        {startItem}-{endItem} of {totalItems}
      </Small>
      <div className="flex gap-2">
        <button
          onClick={() => onPageChange(currentPage - 1)}
          disabled={currentPage === 1}
          className="px-3 py-1 rounded bg-[#0a0a0a] border border-[#00ff00]/20 text-[#00ff00] font-mono text-xs disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#00ff00]/10 transition-colors"
        >
          ← Prev
        </button>
        <span className="px-2 py-1 text-gray-400 font-mono text-xs">
          {currentPage}/{totalPages}
        </span>
        <button
          onClick={() => onPageChange(currentPage + 1)}
          disabled={currentPage === totalPages}
          className="px-3 py-1 rounded bg-[#0a0a0a] border border-[#00ff00]/20 text-[#00ff00] font-mono text-xs disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#00ff00]/10 transition-colors"
        >
          Next →
        </button>
      </div>
    </div>
  );
}

export function LeaderboardTab({ categories: _categories }: LeaderboardTabProps) {
  const [activeTab, setActiveTab] = useState<TabType>("uploaders");
  const [showTechDoc, setShowTechDoc] = useState(false);
  const [showSpecsDoc, setShowSpecsDoc] = useState(false);
  const [showDocsModal, setShowDocsModal] = useState(false);
  const [showBrandKit, setShowBrandKit] = useState(false);
  const [showAdminStats, setShowAdminStats] = useState(false);
  const [totalUpvotes, setTotalUpvotes] = useState(0);
  const [totalMembers, setTotalMembers] = useState(0);
  const [userUpvotesReceived, setUserUpvotesReceived] = useState<Map<string, number>>(new Map());
  const [userUpvotesGiven, setUserUpvotesGiven] = useState<Map<string, number>>(new Map());
  const [bookUpvotes, setBookUpvotes] = useState<Record<string, number>>({});
  const [selectedUser, setSelectedUser] = useState<LeaderboardUserInfo | null>(null);
  const [selectedUserMember, setSelectedUserMember] = useState<(MemberEntry & { pfpUrl?: string }) | null>(null);
  const [topUpvoters, setTopUpvoters] = useState<Array<{
    address: string;
    totalUpvotes: number;
    itemsUpvoted: Array<{ storageKey: string; operator: string; amount: number; timestamp: number }>;
  }>>([]);
  const [upvotersLoading, setUpvotersLoading] = useState(false);
  const [upvoterUsernames, setUpvoterUsernames] = useState<Map<string, { username: string; pfpUrl: string; fid?: number }>>(new Map());
  const [expandedUpvoter, setExpandedUpvoter] = useState<string | null>(null);
  const [showContributorInfo, setShowContributorInfo] = useState(false);
  const [memberDataMap, setMemberDataMap] = useState<Map<string, MemberData>>(new Map());

  // Pagination state for each tab
  const [uploadersPage, setUploadersPage] = useState(1);
  const [stacksPage, setStacksPage] = useState(1);
  const [booksPage, setBooksPage] = useState(1);
  const [upvotersPage, setUpvotersPage] = useState(1);

  // Stacks data
  const [allStacks, setAllStacks] = useState<Array<{
    id: string;
    name: string;
    description?: string;
    owner: string;
    ownerUsername?: string;
    ownerPfpUrl?: string;
    itemCount: number;
    upvotes?: number;
    createdAt: number;
  }>>([]);
  const [totalStacks, setTotalStacks] = useState(0);
  const [stacksLoading, setStacksLoading] = useState(false);

  // Grids data
  const [totalGrids, setTotalGrids] = useState(0);
  const [allGrids, setAllGrids] = useState<Array<{
    id: string;
    name: string;
    size: number;
    creator: string;
    creatorUsername?: string;
    creatorPfpUrl?: string;
    cellCount: number;
    totalCells: number;
    upvoteCount: number;
    createdAt: number;
  }>>([]);
  const [gridsLoading, setGridsLoading] = useState(false);
  const [gridsPage, setGridsPage] = useState(1);
  const [gridsSortBy, setGridsSortBy] = useState<"upvotes" | "items">("upvotes");
  // Track how many grids each item appears in (by CDN URL)
  const [itemGridAppearances, setItemGridAppearances] = useState<Map<string, number>>(new Map());

  // Get current user's membership status for gating features
  const { isMember, fid: currentFid } = useMembershipStatus();
  const isAdmin = currentFid === 282520;

  // Reset pagination when switching tabs
  const handleTabChange = (tab: TabType) => {
    setActiveTab(tab);
    // Keep pages - user might want to return to same position
  };
  const {
    isLoading,
    error,
    refresh,
    globalStats,
    getTopUploaders,
    getPopularBooks,
    getCategoryStats: _getCategoryStats,
    resolvedUsers,
  } = useLeaderboard();

  // Get discovery data from shared context
  const { entries } = useDiscoveryContext();

  // Map of FID -> member data for FID-based lookups
  const [fidToMemberMap, setFidToMemberMap] = useState<Map<number, MemberData>>(new Map());
  // Map of address -> ALL memberships for that user (for showing multiple member #s)
  const [userAllMembershipsMap, setUserAllMembershipsMap] = useState<Map<string, MemberData[]>>(new Map());
  // Map of FID -> ALL memberships for that FID (direct lookup)
  const [fidToAllMemberships, setFidToAllMemberships] = useState<Map<number, MemberData[]>>(new Map());

  // Fetch total members count and member data for cross-platform display
  useEffect(() => {
    async function fetchMemberData() {
      try {
        const response = await fetch("/api/member-registry");
        if (!response.ok) {
          // /api/member-registry is admin-only; fall back to the public /api/stats endpoint
          // for the member count so the stats card shows the correct value for all users.
          try {
            const statsRes = await fetch("/api/stats");
            if (statsRes.ok) {
              const statsData = await statsRes.json();
              setTotalMembers(statsData.stats?.totalMembers || 0);
            }
          } catch {
            // silently ignore — count stays 0
          }
          return;
        }
        const data = await response.json();
        setTotalMembers(data.members?.length || 0);

        // Build maps for lookups by address AND by FID
          const memberMap = new Map<string, MemberData>();
          const fidMap = new Map<number, MemberData>();
          const allMembershipsMap = new Map<string, MemberData[]>();

          for (const member of data.members || []) {
            if (!member.address) continue;
            // Index by primary address
            memberMap.set(member.address.toLowerCase(), member);
            // Also index by linked addresses
            if (member.linkedAddresses) {
              for (const linked of member.linkedAddresses) {
                if (!linked) continue;
                memberMap.set(linked.toLowerCase(), member);
              }
            }
            // Index by FID for cross-platform lookup
            if (member.fid) {
              fidMap.set(member.fid, member);
            }
          }

          // Build allMembershipsMap: Group memberships by BOTH FID AND address
          // Some memberships have same address but different/missing FIDs
          const fidToMembershipsTemp = new Map<number, MemberData[]>();
          const addressToMembershipsTemp = new Map<string, MemberData[]>();

          // First pass: group by address (most reliable for duplicate detection)
          for (const member of data.members || []) {
            if (!member.address) continue;
            const addr = member.address.toLowerCase();
            const existing = addressToMembershipsTemp.get(addr) || [];
            existing.push(member);
            addressToMembershipsTemp.set(addr, existing);

            // Also group by FID for FID-based lookups
            if (member.fid) {
              const fidExisting = fidToMembershipsTemp.get(member.fid) || [];
              fidExisting.push(member);
              fidToMembershipsTemp.set(member.fid, fidExisting);
            }
          }

          // Now map each address to all memberships for that user
          // Merge memberships found by address AND by FID
          for (const member of data.members || []) {
            if (!member.address) continue;
            const addr = member.address.toLowerCase();

            // Start with memberships at this address
            const membershipSet = new Map<number, MemberData>();
            const addressMemberships = addressToMembershipsTemp.get(addr) || [];
            for (const m of addressMemberships) {
              membershipSet.set(m.memberId, m);
            }

            // Also add memberships with matching FID (if any)
            if (member.fid) {
              const fidMemberships = fidToMembershipsTemp.get(member.fid) || [];
              for (const m of fidMemberships) {
                membershipSet.set(m.memberId, m);
              }
            }

            const allMemberships = Array.from(membershipSet.values());
            allMembershipsMap.set(addr, allMemberships);

            // Also map linked addresses
            if (member.linkedAddresses) {
              for (const linked of member.linkedAddresses) {
                if (!linked) continue;
                allMembershipsMap.set(linked.toLowerCase(), allMemberships);
              }
            }
          }

          setMemberDataMap(memberMap);
          setFidToMemberMap(fidMap);
          setUserAllMembershipsMap(allMembershipsMap);
          setFidToAllMemberships(fidToMembershipsTemp);
      } catch (error) {
        console.error("Failed to fetch member data:", error);
      }
    }
    fetchMemberData();
  }, []);

  // Fetch all stacks for leaderboard
  useEffect(() => {
    async function fetchAllStacks() {
      setStacksLoading(true);
      try {
        // Fetch popular stacks (sorted by upvotes)
        const response = await fetch("/api/stacks?popular=true");
        if (response.ok) {
          const data = await response.json();
          setAllStacks(data.stacks || []);
        }

        // Also fetch total count
        const allResponse = await fetch("/api/stacks");
        if (allResponse.ok) {
          const allData = await allResponse.json();
          setTotalStacks(allData.total || allData.stacks?.length || 0);
        }
      } catch (error) {
        console.error("Failed to fetch stacks:", error);
      } finally {
        setStacksLoading(false);
      }
    }
    fetchAllStacks();
  }, []);

  // Fetch all grids for leaderboard and track item appearances
  useEffect(() => {
    async function fetchAllGrids() {
      setGridsLoading(true);
      try {
        // Fetch grids (default sorted by upvotes)
        const response = await fetch("/api/grids?pageSize=100");
        if (response.ok) {
          const data = await response.json();
          const gridsData = data.grids || [];
          setTotalGrids(data.total || gridsData.length);

          // Resolve usernames for grid creators
          const creatorAddresses = [...new Set(gridsData.map((g: { creator: string }) => g.creator))];
          let usernameMap = new Map<string, { username: string; pfpUrl: string }>();

          if (creatorAddresses.length > 0) {
            try {
              const resolveResponse = await fetch("/api/resolve-user", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ addresses: creatorAddresses }),
              });
              if (resolveResponse.ok) {
                const resolveData = await resolveResponse.json();
                for (const [addr, user] of Object.entries(resolveData.users || {})) {
                  const userData = user as { username: string; pfpUrl: string };
                  usernameMap.set(addr.toLowerCase(), userData);
                }
              }
            } catch {
              // Ignore resolve errors
            }
          }

          // Enhance grids with resolved usernames
          const enhancedGrids = gridsData.map((grid: {
            id: string;
            name: string;
            size: number;
            creator: string;
            cellCount: number;
            totalCells: number;
            upvoteCount: number;
            createdAt: number;
          }) => {
            const resolved = grid.creator ? usernameMap.get(grid.creator.toLowerCase()) : undefined;
            return {
              ...grid,
              creatorUsername: resolved?.username,
              creatorPfpUrl: resolved?.pfpUrl,
            };
          });

          setAllGrids(enhancedGrids);

          // Fetch each grid's cells to track item appearances
          // Build a map of CDN URL -> Set of grid IDs where it appears
          const cdnToGridIds = new Map<string, Set<string>>();

          // Fetch cells for each grid (in parallel batches)
          const gridIds = gridsData.map((g: { id: string }) => g.id);
          const batchSize = 10;
          for (let i = 0; i < gridIds.length; i += batchSize) {
            const batch = gridIds.slice(i, i + batchSize);
            await Promise.all(batch.map(async (gridId: string) => {
              try {
                const gridResponse = await fetch(`/api/grids?id=${gridId}`);
                if (gridResponse.ok) {
                  const gridData = await gridResponse.json();
                  const cells = gridData.cells || [];
                  for (const cell of cells) {
                    if (cell.cdnUrl) {
                      const existing = cdnToGridIds.get(cell.cdnUrl) || new Set();
                      existing.add(gridId);
                      cdnToGridIds.set(cell.cdnUrl, existing);
                    }
                  }
                }
              } catch {
                // Ignore individual grid fetch errors
              }
            }));
          }

          // Convert to count map
          const appearancesMap = new Map<string, number>();
          for (const [cdnUrl, gridIds] of cdnToGridIds) {
            appearancesMap.set(cdnUrl, gridIds.size);
          }
          setItemGridAppearances(appearancesMap);
        }
      } catch (error) {
        console.error("Failed to fetch grids:", error);
      } finally {
        setGridsLoading(false);
      }
    }
    fetchAllGrids();
  }, []);

  // Fetch upvote counts for all content
  useEffect(() => {
    async function fetchAllUpvotes() {
      if (entries.length === 0) return;

      try {
        // Generate scoreKeys for the API (same as useUpvoteCounts hook)
        // Use uploaderAddress (user's actual wallet) if present, falling back to operator
        // (backend relay wallet) — must match the address used when casting upvotes
        const scoreKeys = entries.map(e =>
          generateScoreKey(e.contentKey, e.uploaderAddress || e.operator)
        );
        const contentKeys = entries.map(e => e.contentKey);

        const response = await fetch("/api/upvotes", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ scoreKeys, contentKeys }),
        });

        if (response.ok) {
          const data = await response.json();
          let total = 0;
          const userMap = new Map<string, number>();
          const bookCounts: Record<string, number> = {};

          // Process the counts array (matches contentKeys order)
          if (data.counts && Array.isArray(data.counts)) {
            data.counts.forEach((count: number, index: number) => {
              const entry = entries[index];
              if (entry) {
                total += count;
                bookCounts[entry.contentKey] = count;

                // Track per-user received upvotes - use uploaderAddress for attribution
                // (falls back to operator for backwards compatibility with older entries)
                const attributionAddr = entry.uploaderAddress || entry.operator;
                if (attributionAddr) {
                  const currentCount = userMap.get(attributionAddr.toLowerCase()) || 0;
                  userMap.set(attributionAddr.toLowerCase(), currentCount + count);
                }
              }
            });
          }

          setTotalUpvotes(total);
          setUserUpvotesReceived(userMap);
          setBookUpvotes(bookCounts);
        }
      } catch (err) {
        console.error("Failed to fetch upvotes:", err);
      }
    }

    fetchAllUpvotes();
  }, [entries]);

  // State for all memberships for selected user (for users with multiple member numbers)
  const [selectedUserAllMemberships, setSelectedUserAllMemberships] = useState<Array<{
    memberId: number;
    ensSubname: string;
    signupPlatform: "farcaster" | "base-app" | "unknown";
    joinedAt: number;
    fid?: number;
    username?: string;
    address: string;
    matchType: "primary" | "fid" | "linked";
  }> | null>(null);

  // Fetch member info when a user is selected
  // Use the membership API which checks by address, FID, AND linked addresses
  useEffect(() => {
    if (!selectedUser) {
      setSelectedUserMember(null);
      setSelectedUserAllMemberships(null);
      return;
    }

    // Capture the value to avoid null checks in async function
    const user = selectedUser;
    if (!user.address) {
      setSelectedUserMember(null);
      setSelectedUserAllMemberships(null);
      return;
    }

    async function fetchMemberInfo() {
      try {
        // First, try to resolve the user's FID from their address (for cross-platform lookup)
        let userFid: number | undefined;
        try {
          const resolveResponse = await fetch("/api/resolve-user", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ addresses: [user.address] }),
          });
          if (resolveResponse.ok) {
            const resolveData = await resolveResponse.json();
            const resolved = resolveData.users?.[user.address!.toLowerCase()];
            if (resolved?.fid) {
              userFid = resolved.fid;
            }
          }
        } catch {
          // Ignore FID resolution errors
        }

        // Use the membership API which checks address, FID, and linked addresses
        const fidParam = userFid ? `&fid=${userFid}` : "";
        const response = await fetch(`/api/membership?address=${user.address}${fidParam}`);

        if (response.ok) {
          const data = await response.json();

          if (data.isMember && data.member) {
            // Found membership - use the full member data which includes FID info
            setSelectedUserMember({
              ...data.member,
              pfpUrl: user.pfpUrl,
            });
            // Store all memberships if user has multiple member numbers
            setSelectedUserAllMemberships(data.allMemberships || null);
          } else {
            // Create a placeholder member entry for non-members
            setSelectedUserMember({
              memberId: 0,
              address: user.address,
              ensSubname: "non-member",
              username: user.username,
              joinedAt: Date.now(),
              pfpUrl: user.pfpUrl,
            });
            setSelectedUserAllMemberships(null);
          }
        }
      } catch (err) {
        console.error("Failed to fetch member info:", err);
      }
    }

    fetchMemberInfo();
  }, [selectedUser]);

  // Fetch upvoters data on mount (needed for "upvotes given" stats on user cards)
  const [upvotersFetched, setUpvotersFetched] = useState(false);
  useEffect(() => {
    if (upvotersFetched) return;

    async function fetchUpvoters() {
      setUpvotersLoading(true);
      setUpvotersFetched(true);
      try {
        const response = await fetch("/api/upvote-events");
        if (response.ok) {
          const data = await response.json();
          const upvotersList = data.topUpvoters || [];
          setTopUpvoters(upvotersList);

          // Build map of upvotes given by each user
          const givenMap = new Map<string, number>();
          for (const upvoter of upvotersList) {
            if (!upvoter.address) continue;
            givenMap.set(upvoter.address.toLowerCase(), upvoter.totalUpvotes);
          }
          setUserUpvotesGiven(givenMap);

          // Resolve usernames for upvoters
          const addresses = upvotersList.filter((u: { address: string }) => u.address).map((u: { address: string }) => u.address);
          if (addresses.length > 0) {
            const resolveResponse = await fetch("/api/resolve-user", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ addresses }),
            });
            if (resolveResponse.ok) {
              const resolveData = await resolveResponse.json();
              const usernameMap = new Map<string, { username: string; pfpUrl: string; fid?: number }>();
              for (const [addr, user] of Object.entries(resolveData.users || {})) {
                const userData = user as { username: string; pfpUrl: string; fid?: number };
                usernameMap.set(addr.toLowerCase(), {
                  username: userData.username,
                  pfpUrl: userData.pfpUrl,
                  fid: userData.fid,
                });
              }
              setUpvoterUsernames(usernameMap);
            }
          }
        }
      } catch (err) {
        console.error("Failed to fetch upvoters:", err);
      } finally {
        setUpvotersLoading(false);
      }
    }

    fetchUpvoters();
  }, [upvotersFetched]);

  // Get book title from entries by storage key
  const getBookTitle = (storageKey: string): string | null => {
    if (!storageKey) return null;
    // Storage keys are hex-encoded, need to match with content keys
    const entry = entries.find(e => {
      if (!e.contentKey) return false;
      // Compare lowercase, handle potential 0x prefix differences
      const entryKey = e.contentKey.toLowerCase().replace(/^0x/, "");
      const searchKey = storageKey.toLowerCase().replace(/^0x/, "");
      return entryKey.includes(searchKey.slice(0, 16)) || searchKey.includes(entryKey.slice(0, 16));
    });
    return entry?.title || null;
  };

  // Loading state
  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center py-20">
        <div className="text-4xl mb-4 animate-pulse text-[#00ff00]"><ChartIcon size={48} /></div>
        <P className="text-[#00ff00] font-mono">Loading Net Library Info...</P>
        <Small className="text-gray-500 font-mono mt-2">Fetching onchain stats</Small>
      </div>
    );
  }

  // Error state
  if (error) {
    return (
      <div className="flex flex-col items-center justify-center py-20">
        <div className="text-4xl mb-4 text-yellow-500"><WarningIcon size={48} /></div>
        <P className="text-red-400 font-mono mb-2">Failed to load info</P>
        <Small className="text-gray-500 font-mono mb-4">{error}</Small>
        <button
          onClick={refresh}
          className="px-4 py-2 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg text-[#00ff00] font-mono hover:bg-[#00ff00]/20 transition-colors flex items-center gap-2"
        >
          <RefreshIcon size={14} /> Try Again
        </button>
      </div>
    );
  }

  // Get all data (not limited to 10 anymore since we paginate)
  const allTopUploaders = getTopUploaders(100);
  const allPopularBooks = getPopularBooks(100);

  // Paginate uploaders
  const paginatedUploaders = allTopUploaders.slice(
    (uploadersPage - 1) * ITEMS_PER_PAGE,
    uploadersPage * ITEMS_PER_PAGE
  );

  // Paginate books
  const paginatedBooks = allPopularBooks.slice(
    (booksPage - 1) * ITEMS_PER_PAGE,
    booksPage * ITEMS_PER_PAGE
  );

  // Paginate upvoters
  const paginatedUpvoters = topUpvoters.slice(
    (upvotersPage - 1) * ITEMS_PER_PAGE,
    upvotersPage * ITEMS_PER_PAGE
  );

  return (
    <div className="space-y-4">
      {/* Tech Document Modal */}
      <TechDocumentModal isOpen={showTechDoc} onClose={() => setShowTechDoc(false)} />

      {/* Specs Document Modal */}
      <SpecsDocumentModal isOpen={showSpecsDoc} onClose={() => setShowSpecsDoc(false)} />
      <DocsModal isOpen={showDocsModal} onClose={() => setShowDocsModal(false)} isMember={isMember} isAdmin={isAdmin} />
      <BrandKitModal isOpen={showBrandKit} onClose={() => setShowBrandKit(false)} />
      {isAdmin && <AdminStatsModal isOpen={showAdminStats} onClose={() => setShowAdminStats(false)} />}

      {/* Header with Use in Browser button */}
      <div className="flex items-center justify-between">
        <H4 className="text-[#00ff00] font-mono">Net Library Info</H4>
        <button
          onClick={() => openInExternalBrowser("https://miniapp-generator-fid-282520-251210015136529.neynar.app/")}
          className="text-yellow-400 font-mono text-xs hover:text-yellow-300 transition-colors flex items-center gap-1.5"
        >
          <BrowserIcon size={14} />
          <span className="underline">Use in Browser</span>
          <ExportIcon size={10} />
        </button>
      </div>

      {/* Global Stats Banner - Now at top */}
      <Card className="bg-gradient-to-r from-[#00ff00]/10 to-[#00ff00]/5 border-2 border-[#00ff00]/50">
        <CardContent className="p-4">
          <div className="flex flex-col items-center justify-center mb-3">
            <P className="text-2xl font-bold text-[#00ff00] font-mono text-center">Total Net Library Stats</P>
            <P className="text-gray-400 font-mono text-xs text-center">Real-time Onchain Data</P>
          </div>

          {/* Row 1: Items, Stacks, Grids, Data Stored (MB) */}
          <div className="grid grid-cols-4 gap-3 mb-3">
            <div className="flex flex-col items-center">
              <P className="text-xl font-bold text-[#00ff00] font-mono">{entries.length}</P>
              <Small className="text-gray-400 font-mono text-[9px]">Items</Small>
            </div>
            <div className="flex flex-col items-center">
              <P className="text-xl font-bold text-[#00ff00] font-mono">{totalStacks}</P>
              <Small className="text-gray-400 font-mono text-[9px]">Stacks</Small>
            </div>
            <div className="flex flex-col items-center">
              <P className="text-xl font-bold text-[#00ff00] font-mono">{totalGrids}</P>
              <Small className="text-gray-400 font-mono text-[9px]">Grids</Small>
            </div>
            <div className="flex flex-col items-center">
              <P className="text-xl font-bold text-[#00ff00] font-mono">{(globalStats.totalBytes / (1024 * 1024)).toFixed(1)}</P>
              <Small className="text-gray-400 font-mono text-[9px]">MB</Small>
            </div>
          </div>

          {/* Row 2: Members, Contributors, Upvotes */}
          <div className="grid grid-cols-3 gap-4">
            <div className="flex flex-col items-center">
              <P className="text-2xl font-bold text-[#00ff00] font-mono">{totalMembers}</P>
              <Small className="text-gray-400 font-mono text-[10px]">Members</Small>
            </div>
            <div className="flex flex-col items-center relative">
              <P className="text-2xl font-bold text-[#00ff00] font-mono">{globalStats.totalUsers}</P>
              <button
                onClick={() => setShowContributorInfo(!showContributorInfo)}
                className="text-gray-400 font-mono text-[10px] flex items-center gap-0.5 hover:text-gray-300 transition-colors"
              >
                Contributors
                <sup className="text-[8px] text-[#00ff00]/70 ml-0.5">ⓘ</sup>
              </button>
              {showContributorInfo && (
                <div className="absolute top-full mt-1 left-1/2 -translate-x-1/2 bg-black border border-[#00ff00]/30 rounded px-2 py-1 z-10 whitespace-nowrap">
                  <Small className="text-gray-300 font-mono text-[9px]">
                    Unique users with at least 1 upload
                  </Small>
                </div>
              )}
            </div>
            <div className="flex flex-col items-center">
              <P className="text-2xl font-bold text-[#00ff00] font-mono">{totalUpvotes}</P>
              <Small className="text-gray-400 font-mono text-[10px]">Upvotes</Small>
            </div>
          </div>

          {/* Admin-only stats button — only rendered for FID 282520 */}
          {isAdmin && (
            <div className="mt-3 pt-3 border-t border-[#00ff00]/10 flex justify-center">
              <button
                onClick={() => setShowAdminStats(true)}
                className="flex items-center gap-1.5 px-3 py-1.5 rounded bg-[#00ff00]/5 border border-[#00ff00]/20 text-[#00ff00]/60 font-mono text-[10px] hover:bg-[#00ff00]/10 hover:text-[#00ff00] hover:border-[#00ff00]/40 transition-all"
              >
                <ChartIcon size={11} />
                ADMIN STATS
              </button>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Resources Section - Overview, Technical, Code Docs, Brand Kit */}
      <div>
        <P className="text-sm font-bold text-[#00ff00] font-mono mb-2">RESOURCES</P>
        <div className="grid grid-cols-4 gap-2">
          <button
            onClick={() => setShowTechDoc(true)}
            className="flex flex-col items-center justify-center py-3 px-2 bg-[#0a0a0a] border border-[#00ff00]/50 rounded-lg hover:border-[#00ff00] hover:bg-[#00ff00]/5 transition-all"
          >
            <span className="text-lg mb-1 text-[#00ff00]"><LibraryIcon size={18} /></span>
            <P className="text-[9px] font-bold text-gray-400 font-mono text-center">OVERVIEW</P>
          </button>
          <button
            onClick={() => setShowSpecsDoc(true)}
            className="flex flex-col items-center justify-center py-3 px-2 bg-[#0a0a0a] border border-[#00ff00]/50 rounded-lg hover:border-[#00ff00] hover:bg-[#00ff00]/5 transition-all"
          >
            <span className="text-lg mb-1 text-[#00ff00]"><SettingsIcon size={18} /></span>
            <P className="text-[9px] font-bold text-gray-400 font-mono text-center">TECHNICAL</P>
          </button>
          <button
            onClick={() => setShowDocsModal(true)}
            className="flex flex-col items-center justify-center py-3 px-2 bg-[#0a0a0a] border border-[#00ff00]/50 rounded-lg hover:border-[#00ff00] hover:bg-[#00ff00]/5 transition-all"
          >
            <span className="text-lg mb-1 text-[#00ff00]"><MonitorIcon size={18} /></span>
            <P className="text-[9px] font-bold text-gray-400 font-mono text-center">CODE DOCS</P>
          </button>
          <button
            onClick={() => setShowBrandKit(true)}
            className="flex flex-col items-center justify-center py-3 px-2 bg-[#0a0a0a] border border-[#00ff00]/50 rounded-lg hover:border-[#00ff00] hover:bg-[#00ff00]/5 transition-all"
          >
            <span className="text-lg mb-1 text-[#00ff00]"><PaletteIcon size={18} /></span>
            <P className="text-[9px] font-bold text-gray-400 font-mono text-center">BRAND KIT</P>
          </button>
        </div>
      </div>

      {/* Leaderboards Section */}
      <P className="text-lg font-bold text-[#00ff00] font-mono text-center">LEADERBOARDS</P>

      {/* Tab Navigation */}
      <div className="flex gap-1">
        {[
          { id: "uploaders" as TabType, label: "Users", Icon: UserIcon },
          { id: "stacks" as TabType, label: "Stacks", Icon: FolderIcon },
          { id: "grids" as TabType, label: "Grids", Icon: GridIcon },
          { id: "books" as TabType, label: "Items", Icon: DocumentIcon },
          { id: "upvoters" as TabType, label: "Upvotes", Icon: ChevronUpIcon },
        ].map((tab) => (
          <button
            key={tab.id}
            onClick={() => handleTabChange(tab.id)}
            className={`flex-1 px-2 py-2 rounded-lg font-mono text-xs transition-all flex items-center justify-center gap-1 ${
              activeTab === tab.id
                ? "bg-[#00ff00]/20 border border-[#00ff00]/50 text-[#00ff00]"
                : "bg-[#0a0a0a] border border-[#1a1a1a] text-gray-400 hover:border-[#00ff00]/30"
            }`}
          >
            {tab.Icon && <tab.Icon size={10} />}
            {tab.label}
          </button>
        ))}
      </div>

      {/* Tab Content */}
      <div className="space-y-2">
        {/* Top Uploaders */}
        {activeTab === "uploaders" && (
          <>
            {allTopUploaders.length === 0 ? (
              <div className="text-center py-8">
                <div className="text-3xl mb-2 text-[#00ff00]"><UserIcon size={36} /></div>
                <P className="text-gray-400 font-mono">No uploaders yet</P>
                <Small className="text-gray-500 font-mono">Be the first to upload!</Small>
              </div>
            ) : (
              paginatedUploaders.filter(u => u.address).map((user, index) => {
                // Calculate global rank based on page
                const globalIndex = (uploadersPage - 1) * ITEMS_PER_PAGE + index;
                const userAddr = user.address || '';
                const resolved = resolvedUsers.get(userAddr.toLowerCase());
                const displayName = resolved?.username || shortenAddress(userAddr);
                const avatarUrl = resolved?.pfpUrl || `https://api.dicebear.com/7.x/identicon/svg?seed=${userAddr}`;
                const upvotesReceived = userUpvotesReceived.get(userAddr.toLowerCase()) || 0;
                const upvotesGiven = userUpvotesGiven.get(userAddr.toLowerCase()) || 0;
                // Try to find member data by address first, then by FID (for cross-platform identity)
                let memberData = memberDataMap.get(userAddr.toLowerCase()) || null;
                if (!memberData && resolved?.fid) {
                  // User's uploader address doesn't match membership, but their FID does
                  // This handles users who signed up on Farcaster but upload from Base App
                  memberData = fidToMemberMap.get(resolved.fid) || null;
                }
                // Get ALL memberships for this user (via FID) for multi-membership display
                let allMemberships = userAllMembershipsMap.get(userAddr.toLowerCase()) || [];
                if (allMemberships.length === 0 && resolved?.fid) {
                  // Direct FID lookup - more reliable than iterating through address map
                  allMemberships = fidToAllMemberships.get(resolved.fid) || [];
                }
                // Sort by memberId (lowest first)
                allMemberships = [...allMemberships].sort((a, b) => a.memberId - b.memberId);

                return (
                  <Card
                    key={userAddr}
                    className="bg-[#0a0a0a] border border-[#00ff00]/50 hover:border-[#00ff00] transition-all"
                  >
                    <CardContent className="p-3">
                      <div className="flex items-center gap-3">
                        {/* Rank Badge */}
                        <div
                          className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold font-mono shrink-0 ${
                            globalIndex === 0
                              ? "bg-yellow-500/20 text-yellow-400 border border-yellow-500/30"
                              : globalIndex === 1
                              ? "bg-gray-400/20 text-gray-300 border border-gray-400/30"
                              : globalIndex === 2
                              ? "bg-orange-500/20 text-orange-400 border border-orange-500/30"
                              : "bg-[#00ff00]/10 text-[#00ff00] border border-[#00ff00]/20"
                          }`}
                        >
                          {globalIndex + 1}
                        </div>

                        {/* Avatar - Tappable to view library card */}
                        <button
                          onClick={() => setSelectedUser({
                            address: user.address,
                            username: resolved?.username,
                            pfpUrl: avatarUrl,
                          })}
                          className="shrink-0 focus:outline-none focus:ring-2 focus:ring-[#00ff00]/50 rounded-full"
                        >
                          <img
                            src={avatarUrl}
                            alt="avatar"
                            className="w-10 h-10 rounded-full border border-[#00ff00]/30 object-cover hover:border-[#00ff00] hover:shadow-[0_0_10px_rgba(0,255,0,0.3)] transition-all cursor-pointer"
                          />
                        </button>

                        {/* Info */}
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2">
                            <P className="text-sm font-mono text-white truncate">
                              {displayName}
                            </P>
                            {/* Member #s (show ALL memberships) and platform badges */}
                            {allMemberships.length > 0 ? (
                              <div className="flex items-center gap-1.5 shrink-0">
                                {allMemberships.map((m, i) => (
                                  <span key={m.memberId} className={`text-[9px] font-mono ${getSignupPlatformColor(m.signupPlatform)}`}>
                                    #{m.memberId}{i < allMemberships.length - 1 ? "," : ""}
                                  </span>
                                ))}
                                <PlatformBadges member={memberData} resolvedFid={resolved?.fid} />
                              </div>
                            ) : memberData && memberData.memberId > 0 && (
                              <div className="flex items-center gap-1.5 shrink-0">
                                <span className={`text-[9px] font-mono ${getSignupPlatformColor(memberData.signupPlatform)}`}>
                                  #{memberData.memberId}
                                </span>
                                <PlatformBadges member={memberData} resolvedFid={resolved?.fid} />
                              </div>
                            )}
                          </div>
                          <div className="grid grid-cols-4 gap-2 mt-2">
                            <div className="flex flex-col items-center">
                              <Small className="text-[#00ff00] font-mono text-xs font-bold">
                                {user.totalUploads}
                              </Small>
                              <Small className="text-gray-500 font-mono text-[7px]">
                                uploads
                              </Small>
                            </div>
                            <div className="flex flex-col items-center">
                              <Small className="text-[#00ff00] font-mono text-xs font-bold">
                                {upvotesReceived}
                              </Small>
                              <Small className="text-gray-500 font-mono text-[7px]">
                                ▲ received
                              </Small>
                            </div>
                            <div className="flex flex-col items-center">
                              <Small className="text-cyan-400 font-mono text-xs font-bold">
                                {upvotesGiven}
                              </Small>
                              <Small className="text-gray-500 font-mono text-[7px]">
                                ▲ given
                              </Small>
                            </div>
                            <div className="flex flex-col items-center">
                              <Small className="text-gray-400 font-mono text-xs font-bold">
                                {formatBytes(user.totalBytesUploaded)}
                              </Small>
                              <Small className="text-gray-500 font-mono text-[7px]">
                                data
                              </Small>
                            </div>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                );
              })
            )}
            {allTopUploaders.length > 0 && (
              <Pagination
                currentPage={uploadersPage}
                totalItems={allTopUploaders.length}
                itemsPerPage={ITEMS_PER_PAGE}
                onPageChange={setUploadersPage}
              />
            )}
          </>
        )}

        {/* Stacks Leaderboard */}
        {activeTab === "stacks" && (
          <>
            {stacksLoading ? (
              <div className="text-center py-8">
                <div className="text-3xl mb-2 animate-pulse text-[#00ff00]"><FolderIcon size={36} /></div>
                <P className="text-[#00ff00] font-mono">Loading stacks...</P>
                <Small className="text-gray-500 font-mono">Fetching stack data</Small>
              </div>
            ) : allStacks.length === 0 ? (
              <div className="text-center py-8">
                <div className="text-3xl mb-2 text-[#00ff00]"><FolderIcon size={36} /></div>
                <P className="text-gray-400 font-mono">No stacks yet</P>
                <Small className="text-gray-500 font-mono">Create the first stack!</Small>
              </div>
            ) : (
              allStacks.slice((stacksPage - 1) * ITEMS_PER_PAGE, stacksPage * ITEMS_PER_PAGE).map((stack, index) => {
                const globalIndex = (stacksPage - 1) * ITEMS_PER_PAGE + index;
                const avatarUrl = stack.ownerPfpUrl || `https://api.dicebear.com/7.x/identicon/svg?seed=${stack.owner}`;
                return (
                  <Card
                    key={stack.id}
                    className="bg-[#0a0a0a] border border-[#00ff00]/50 hover:border-[#00ff00] transition-all cursor-pointer"
                    onClick={() => {
                      // Navigate to stack detail
                      window.dispatchEvent(new CustomEvent("navigate-to-stack", { detail: stack }));
                    }}
                  >
                    <CardContent className="p-3">
                      <div className="flex items-center gap-3">
                        {/* Rank Badge */}
                        <div
                          className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold font-mono shrink-0 ${
                            globalIndex === 0
                              ? "bg-yellow-500/20 text-yellow-400 border border-yellow-500/30"
                              : globalIndex === 1
                              ? "bg-gray-400/20 text-gray-300 border border-gray-400/30"
                              : globalIndex === 2
                              ? "bg-orange-500/20 text-orange-400 border border-orange-500/30"
                              : "bg-[#00ff00]/10 text-[#00ff00] border border-[#00ff00]/20"
                          }`}
                        >
                          {globalIndex + 1}
                        </div>

                        {/* Stack Info */}
                        <div className="flex-1 min-w-0">
                          <P className="text-sm font-mono text-white truncate">{stack.name}</P>
                          <div className="flex items-center gap-2 mt-0.5">
                            <img
                              src={avatarUrl}
                              alt="owner"
                              className="w-4 h-4 rounded-full border border-[#00ff00]/20"
                            />
                            <Small className="text-gray-500 font-mono truncate">
                              {stack.ownerUsername || shortenAddress(stack.owner)}
                            </Small>
                          </div>
                        </div>

                        {/* Stats */}
                        <div className="flex flex-col items-end shrink-0">
                          <div className="flex items-center gap-3">
                            <div className="text-center">
                              <P className="text-[#00ff00] font-mono text-sm">{stack.itemCount}</P>
                              <Small className="text-gray-500 font-mono text-[9px]">items</Small>
                            </div>
                            <div className="text-center">
                              <UpvoteButton
                                contentKey={stack.id}
                                operatorAddress={stack.owner}
                                upvoteCount={stack.upvotes || 0}
                                title={stack.name}
                                inline
                              />
                              <Small className="text-gray-500 font-mono text-[9px]">upvotes</Small>
                            </div>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                );
              })
            )}
            {allStacks.length > 0 && (
              <Pagination
                currentPage={stacksPage}
                totalItems={allStacks.length}
                itemsPerPage={ITEMS_PER_PAGE}
                onPageChange={setStacksPage}
              />
            )}
          </>
        )}

        {/* Grids Leaderboard */}
        {activeTab === "grids" && (
          <>
            {/* Sort Toggle */}
            <div className="flex items-center justify-between mb-2">
              <Small className="text-gray-500 font-mono">Sort by:</Small>
              <div className="flex gap-1">
                <button
                  onClick={() => setGridsSortBy("upvotes")}
                  className={`px-2 py-1 rounded text-xs font-mono transition-all ${
                    gridsSortBy === "upvotes"
                      ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/50"
                      : "bg-[#0a0a0a] text-gray-400 border border-[#1a1a1a] hover:border-[#00ff00]/30"
                  }`}
                >
                  ▲ Upvotes
                </button>
                <button
                  onClick={() => setGridsSortBy("items")}
                  className={`px-2 py-1 rounded text-xs font-mono transition-all ${
                    gridsSortBy === "items"
                      ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/50"
                      : "bg-[#0a0a0a] text-gray-400 border border-[#1a1a1a] hover:border-[#00ff00]/30"
                  }`}
                >
                  📦 Items
                </button>
              </div>
            </div>

            {gridsLoading ? (
              <div className="text-center py-8">
                <div className="text-3xl mb-2 animate-pulse text-[#00ff00]"><GridIcon size={36} /></div>
                <P className="text-[#00ff00] font-mono">Loading grids...</P>
                <Small className="text-gray-500 font-mono">Fetching grid data</Small>
              </div>
            ) : allGrids.length === 0 ? (
              <div className="text-center py-8">
                <div className="text-3xl mb-2 text-[#00ff00]"><GridIcon size={36} /></div>
                <P className="text-gray-400 font-mono">No grids yet</P>
                <Small className="text-gray-500 font-mono">Create the first grid!</Small>
              </div>
            ) : (
              [...allGrids]
                .sort((a, b) => gridsSortBy === "upvotes"
                  ? b.upvoteCount - a.upvoteCount
                  : b.cellCount - a.cellCount
                )
                .slice((gridsPage - 1) * ITEMS_PER_PAGE, gridsPage * ITEMS_PER_PAGE)
                .map((grid, index) => {
                  const globalIndex = (gridsPage - 1) * ITEMS_PER_PAGE + index;
                  const avatarUrl = grid.creatorPfpUrl || `https://api.dicebear.com/7.x/identicon/svg?seed=${grid.creator || 'unknown'}`;
                  const fillPercent = (grid.totalCells || 0) > 0 ? Math.round(((grid.cellCount || 0) / (grid.totalCells || 1)) * 100) : 0;
                  return (
                    <Card
                      key={grid.id}
                      className="bg-[#0a0a0a] border border-[#00ff00]/50 hover:border-[#00ff00] transition-all cursor-pointer"
                      onClick={() => {
                        // Navigate to grid detail
                        window.dispatchEvent(new CustomEvent("navigate-to-grid", { detail: grid }));
                      }}
                    >
                      <CardContent className="p-3">
                        <div className="flex items-center gap-3">
                          {/* Rank Badge */}
                          <div
                            className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold font-mono shrink-0 ${
                              globalIndex === 0
                                ? "bg-yellow-500/20 text-yellow-400 border border-yellow-500/30"
                                : globalIndex === 1
                                ? "bg-gray-400/20 text-gray-300 border border-gray-400/30"
                                : globalIndex === 2
                                ? "bg-orange-500/20 text-orange-400 border border-orange-500/30"
                                : "bg-[#00ff00]/10 text-[#00ff00] border border-[#00ff00]/20"
                            }`}
                          >
                            {globalIndex + 1}
                          </div>

                          {/* Grid Info */}
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2">
                              <P className="text-sm font-mono text-white truncate">{grid.name || 'Untitled'}</P>
                              <span className="text-[9px] font-mono text-gray-500 shrink-0">{grid.size || 3}×{grid.size || 3}</span>
                            </div>
                            <div className="flex items-center gap-2 mt-0.5">
                              <img
                                src={avatarUrl}
                                alt="creator"
                                className="w-4 h-4 rounded-full border border-[#00ff00]/20"
                              />
                              <Small className="text-gray-500 font-mono truncate">
                                {grid.creatorUsername || shortenAddress(grid.creator || '')}
                              </Small>
                            </div>
                          </div>

                          {/* Stats */}
                          <div className="flex flex-col items-end shrink-0">
                            <div className="flex items-center gap-3">
                              <div className="text-center">
                                <P className="text-[#00ff00] font-mono text-sm">{grid.cellCount}</P>
                                <Small className="text-gray-500 font-mono text-[9px]">items</Small>
                              </div>
                              <div className="text-center">
                                <UpvoteButton
                                  contentKey={grid.id}
                                  operatorAddress={grid.creator || ''}
                                  upvoteCount={grid.upvoteCount || 0}
                                  title={grid.name || 'Grid'}
                                  inline
                                />
                                <Small className="text-gray-500 font-mono text-[9px]">upvotes</Small>
                              </div>
                            </div>
                            {/* Fill progress bar */}
                            <div className="mt-1 w-full">
                              <div className="h-1 w-16 bg-[#1a1a1a] rounded-full overflow-hidden">
                                <div
                                  className="h-full bg-[#00ff00]/50 transition-all"
                                  style={{ width: `${fillPercent}%` }}
                                />
                              </div>
                              <Small className="text-gray-600 font-mono text-[8px] text-right block">{fillPercent}% filled</Small>
                            </div>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  );
                })
            )}
            {allGrids.length > 0 && (
              <Pagination
                currentPage={gridsPage}
                totalItems={allGrids.length}
                itemsPerPage={ITEMS_PER_PAGE}
                onPageChange={setGridsPage}
              />
            )}
          </>
        )}

        {/* Popular Books */}
        {activeTab === "books" && (
          <>
            {allPopularBooks.length === 0 ? (
              <div className="text-center py-8">
                <div className="text-3xl mb-2 text-[#00ff00]"><DocumentIcon size={36} /></div>
                <P className="text-gray-400 font-mono">No books yet</P>
                <Small className="text-gray-500 font-mono">Upload the first book!</Small>
              </div>
            ) : (
              paginatedBooks.map((book, index) => {
                const globalIndex = (booksPage - 1) * ITEMS_PER_PAGE + index;
                const upvotes = bookUpvotes[book.contentKey] || 0;
                // Count grids this item appears in by checking if any CDN URLs contain the content key
                // Net Protocol CDN URLs typically include the content key
                const contentKeyNormalized = (book.contentKey || '').toLowerCase().replace(/^0x/, "");
                let gridCount = 0;
                for (const [cdnUrl, count] of itemGridAppearances) {
                  if (cdnUrl.toLowerCase().includes(contentKeyNormalized.slice(0, 16))) {
                    gridCount += count;
                    break; // Only count once per book
                  }
                }
                return (
                  <Card
                    key={book.contentKey}
                    className="bg-[#0a0a0a] border border-[#00ff00]/50 hover:border-[#00ff00] transition-all"
                  >
                    <CardContent className="p-3">
                      <div className="flex items-center gap-3">
                        {/* Rank */}
                        <div className="w-6 h-6 rounded-full bg-[#00ff00]/10 flex items-center justify-center text-xs font-bold text-[#00ff00] font-mono shrink-0">
                          {globalIndex + 1}
                        </div>

                        {/* Book Info */}
                        <div className="flex-1 min-w-0">
                          <P className="text-sm font-mono text-white truncate">{book.title}</P>
                          <Small className="text-gray-500 font-mono truncate block">
                            by {book.author}
                          </Small>
                        </div>

                        {/* Stats */}
                        <div className="flex items-center gap-3 shrink-0">
                          <div className="text-center">
                            <P className="text-[#00ff00] font-mono text-sm">▲ {upvotes}</P>
                            <Small className="text-gray-500 font-mono text-[9px]">upvotes</Small>
                          </div>
                          <div className="text-center">
                            <P className="text-cyan-400 font-mono text-sm">{gridCount}</P>
                            <Small className="text-gray-500 font-mono text-[9px]">grids</Small>
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                );
              })
            )}
            {allPopularBooks.length > 0 && (
              <Pagination
                currentPage={booksPage}
                totalItems={allPopularBooks.length}
                itemsPerPage={ITEMS_PER_PAGE}
                onPageChange={setBooksPage}
              />
            )}
          </>
        )}

        {/* Top Upvoters */}
        {activeTab === "upvoters" && (
          <>
            {upvotersLoading ? (
              <div className="text-center py-8">
                <div className="text-3xl mb-2 animate-pulse">▲</div>
                <P className="text-[#00ff00] font-mono">Loading upvoters...</P>
                <Small className="text-gray-500 font-mono">Fetching onchain data</Small>
              </div>
            ) : topUpvoters.length === 0 ? (
              <div className="text-center py-8">
                <div className="text-3xl mb-2">▲</div>
                <P className="text-gray-400 font-mono">No upvoters yet</P>
                <Small className="text-gray-500 font-mono">Be the first to upvote!</Small>
              </div>
            ) : (
              paginatedUpvoters.filter(u => u.address).map((upvoter, index) => {
                const globalIndex = (upvotersPage - 1) * ITEMS_PER_PAGE + index;
                const upvoterAddr = upvoter.address || '';
                const resolved = upvoterUsernames.get(upvoterAddr.toLowerCase());
                const displayName = resolved?.username || shortenAddress(upvoterAddr);
                const avatarUrl = resolved?.pfpUrl || `https://api.dicebear.com/7.x/identicon/svg?seed=${upvoterAddr}`;
                const isExpanded = expandedUpvoter === upvoterAddr;
                // Try to find member data by address first, then by FID (for cross-platform identity)
                let memberData = memberDataMap.get(upvoterAddr.toLowerCase()) || null;
                if (!memberData && resolved?.fid) {
                  memberData = fidToMemberMap.get(resolved.fid) || null;
                }
                // Get ALL memberships for this user (via FID) for multi-membership display
                let allMemberships = userAllMembershipsMap.get(upvoterAddr.toLowerCase()) || [];
                if (allMemberships.length === 0 && resolved?.fid) {
                  // Direct FID lookup - more reliable than iterating through address map
                  allMemberships = fidToAllMemberships.get(resolved.fid) || [];
                }
                // Sort by memberId (lowest first)
                allMemberships = [...allMemberships].sort((a, b) => a.memberId - b.memberId);

                return (
                  <Card
                    key={upvoterAddr}
                    className="bg-[#0a0a0a] border border-[#00ff00]/50 hover:border-[#00ff00] transition-all"
                  >
                    <CardContent className="p-3">
                      <div className="flex items-center gap-3">
                        {/* Rank Badge */}
                        <div
                          className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold font-mono shrink-0 ${
                            globalIndex === 0
                              ? "bg-yellow-500/20 text-yellow-400 border border-yellow-500/30"
                              : globalIndex === 1
                              ? "bg-gray-400/20 text-gray-300 border border-gray-400/30"
                              : globalIndex === 2
                              ? "bg-orange-500/20 text-orange-400 border border-orange-500/30"
                              : "bg-[#00ff00]/10 text-[#00ff00] border border-[#00ff00]/20"
                          }`}
                        >
                          {globalIndex + 1}
                        </div>

                        {/* Avatar - Tappable to view library card */}
                        <button
                          onClick={() => setSelectedUser({
                            address: upvoter.address,
                            username: resolved?.username,
                            pfpUrl: avatarUrl,
                          })}
                          className="shrink-0 focus:outline-none focus:ring-2 focus:ring-[#00ff00]/50 rounded-full"
                        >
                          <img
                            src={avatarUrl}
                            alt="avatar"
                            className="w-10 h-10 rounded-full border border-[#00ff00]/30 object-cover hover:border-[#00ff00] hover:shadow-[0_0_10px_rgba(0,255,0,0.3)] transition-all cursor-pointer"
                          />
                        </button>

                        {/* Info */}
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center gap-2">
                            <P className="text-sm font-mono text-white truncate">{displayName}</P>
                            {/* Member #s (show ALL memberships) and platform badges */}
                            {allMemberships.length > 0 ? (
                              <div className="flex items-center gap-1.5 shrink-0">
                                {allMemberships.map((m, i) => (
                                  <span key={m.memberId} className={`text-[9px] font-mono ${getSignupPlatformColor(m.signupPlatform)}`}>
                                    #{m.memberId}{i < allMemberships.length - 1 ? "," : ""}
                                  </span>
                                ))}
                                <PlatformBadges member={memberData} resolvedFid={resolved?.fid} />
                              </div>
                            ) : memberData && memberData.memberId > 0 && (
                              <div className="flex items-center gap-1.5 shrink-0">
                                <span className={`text-[9px] font-mono ${getSignupPlatformColor(memberData.signupPlatform)}`}>
                                  #{memberData.memberId}
                                </span>
                                <PlatformBadges member={memberData} resolvedFid={resolved?.fid} />
                              </div>
                            )}
                          </div>
                          <Small className="text-gray-500 font-mono">
                            {(upvoter.itemsUpvoted || []).length} item{(upvoter.itemsUpvoted || []).length !== 1 ? "s" : ""} upvoted
                          </Small>
                        </div>

                        {/* Upvote Count & Expand */}
                        <div className="flex items-center gap-2 shrink-0">
                          <div className="text-center">
                            <P className="text-[#00ff00] font-mono text-lg font-bold">▲ {upvoter.totalUpvotes}</P>
                            <Small className="text-gray-500 font-mono text-[9px]">total</Small>
                          </div>
                          <button
                            onClick={() => setExpandedUpvoter(isExpanded ? null : upvoter.address)}
                            className="w-6 h-6 flex items-center justify-center text-gray-400 hover:text-[#00ff00] transition-colors"
                          >
                            {isExpanded ? "▼" : "▶"}
                          </button>
                        </div>
                      </div>

                      {/* Expanded: Items they upvoted */}
                      {isExpanded && (upvoter.itemsUpvoted || []).length > 0 && (
                        <div className="mt-3 pt-3 border-t border-[#00ff00]/10">
                          <Small className="text-gray-400 font-mono mb-2 block">Items upvoted:</Small>
                          <div className="space-y-2">
                            {(upvoter.itemsUpvoted || []).slice(0, 5).map((item, i) => {
                              const title = getBookTitle(item.storageKey);
                              return (
                                <div key={i} className="flex items-center justify-between text-xs">
                                  <span className="text-gray-300 font-mono truncate flex-1">
                                    {title || shortenAddress(item.storageKey)}
                                  </span>
                                  <span className="text-[#00ff00] font-mono ml-2">▲ {item.amount}</span>
                                </div>
                              );
                            })}
                            {(upvoter.itemsUpvoted || []).length > 5 && (
                              <Small className="text-gray-500 font-mono">
                                +{(upvoter.itemsUpvoted || []).length - 5} more...
                              </Small>
                            )}
                          </div>
                        </div>
                      )}
                    </CardContent>
                  </Card>
                );
              })
            )}
            {topUpvoters.length > 0 && (
              <Pagination
                currentPage={upvotersPage}
                totalItems={topUpvoters.length}
                itemsPerPage={ITEMS_PER_PAGE}
                onPageChange={setUpvotersPage}
              />
            )}
          </>
        )}
      </div>

      {/* User Library Card Modal */}
      {selectedUserMember && (
        <UserLibraryCardModal
          isOpen={!!selectedUser}
          onClose={() => {
            setSelectedUser(null);
            setSelectedUserMember(null);
            setSelectedUserAllMemberships(null);
          }}
          member={selectedUserMember}
          allMemberships={selectedUserAllMemberships}
        />
      )}
    </div>
  );
}
src/features/app/components/library-card-share-modal.tsx
"use client";

import { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { P, Small } from "@neynar/ui";
import { safeComposeCast, safeOpenUrl, useAppMode } from "@/lib/app-mode";
import { Link2, Check } from "lucide-react";
import { UploadIcon } from "@/components/icons/net-library-icons";

interface LibraryCardShareModalProps {
  isOpen: boolean;
  onClose: () => void;
  memberId: number;
  ensSubname: string;
  /** Farcaster handle (e.g. "cherylfromnet") — used for @handle display */
  username: string;
  /** Human-readable display name (e.g. "Cheryl") — used for the big name title.
   *  Falls back to username when not provided (backwards compat). */
  displayName?: string;
  uploads: number;
  dataMb: string;
  upvotes: number;
  pfpUrl?: string;
  /** Mode: "share" for existing members, "welcome" for new signups */
  mode?: "share" | "welcome";
  /** Optional callback after successful share */
  onShared?: () => void;
  /** Platform verification status */
  fcVerified?: boolean;
  baseVerified?: boolean;
  webVerified?: boolean;
  /** Net Link info */
  hasNetLink?: boolean;
  netLinkLabel?: string;
}

export function LibraryCardShareModal({
  isOpen,
  onClose,
  memberId,
  ensSubname,
  username,
  displayName,
  uploads,
  dataMb,
  upvotes,
  pfpUrl,
  mode = "share",
  onShared,
  fcVerified = false,
  baseVerified = false,
  webVerified = false,
  hasNetLink = false,
  netLinkLabel = "",
}: LibraryCardShareModalProps) {
  // Resolve the display name — prefer explicit displayName prop, fall back to username
  const resolvedDisplayName = displayName || username;
  const [mounted, setMounted] = useState(false);
  const [isSharing, setIsSharing] = useState<"farcaster" | "x" | null>(null);
  const [showShareMenu, setShowShareMenu] = useState(false);
  const [imageLoaded, setImageLoaded] = useState(false);
  const [copied, setCopied] = useState(false);
  const appMode = useAppMode();
  const isBaseApp = appMode === "base-app";

  // Track client-side mount for portal
  useEffect(() => {
    setMounted(true);
    // Reset image loaded state when modal opens
    if (isOpen) {
      setImageLoaded(false);
    }
  }, [isOpen]);

  if (!isOpen || !mounted) return null;

  // Build the image URL for preview
  const baseUrl = typeof window !== "undefined" ? window.location.origin : "";
  const source = isBaseApp ? "base" : "farcaster";
  const imageParams = new URLSearchParams({
    memberId: String(memberId),
    ensSubname,
    username,       // Farcaster handle shown as @handle
    displayName: resolvedDisplayName, // Human-readable name shown as big title
    uploads: String(uploads),
    dataMb,
    upvotes: String(upvotes),
    fcVerified: String(fcVerified),
    baseVerified: String(baseVerified),
    webVerified: String(webVerified),
    hasNetLink: String(hasNetLink),
    netLinkLabel,
    t: String(Date.now()), // Cache buster
  });
  // Add PFP URL if available for the actual user photo
  if (pfpUrl) {
    imageParams.set('pfpUrl', pfpUrl);
  }
  const imageUrl = `${baseUrl}/api/share/image/library-card-nft?${imageParams.toString()}`;

  // Build the share URL (the page that crawlers will see)
  const shareParams = new URLSearchParams({
    memberId: String(memberId),
    ensSubname,
    username,       // Farcaster handle shown as @handle
    displayName: resolvedDisplayName, // Human-readable name shown as big title
    uploads: String(uploads),
    dataMb,
    upvotes: String(upvotes),
    fcVerified: String(fcVerified),
    baseVerified: String(baseVerified),
    webVerified: String(webVerified),
    hasNetLink: String(hasNetLink),
    netLinkLabel,
    t: String(Date.now()),
    source,
  });
  // Add PFP URL so the share page can include it in the OG image
  if (pfpUrl) {
    shareParams.set('pfpUrl', pfpUrl);
  }
  const shareUrl = `${baseUrl}/share/library-card?${shareParams.toString()}`;

  // Share text
  const castText = mode === "welcome"
    ? `I just minted my Net Library card!\n\nI'm member #${memberId} of the onchain decentralized media revolution powered by @netprotocol\n\n🟩 is $ALPHA\n\nTap below to mint your own card! 👇`
    : `Check out my Net Library Card!\n\n📤 ${uploads} uploads\n💾 ${dataMb} MB uploaded onchain\n▲ ${upvotes} upvotes received\n\nDecentralized onchain media powered by @netprotocol`;

  const xText = castText.replace("@netprotocol", "@netprotocolapp");

  const handleShareToFarcaster = async () => {
    setIsSharing("farcaster");
    setShowShareMenu(false);
    try {
      await safeComposeCast({
        text: castText,
        embeds: [shareUrl],
      });
      onShared?.();
      onClose();
    } catch (err) {
      console.error("Failed to share to Farcaster:", err);
    } finally {
      setIsSharing(null);
    }
  };

  const handleShareToX = async () => {
    setIsSharing("x");
    setShowShareMenu(false);
    try {
      // Build X share URL with source=web for browser deep link
      const xShareUrl = new URL(shareUrl);
      xShareUrl.searchParams.set("source", "web");

      const xIntentParams = new URLSearchParams({
        text: xText,
        url: xShareUrl.toString(),
      });
      const xIntentUrl = `https://twitter.com/intent/tweet?${xIntentParams.toString()}`;
      if (isBaseApp) {
        window.open(xIntentUrl, "_blank", "noopener,noreferrer");
      } else {
        await safeOpenUrl(xIntentUrl);
      }
      onShared?.();
      onClose();
    } catch (err) {
      console.error("Failed to share to X:", err);
    } finally {
      setIsSharing(null);
    }
  };

  const handleCopyLink = async () => {
    setShowShareMenu(false);
    try {
      await navigator.clipboard.writeText(shareUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error("Failed to copy link:", err);
      // Fallback for older browsers
      const textArea = document.createElement("textarea");
      textArea.value = shareUrl;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand("copy");
      document.body.removeChild(textArea);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  // Truncate URL for display
  const truncatedUrl = (() => {
    try {
      const url = new URL(shareUrl);
      const path = url.pathname + url.search;
      const maxPathLength = 20;
      const truncatedPath = path.length > maxPathLength
        ? path.slice(0, maxPathLength) + "..."
        : path;
      return url.host.replace(/^www\./, "").slice(0, 25) + truncatedPath;
    } catch {
      return shareUrl.slice(0, 35) + "...";
    }
  })();

  const modalContent = (
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/95"
      onClick={onClose}
    >
      <div
        className="w-full max-w-md"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Close button */}
        <div className="flex justify-end mb-2">
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors"
          >
            ✕
          </button>
        </div>

        {/* Modal Card */}
        <div className="bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl overflow-hidden shadow-[0_0_30px_rgba(0,255,0,0.15)]">
          {/* Header */}
          <div className="p-3 border-b border-[#00ff00]/20 bg-[#00ff00]/5">
            <div className="flex items-center gap-2">
              <div className="w-2 h-2 rounded-full bg-[#00ff00] animate-pulse shadow-[0_0_8px_#00ff00]" />
              <P className="text-[#00ff00] font-mono text-sm font-bold">
                {mode === "welcome" ? "🎉 Welcome to Net Library!" : "Share Your Library Card"}
              </P>
            </div>
            {mode === "welcome" && (
              <Small className="text-gray-400 font-mono mt-1 block">
                You are member #{memberId}! Share your card to let others know.
              </Small>
            )}
          </div>

          {/* Library Card Image Preview */}
          <div className="p-4">
            <div className="relative rounded-lg overflow-hidden border-2 border-[#00ff00]/30 bg-black">
              {/* Loading state */}
              {!imageLoaded && (
                <div className="absolute inset-0 flex items-center justify-center bg-black">
                  <div className="flex flex-col items-center gap-2">
                    <div className="w-8 h-8 border-2 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
                    <Small className="text-[#00ff00]/50 font-mono">Generating card...</Small>
                  </div>
                </div>
              )}
              {/* The actual image - 1.91:1 aspect ratio (1200x630) */}
              <img
                src={imageUrl}
                alt="Your Net Library Card"
                className={`w-full aspect-[1.91/1] object-cover transition-opacity duration-300 ${imageLoaded ? 'opacity-100' : 'opacity-0'}`}
                onLoad={() => setImageLoaded(true)}
                onError={() => setImageLoaded(true)} // Still show even if error
              />
            </div>

            {/* Member info summary */}
            <div className="mt-3 flex items-center justify-between px-1">
              <div className="flex items-center gap-2">
                {pfpUrl && (
                  <img
                    src={pfpUrl}
                    alt={username}
                    className="w-6 h-6 rounded-full border border-[#00ff00]/30"
                  />
                )}
                <div>
                  <Small className="text-[#00ff00] font-mono font-bold">@{username}</Small>
                  <Small className="text-gray-500 font-mono text-[10px] block">{resolvedDisplayName} · {ensSubname}</Small>
                </div>
              </div>
              <div className="flex items-center gap-3 text-[10px] font-mono text-gray-400">
                <span className="flex items-center gap-0.5"><UploadIcon size={10} /> {uploads}</span>
                <span>💾 {dataMb}MB</span>
                <span>▲ {upvotes}</span>
              </div>
            </div>
          </div>

          {/* Share Actions */}
          <div className="p-4 pt-0 space-y-2 relative">
            {/* Primary share button with dropdown */}
            <button
              onClick={() => setShowShareMenu(!showShareMenu)}
              disabled={isSharing !== null}
              className={`w-full py-3 rounded-lg font-mono text-sm font-bold transition-all disabled:opacity-50 ${
                isBaseApp
                  ? "bg-[#0052FF] text-white hover:bg-[#0052FF]/90"
                  : "bg-[#8A63D2] text-white hover:bg-[#8A63D2]/90"
              }`}
            >
              {isSharing ? "Sharing..." : mode === "welcome" ? "Share My New Card! 🎉" : "Share My Library Card ▾"}
            </button>

            {/* Share dropdown menu */}
            {showShareMenu && (
              <>
                <div className="fixed inset-0 z-40" onClick={() => setShowShareMenu(false)} />
                <div className="absolute bottom-full left-4 right-4 mb-2 bg-black border border-[#00ff00]/30 rounded-lg overflow-hidden z-50 shadow-lg">
                  <button
                    onClick={handleShareToFarcaster}
                    className={`w-full px-4 py-3 text-left text-sm font-mono flex items-center gap-3 transition-colors ${
                      isBaseApp
                        ? "hover:bg-[#0052FF]/20 text-[#0052FF]"
                        : "hover:bg-[#8A63D2]/20 text-[#8A63D2]"
                    }`}
                  >
                    {isBaseApp ? (
                      <svg width="18" height="18" viewBox="0 0 111 111" fill="none">
                        <path d="M54.921 110.034C85.359 110.034 110.034 85.402 110.034 55.017C110.034 24.6319 85.359 0 54.921 0C26.0432 0 2.35281 22.1714 0 50.3923H72.8467V59.6416H0C2.35281 87.8625 26.0432 110.034 54.921 110.034Z" fill="#0052FF"/>
                      </svg>
                    ) : (
                      <svg width="18" height="18" viewBox="0 0 1000 1000" fill="#8A63D2">
                        <path d="M257.778 155.556H742.222V844.445H671.111V528.889H670.414C662.554 441.677 589.258 373.333 500 373.333C410.742 373.333 337.446 441.677 329.586 528.889H328.889V844.445H257.778V155.556Z"/>
                        <path d="M128.889 253.333L157.778 351.111H182.222V746.667C169.949 746.667 160 756.616 160 768.889V795.556H155.556C143.283 795.556 133.333 805.505 133.333 817.778V844.445H382.222V817.778C382.222 805.505 372.273 795.556 360 795.556H355.556V768.889C355.556 756.616 345.606 746.667 333.333 746.667H306.667V253.333H128.889Z"/>
                        <path d="M675.556 746.667C663.283 746.667 653.333 756.616 653.333 768.889V795.556H648.889C636.616 795.556 626.667 805.505 626.667 817.778V844.445H875.556V817.778C875.556 805.505 865.606 795.556 853.333 795.556H848.889V768.889C848.889 756.616 838.94 746.667 826.667 746.667V351.111H851.111L880 253.333H702.222V746.667H675.556Z"/>
                      </svg>
                    )}
                    {isBaseApp ? "Share to Feed" : "Share to Farcaster"}
                  </button>
                  <button
                    onClick={handleShareToX}
                    className="w-full px-4 py-3 text-left text-sm font-mono flex items-center gap-3 hover:bg-white/10 text-white transition-colors border-t border-gray-800"
                  >
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="white">
                      <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                    </svg>
                    Share to X
                  </button>
                  <button
                    onClick={handleCopyLink}
                    className="w-full px-4 py-3 text-left text-sm font-mono flex items-center gap-3 hover:bg-[#00ff00]/10 text-[#00ff00] transition-colors border-t border-gray-800"
                  >
                    {copied ? (
                      <Check size={16} className="text-[#00ff00]" />
                    ) : (
                      <Link2 size={16} className="text-[#00ff00]" />
                    )}
                    <div className="flex-1 min-w-0">
                      <span className="block">{copied ? "Copied!" : "Copy Link"}</span>
                      <span className="block text-[10px] text-gray-500 truncate">{truncatedUrl}</span>
                    </div>
                  </button>
                </div>
              </>
            )}

            {/* Skip/Close button for welcome mode */}
            {mode === "welcome" && (
              <button
                onClick={onClose}
                className="w-full py-2 rounded-lg text-gray-500 font-mono text-sm hover:text-gray-400 transition-colors"
              >
                Maybe later
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );

  return createPortal(modalContent, document.body);
}
src/features/app/components/link-base-modal.tsx
"use client";

import { useState, useEffect } from "react";
import { H4, P, Small } from "@neynar/ui";
import { useAccount, useSignMessage } from "wagmi";
import { useFarcasterUser } from "@/neynar-farcaster-sdk/mini";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { createLinkWalletMessage, generateNonce } from "@/lib/siwe";
import { LinkIcon, LoadingIcon, ShareIcon, ClockIcon, EditIcon, CopyIcon, CheckIcon, CheckCircleIcon, BaseIcon } from "@/components/icons/net-library-icons";

interface LinkBaseModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

type Mode = "choose" | "same-device" | "different-device";
type Step = "connect" | "sign" | "verifying" | "success" | "link-generated";

interface ChallengeData {
  challengeId: string;
  linkUrl: string;
  expiresIn: number;
  memberId: number;
  ensSubname: string;
}

/**
 * Modal for Farcaster users to link their Base App wallet address to their existing membership.
 *
 * Two modes:
 * 1. Same Device: User's Base wallet is accessible on this device (direct SIWE)
 * 2. Different Device: User needs to open a link on their Base App device (challenge-based)
 *
 * Flow (Same Device):
 * 1. User connects their wallet (or uses already connected one)
 * 2. User signs a SIWE message to cryptographically prove wallet ownership
 * 3. We verify the signature and link the address to their membership
 *
 * Flow (Different Device):
 * 1. Create a time-limited challenge tied to the membership
 * 2. Generate a shareable link for the user to open in Base App
 * 3. User opens link in Base App, connects wallet, signs SIWE
 * 4. Server validates challenge and links wallet
 */
export function LinkBaseModal({ isOpen, onClose, onSuccess }: LinkBaseModalProps) {
  const { address: connectedAddress, isConnected } = useAccount();
  const { data: farcasterUser } = useFarcasterUser();
  const { memberId, registeredAddress, refresh: refreshMembership } = useMembershipStatus();
  const { signMessageAsync, isPending: isSigning } = useSignMessage();

  const [mode, setMode] = useState<Mode>("choose");
  const [step, setStep] = useState<Step>("connect");
  const [error, setError] = useState<string | null>(null);
  const [nonce, setNonce] = useState<string>("");
  const [challengeData, setChallengeData] = useState<ChallengeData | null>(null);
  const [isGeneratingLink, setIsGeneratingLink] = useState(false);
  const [linkCopied, setLinkCopied] = useState(false);

  // Reset state when modal opens
  useEffect(() => {
    if (isOpen) {
      setMode("choose");
      setStep("connect");
      setError(null);
      setNonce(generateNonce());
      setChallengeData(null);
      setLinkCopied(false);
    }
  }, [isOpen]);

  // Watch for wallet connection in same-device mode
  useEffect(() => {
    if (isOpen && mode === "same-device" && step === "connect" && isConnected && connectedAddress) {
      setStep("sign");
    }
  }, [isOpen, mode, step, isConnected, connectedAddress]);

  const handleChooseMode = (selectedMode: "same-device" | "different-device") => {
    setMode(selectedMode);
    if (selectedMode === "same-device") {
      if (isConnected && connectedAddress) {
        setStep("sign");
      } else {
        setStep("connect");
      }
    }
  };

  const handleGenerateLink = async () => {
    if (!farcasterUser?.fid || !registeredAddress) {
      setError("Missing membership data");
      return;
    }

    setIsGeneratingLink(true);
    setError(null);

    try {
      const response = await fetch("/api/link-challenge", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          fid: farcasterUser.fid,
          address: registeredAddress,
        }),
      });

      const data = await response.json();

      if (!response.ok || !data.success) {
        throw new Error(data.error || "Failed to create link");
      }

      setChallengeData({
        challengeId: data.challengeId,
        linkUrl: data.linkUrl,
        expiresIn: data.expiresIn,
        memberId: data.memberId,
        ensSubname: data.ensSubname,
      });
      setStep("link-generated");
    } catch (err) {
      console.error("Generate link error:", err);
      setError(err instanceof Error ? err.message : "Failed to generate link");
    } finally {
      setIsGeneratingLink(false);
    }
  };

  const handleCopyLink = async () => {
    if (!challengeData?.linkUrl) return;

    try {
      await navigator.clipboard.writeText(challengeData.linkUrl);
      setLinkCopied(true);
      setTimeout(() => setLinkCopied(false), 2000);
    } catch {
      // Fallback: select text
      setError("Could not copy. Please copy the link manually.");
    }
  };

  const handleShareLink = async () => {
    if (!challengeData?.linkUrl) return;

    if (navigator.share) {
      try {
        await navigator.share({
          title: "Link your Base wallet to Net Library",
          text: `Open this link in your Base App to link your wallet to member #${challengeData.memberId}`,
          url: challengeData.linkUrl,
        });
      } catch {
        // User cancelled or share failed - fall back to copy
        handleCopyLink();
      }
    } else {
      handleCopyLink();
    }
  };

  const handleSign = async () => {
    if (!connectedAddress || !farcasterUser?.fid || !memberId) {
      setError("Missing required data. Please try again.");
      return;
    }

    setError(null);

    try {
      // Create the SIWE message
      const message = createLinkWalletMessage(connectedAddress, farcasterUser.fid, nonce);

      // Request signature from wallet
      const signature = await signMessageAsync({ message });

      setStep("verifying");

      // Verify the signature server-side
      const verifyResponse = await fetch("/api/verify-siwe", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          message,
          signature,
          expectedAddress: connectedAddress,
        }),
      });

      const verifyData = await verifyResponse.json();

      if (!verifyResponse.ok || !verifyData.valid) {
        throw new Error(verifyData.error || "Signature verification failed");
      }

      // Now link the verified address to the membership
      const linkResponse = await fetch("/api/link-address", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          memberId,
          address: connectedAddress.toLowerCase(),
          fid: farcasterUser.fid,
          verified: true, // Mark as cryptographically verified
        }),
      });

      const linkData = await linkResponse.json();

      if (!linkResponse.ok || !linkData.success) {
        throw new Error(linkData.error || "Failed to link address");
      }

      setStep("success");
      refreshMembership();
      onSuccess?.();
    } catch (err) {
      console.error("SIWE error:", err);
      setError(err instanceof Error ? err.message : "Failed to verify wallet");
      setStep("sign");
    }
  };

  const handleClose = () => {
    setError(null);
    setMode("choose");
    setStep("connect");
    setNonce("");
    setChallengeData(null);
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4"
      onClick={handleClose}
    >
      <div
        className="bg-[#0a0a0a] border border-blue-500/30 rounded-xl max-w-sm w-full overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 py-3 border-b border-blue-500/20 flex items-center justify-between bg-blue-500/5">
          <div className="flex items-center gap-2">
            <BaseIcon size={20} className="text-blue-400" />
            <H4 className="text-blue-400 font-mono">Link Base Wallet</H4>
          </div>
          <button
            onClick={handleClose}
            className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors"
          >
            ✕
          </button>
        </div>

        {/* Content */}
        <div className="p-4">
          {/* Choose Mode */}
          {mode === "choose" && (
            <>
              <P className="text-gray-300 font-mono text-sm mb-4">
                Link your Base App wallet to access your membership on both platforms.
              </P>

              <div className="space-y-3">
                <button
                  onClick={() => handleChooseMode("same-device")}
                  className="w-full p-4 rounded-lg bg-[#1a1a1a] border border-gray-700 hover:border-blue-500/50 transition-colors text-left"
                >
                  <div className="flex items-center gap-3 mb-2">
                    <span className="text-2xl">📱</span>
                    <P className="text-white font-mono font-bold">Same Device</P>
                  </div>
                  <Small className="text-gray-400 font-mono block">
                    My Base wallet is accessible on this device (e.g., browser extension)
                  </Small>
                </button>

                <button
                  onClick={() => handleChooseMode("different-device")}
                  className="w-full p-4 rounded-lg bg-[#1a1a1a] border border-gray-700 hover:border-blue-500/50 transition-colors text-left"
                >
                  <div className="flex items-center gap-3 mb-2">
                    <LinkIcon size={24} className="text-blue-400" />
                    <P className="text-white font-mono font-bold">Different Device</P>
                  </div>
                  <Small className="text-gray-400 font-mono block">
                    My Base wallet is on another device (e.g., phone with Base App)
                  </Small>
                </button>
              </div>

              <Small className="text-gray-500 font-mono block text-center mt-4">
                Both methods use cryptographic signatures to prove wallet ownership.
              </Small>
            </>
          )}

          {/* Same Device Flow */}
          {mode === "same-device" && (
            <>
              {/* Back button */}
              <button
                onClick={() => setMode("choose")}
                className="text-gray-400 font-mono text-sm mb-4 hover:text-white transition-colors flex items-center gap-1"
              >
                ← Back
              </button>

              {/* Step: Connect Wallet */}
              {step === "connect" && (
                <>
                  <P className="text-gray-300 font-mono text-sm mb-4">
                    Connect your Base wallet to link it to your membership.
                  </P>

                  <div className="p-4 rounded-lg bg-blue-500/10 border border-blue-500/30 mb-4">
                    <P className="text-blue-400 font-mono text-sm text-center">
                      Please connect your wallet using the connect button in the app.
                    </P>
                  </div>

                  <Small className="text-gray-500 font-mono block text-center">
                    Once connected, you&apos;ll sign a message to prove ownership.
                  </Small>
                </>
              )}

              {/* Step: Sign Message */}
              {step === "sign" && (
                <>
                  <P className="text-gray-300 font-mono text-sm mb-4">
                    Sign a message to prove you own this wallet.
                  </P>

                  {/* Connected wallet display */}
                  <div className="p-4 rounded-lg bg-[#1a1a1a] border border-gray-700 mb-4">
                    <Small className="text-gray-400 font-mono block mb-1">
                      Connected Wallet
                    </Small>
                    <P className="text-white font-mono text-sm break-all">
                      {connectedAddress}
                    </P>
                  </div>

                  {/* What you're signing */}
                  <div className="p-3 rounded-lg bg-blue-500/10 border border-blue-500/20 mb-4">
                    <Small className="text-blue-400 font-mono block mb-2">
                      You&apos;re signing:
                    </Small>
                    <Small className="text-gray-400 font-mono block">
                      &quot;Link this wallet to Farcaster account (FID: {farcasterUser?.fid}) on Net Library&quot;
                    </Small>
                  </div>

                  {error && (
                    <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30 mb-4">
                      <P className="text-red-400 font-mono text-sm">{error}</P>
                    </div>
                  )}

                  <button
                    onClick={handleSign}
                    disabled={isSigning}
                    className="w-full py-3 rounded-lg bg-blue-500 text-white font-mono font-bold hover:bg-blue-400 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2"
                  >
                    {isSigning ? (
                      <>
                        <LoadingIcon size={16} className="animate-spin" />
                        Waiting for signature...
                      </>
                    ) : (
                      <>
                        <EditIcon size={16} /> Sign Message
                      </>
                    )}
                  </button>

                  <Small className="text-gray-500 font-mono block text-center mt-3">
                    This signature is free and doesn&apos;t cost any gas.
                  </Small>
                </>
              )}

              {/* Step: Verifying */}
              {step === "verifying" && (
                <div className="text-center py-6">
                  <div className="mb-4 flex justify-center"><LoadingIcon size={40} className="text-blue-400 animate-spin" /></div>
                  <H4 className="text-blue-400 font-mono mb-2">Verifying...</H4>
                  <P className="text-gray-400 font-mono text-sm">
                    Checking your signature and linking your wallet.
                  </P>
                </div>
              )}

              {/* Step: Success */}
              {step === "success" && (
                <div className="text-center py-4">
                  <div className="mb-4 flex justify-center"><CheckCircleIcon size={48} className="text-blue-400" /></div>
                  <H4 className="text-blue-400 font-mono mb-2">Wallet Linked!</H4>
                  <P className="text-gray-300 font-mono text-sm mb-4">
                    Your Base wallet is now linked to your membership.
                  </P>
                  <div className="p-3 rounded-lg bg-blue-500/10 border border-blue-500/30 mb-4">
                    <Small className="text-blue-400 font-mono">
                      You can now access Net Library from the Base App with the same member #{memberId}!
                    </Small>
                  </div>
                  <button
                    onClick={handleClose}
                    className="w-full py-3 rounded-lg bg-blue-500 text-white font-mono font-bold hover:bg-blue-400 transition-colors"
                  >
                    Done
                  </button>
                </div>
              )}
            </>
          )}

          {/* Different Device Flow */}
          {mode === "different-device" && (
            <>
              {/* Back button */}
              {step !== "link-generated" && (
                <button
                  onClick={() => setMode("choose")}
                  className="text-gray-400 font-mono text-sm mb-4 hover:text-white transition-colors flex items-center gap-1"
                >
                  ← Back
                </button>
              )}

              {step !== "link-generated" && (
                <>
                  <P className="text-gray-300 font-mono text-sm mb-4">
                    Generate a secure link to share with your Base App device.
                  </P>

                  <div className="p-4 rounded-lg bg-blue-500/10 border border-blue-500/30 mb-4">
                    <Small className="text-blue-400 font-mono block mb-2">How it works:</Small>
                    <ol className="text-gray-400 font-mono text-xs space-y-1">
                      <li>1. Generate a secure link (valid for 10 minutes)</li>
                      <li>2. Open the link in your Base App browser</li>
                      <li>3. Connect wallet & sign to prove ownership</li>
                      <li>4. Wallets are linked to your membership</li>
                    </ol>
                  </div>

                  {error && (
                    <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30 mb-4">
                      <P className="text-red-400 font-mono text-sm">{error}</P>
                    </div>
                  )}

                  <button
                    onClick={handleGenerateLink}
                    disabled={isGeneratingLink}
                    className="w-full py-3 rounded-lg bg-blue-500 text-white font-mono font-bold hover:bg-blue-400 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2"
                  >
                    {isGeneratingLink ? (
                      <>
                        <LoadingIcon size={16} className="animate-spin" />
                        Generating...
                      </>
                    ) : (
                      <>
                        <LinkIcon size={16} /> Generate Secure Link
                      </>
                    )}
                  </button>

                  <Small className="text-gray-500 font-mono block text-center mt-3">
                    Only you can use this link to add a wallet to your membership.
                  </Small>
                </>
              )}

              {/* Link Generated */}
              {step === "link-generated" && challengeData && (
                <>
                  <div className="text-center mb-4">
                    <div className="text-4xl mb-2">✓</div>
                    <H4 className="text-[#00ff00] font-mono">Link Generated!</H4>
                  </div>

                  <div className="p-4 rounded-lg bg-[#1a1a1a] border border-gray-700 mb-4">
                    <Small className="text-gray-400 font-mono block mb-2">Member</Small>
                    <P className="text-white font-mono text-sm">
                      #{challengeData.memberId} • {challengeData.ensSubname}
                    </P>
                  </div>

                  <div className="p-4 rounded-lg bg-blue-500/10 border border-blue-500/30 mb-4">
                    <Small className="text-blue-400 font-mono block mb-2">Secure Link</Small>
                    <P className="text-gray-300 font-mono text-xs break-all bg-[#0a0a0a] p-2 rounded">
                      {challengeData.linkUrl}
                    </P>
                  </div>

                  <div className="text-center mb-4">
                    <Small className="text-yellow-400 font-mono flex items-center justify-center gap-1">
                      <ClockIcon size={14} /> Expires in {Math.ceil(challengeData.expiresIn / 60000)} minutes
                    </Small>
                  </div>

                  <div className="flex gap-2 mb-4">
                    <button
                      onClick={handleCopyLink}
                      className="flex-1 py-3 rounded-lg bg-[#1a1a1a] text-white font-mono hover:bg-[#222] transition-colors flex items-center justify-center gap-2"
                    >
                      {linkCopied ? <><CheckIcon size={14} /> Copied!</> : <><CopyIcon size={14} /> Copy</>}
                    </button>
                    <button
                      onClick={handleShareLink}
                      className="flex-1 py-3 rounded-lg bg-blue-500 text-white font-mono font-bold hover:bg-blue-400 transition-colors flex items-center justify-center gap-2"
                    >
                      <ShareIcon size={14} /> Share
                    </button>
                  </div>

                  <Small className="text-gray-500 font-mono block text-center mb-4">
                    Open this link on your device with the Base App wallet.
                  </Small>

                  <button
                    onClick={handleClose}
                    className="w-full py-2 rounded-lg bg-transparent border border-gray-700 text-gray-400 font-mono hover:bg-[#1a1a1a] transition-colors"
                  >
                    Close
                  </button>
                </>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}
src/features/app/components/link-farcaster-modal.tsx
"use client";

import { useState, useEffect, useCallback } from "react";
import { H4, P, Small } from "@neynar/ui";
import { useAccount } from "wagmi";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { CheckCircleIcon, FarcasterIcon } from "@/components/icons/net-library-icons";
import { publicConfig } from "@/config/public-config";

// SIWN Client ID - uses the app's Neynar client ID
const NEYNAR_CLIENT_ID = publicConfig.neynarClientId;

// Storage key for pending link operation
const PENDING_LINK_KEY = "nl_pending_farcaster_link";

interface LinkFarcasterModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
  /** If true, user is trying to claim existing FC membership from Base App */
  claimExistingMembership?: boolean;
}

interface SIWNUser {
  fid: number;
  username: string;
  display_name?: string;
  pfp_url?: string;
  verified_addresses?: {
    eth_addresses?: string[];
  };
}

interface PendingLinkData {
  mode: "link" | "claim";
  address: string;
  memberId: number | null;
  timestamp: number;
}

/**
 * Modal for Base App users to link their Farcaster account.
 *
 * Uses redirect-based auth flow (works in WebViews) instead of popup.
 *
 * Two modes:
 * 1. Link mode (default): Base App member linking their Farcaster account to their membership
 * 2. Claim mode: Existing Farcaster member claiming their membership on Base App
 *
 * Flow:
 * 1. User clicks "Sign in with Farcaster" button
 * 2. Redirect to Neynar auth page
 * 3. On callback, verify FID and link/claim membership
 */
export function LinkFarcasterModal({
  isOpen,
  onClose,
  onSuccess,
  claimExistingMembership = false,
}: LinkFarcasterModalProps) {
  const { address } = useAccount();
  const { memberId, refresh: refreshMembership } = useMembershipStatus();

  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [step, setStep] = useState<"auth" | "confirm" | "success">("auth");
  const [farcasterUser, setFarcasterUser] = useState<SIWNUser | null>(null);
  const [existingMembership, setExistingMembership] = useState<{
    memberId: number;
    ensSubname: string;
  } | null>(null);

  // Check for callback on mount (returning from auth redirect)
  // Neynar returns: fid and signer_uuid on success
  useEffect(() => {
    if (typeof window === "undefined") return;
    if (!isOpen) return; // Only process when modal is open

    const urlParams = new URLSearchParams(window.location.search);
    const fid = urlParams.get("fid");
    const signerUuid = urlParams.get("signer_uuid");

    // Neynar auth success returns fid and signer_uuid
    if (fid && signerUuid) {
      console.log("[LinkFarcaster] Auth callback detected - FID:", fid, "signer_uuid:", signerUuid);
      // We're returning from auth - process the callback
      handleAuthCallback(parseInt(fid, 10));

      // Clean up URL
      const url = new URL(window.location.href);
      url.searchParams.delete("fid");
      url.searchParams.delete("signer_uuid");
      url.searchParams.delete("is_authenticated");
      window.history.replaceState({}, "", url.pathname);
    }
  }, [isOpen]);

  // Process auth callback
  const handleAuthCallback = async (fid: number) => {
    console.log("[LinkFarcaster] Processing auth callback for FID:", fid);
    setIsLoading(true);
    setError(null);

    // Get pending link data
    const pendingDataStr = localStorage.getItem(PENDING_LINK_KEY);
    if (!pendingDataStr) {
      setError("Session expired. Please try again.");
      setIsLoading(false);
      return;
    }

    const pendingData: PendingLinkData = JSON.parse(pendingDataStr);

    // Check if data is stale (older than 10 minutes)
    if (Date.now() - pendingData.timestamp > 10 * 60 * 1000) {
      localStorage.removeItem(PENDING_LINK_KEY);
      setError("Session expired. Please try again.");
      setIsLoading(false);
      return;
    }

    try {
      // Fetch user data
      const response = await fetch("/api/resolve-user", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ fids: [fid] }),
      });
      const userData = await response.json();

      if (!userData.users || userData.users.length === 0) {
        throw new Error("Failed to fetch user data");
      }

      const u = userData.users[0];
      const user: SIWNUser = {
        fid: u.fid,
        username: u.username,
        display_name: u.display_name,
        pfp_url: u.pfp_url,
        verified_addresses: u.verified_addresses,
      };

      setFarcasterUser(user);

      // Check membership status
      const checkResponse = await fetch(`/api/membership/check-fid?fid=${fid}`);
      const checkData = await checkResponse.json();

      if (pendingData.mode === "claim") {
        // CLAIM MODE
        if (!checkData.isMember) {
          setError(`No membership found for @${user.username}. You may need to become a member first.`);
          setIsLoading(false);
          return;
        }
        setExistingMembership({
          memberId: checkData.member.memberId,
          ensSubname: checkData.member.ensSubname,
        });
      } else {
        // LINK MODE
        if (checkData.isMember && checkData.member?.memberId !== pendingData.memberId) {
          setError(`This Farcaster account is already linked to member #${checkData.member.memberId}`);
          setIsLoading(false);
          return;
        }
      }

      setStep("confirm");
    } catch (err) {
      console.error("[LinkFarcaster] Error processing callback:", err);
      setError("Failed to process sign-in. Please try again.");
    } finally {
      setIsLoading(false);
    }
  };

  // Initiate auth redirect
  const initiateAuth = useCallback(() => {
    if (!NEYNAR_CLIENT_ID) {
      setError("Sign In With Farcaster is not configured. The NEXT_PUBLIC_NEYNAR_CLIENT_ID environment variable must be set.");
      return;
    }

    // Save pending link data
    const pendingData: PendingLinkData = {
      mode: claimExistingMembership ? "claim" : "link",
      address: address || "",
      memberId: memberId,
      timestamp: Date.now(),
    };
    localStorage.setItem(PENDING_LINK_KEY, JSON.stringify(pendingData));

    // Build redirect URL - return to current page
    const redirectUri = encodeURIComponent(window.location.origin + window.location.pathname);

    // Redirect to Neynar auth
    const authUrl = `https://app.neynar.com/login?client_id=${NEYNAR_CLIENT_ID}&redirect_uri=${redirectUri}`;

    console.log("[LinkFarcaster] Redirecting to:", authUrl);

    // Try multiple redirect methods for WebView compatibility
    // Some WebViews don't handle window.location.href well
    try {
      // Method 1: Standard location change
      window.location.href = authUrl;

      // Method 2: Fallback after short delay if still on same page
      setTimeout(() => {
        if (window.location.href.indexOf("neynar.com") === -1) {
          // Still on same page, try window.open as fallback
          const newWindow = window.open(authUrl, "_self");
          if (!newWindow) {
            // Popup blocked or failed, try top-level navigation
            window.top?.location?.assign(authUrl);
          }
        }
      }, 500);
    } catch (err) {
      console.error("[LinkFarcaster] Redirect failed:", err);
      setError("Failed to open sign-in page. Please try again or use a different browser.");
    }
  }, [address, memberId, claimExistingMembership]);

  // Claim existing membership by linking current wallet to it
  const claimMembership = async (fid: number, existingMemberId: number) => {
    setIsLoading(true);
    setError(null);

    // Get address from pending data
    const pendingDataStr = localStorage.getItem(PENDING_LINK_KEY);
    const pendingData: PendingLinkData | null = pendingDataStr ? JSON.parse(pendingDataStr) : null;
    const walletAddress = pendingData?.address || address;

    try {
      const response = await fetch("/api/link-address", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          address: walletAddress,
          memberId: existingMemberId,
          fid,
        }),
      });

      const data = await response.json();

      if (!response.ok || !data.success) {
        throw new Error(data.error || "Failed to claim membership");
      }

      // Clear pending data
      localStorage.removeItem(PENDING_LINK_KEY);

      setStep("success");
      refreshMembership();
      onSuccess?.();
    } catch (err) {
      console.error("Claim error:", err);
      setError(err instanceof Error ? err.message : "Failed to claim membership");
    } finally {
      setIsLoading(false);
    }
  };

  const linkFarcasterAccount = async (fid: number, fcUsername: string) => {
    setIsLoading(true);
    setError(null);

    // Get data from pending data
    const pendingDataStr = localStorage.getItem(PENDING_LINK_KEY);
    const pendingData: PendingLinkData | null = pendingDataStr ? JSON.parse(pendingDataStr) : null;
    const walletAddress = pendingData?.address || address;
    const memberIdToUse = pendingData?.memberId || memberId;

    try {
      const response = await fetch("/api/link-farcaster", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          address: walletAddress,
          memberId: memberIdToUse,
          fid,
          username: fcUsername,
        }),
      });

      const data = await response.json();

      if (!response.ok || !data.success) {
        throw new Error(data.error || "Failed to link account");
      }

      // Clear pending data
      localStorage.removeItem(PENDING_LINK_KEY);

      setStep("success");
      refreshMembership();
      onSuccess?.();
    } catch (err) {
      console.error("Link error:", err);
      setError(err instanceof Error ? err.message : "Failed to link account");
    } finally {
      setIsLoading(false);
    }
  };

  // User confirmed - proceed to link/claim
  const handleConfirm = async () => {
    if (!farcasterUser) return;

    const pendingDataStr = localStorage.getItem(PENDING_LINK_KEY);
    const pendingData: PendingLinkData | null = pendingDataStr ? JSON.parse(pendingDataStr) : null;
    const isClaimMode = pendingData?.mode === "claim" || claimExistingMembership;

    if (isClaimMode && existingMembership) {
      await claimMembership(farcasterUser.fid, existingMembership.memberId);
    } else {
      await linkFarcasterAccount(farcasterUser.fid, farcasterUser.username);
    }
  };

  const handleClose = () => {
    setError(null);
    setStep("auth");
    setFarcasterUser(null);
    setExistingMembership(null);
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 bg-black/95 z-[9999] flex items-center justify-center p-4 safe-area-inset"
      style={{ paddingTop: 'max(1rem, env(safe-area-inset-top))', paddingBottom: 'max(1rem, env(safe-area-inset-bottom))' }}
      onClick={handleClose}
    >
      <div
        className="bg-[#0a0a0a] border border-purple-500/30 rounded-xl max-w-sm w-full overflow-hidden max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 py-3 border-b border-purple-500/20 flex items-center justify-between bg-purple-500/5">
          <div className="flex items-center gap-2">
            <FarcasterIcon size={20} className="text-purple-400" />
            <H4 className="text-purple-400 font-mono">
              {claimExistingMembership ? "Claim Membership" : "Link Farcaster"}
            </H4>
          </div>
          <button
            onClick={handleClose}
            className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors"
          >
            ✕
          </button>
        </div>

        {/* Content */}
        <div className="p-4">
          {step === "auth" && (
            <>
              <P className="text-gray-300 font-mono text-sm mb-4">
                {claimExistingMembership
                  ? "Already a member on Farcaster? Sign in to link this wallet to your existing membership."
                  : "Sign in with your Farcaster account to link it to your membership."}
              </P>

              {/* Sign in button - always show, will redirect to Neynar */}
              <button
                onClick={initiateAuth}
                disabled={isLoading}
                className="w-full py-3 px-4 rounded-xl bg-purple-600 hover:bg-purple-500 disabled:opacity-50 text-white font-mono font-bold transition-colors flex items-center justify-center gap-3 mb-4"
              >
                <svg width="24" height="24" viewBox="0 0 1000 1000" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <rect width="1000" height="1000" rx="200" fill="#855DCD"/>
                  <path d="M257.778 155.556H742.222V844.444H671.111V528.889H670.414C662.554 441.677 589.258 373.333 500 373.333C410.742 373.333 337.446 441.677 329.586 528.889H328.889V844.444H257.778V155.556Z" fill="white"/>
                  <path d="M128.889 253.333L157.778 351.111H182.222V746.667C169.949 746.667 160 756.616 160 768.889V795.556H155.556C143.283 795.556 133.333 805.505 133.333 817.778V844.444H382.222V817.778C382.222 805.505 372.273 795.556 360 795.556H355.556V768.889C355.556 756.616 345.606 746.667 333.333 746.667H306.667V253.333H128.889Z" fill="white"/>
                  <path d="M675.556 746.667C663.283 746.667 653.333 756.616 653.333 768.889V795.556H648.889C636.616 795.556 626.667 805.505 626.667 817.778V844.444H875.556V817.778C875.556 805.505 865.606 795.556 853.333 795.556H848.889V768.889C848.889 756.616 838.939 746.667 826.667 746.667V351.111H851.111L880 253.333H702.222V746.667H675.556Z" fill="white"/>
                </svg>
                <span>Sign in with Farcaster</span>
              </button>

              {isLoading && (
                <div className="text-center py-2">
                  <P className="text-purple-400 font-mono text-sm">
                    Verifying your account...
                  </P>
                </div>
              )}

              {error && (
                <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30 mb-4">
                  <P className="text-red-400 font-mono text-sm">{error}</P>
                </div>
              )}

              <Small className="text-gray-500 font-mono block text-center">
                You&apos;ll be redirected to verify your Farcaster account
              </Small>
            </>
          )}

          {step === "confirm" && farcasterUser && (
            <>
              <P className="text-gray-300 font-mono text-sm mb-4">
                ✓ Verified! Ready to link this account?
              </P>

              {/* User Card */}
              <div className="p-4 rounded-lg bg-purple-500/10 border border-purple-500/30 mb-4">
                <div className="flex items-center gap-4">
                  {farcasterUser.pfp_url ? (
                    <img
                      src={farcasterUser.pfp_url}
                      alt={farcasterUser.username}
                      className="w-16 h-16 rounded-full border-2 border-purple-500/50"
                    />
                  ) : (
                    <div className="w-16 h-16 rounded-full bg-purple-500/20 flex items-center justify-center border-2 border-purple-500/50">
                      <span className="text-purple-400 font-mono text-xl">
                        {(farcasterUser.username || '?')[0].toUpperCase()}
                      </span>
                    </div>
                  )}
                  <div className="flex-1">
                    <P className="text-white font-mono font-bold text-lg">
                      {farcasterUser.display_name || farcasterUser.username}
                    </P>
                    <P className="text-purple-400 font-mono text-base">
                      @{farcasterUser.username}
                    </P>
                    <Small className="text-gray-500 font-mono block mt-1">
                      FID #{farcasterUser.fid}
                    </Small>
                  </div>
                </div>
                {/* Show existing membership in claim mode */}
                {existingMembership && (
                  <div className="mt-3 pt-3 border-t border-purple-500/20">
                    <Small className="text-[#00ff00] font-mono flex items-center gap-2">
                      <span>✓</span>
                      <span>
                        Member #{existingMembership.memberId} •{" "}
                        {existingMembership.ensSubname}
                      </span>
                    </Small>
                  </div>
                )}
              </div>

              {error && (
                <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30 mb-4">
                  <P className="text-red-400 font-mono text-sm">{error}</P>
                </div>
              )}

              <div className="flex gap-2">
                <button
                  onClick={() => {
                    setStep("auth");
                    setFarcasterUser(null);
                    setExistingMembership(null);
                    setError(null);
                  }}
                  className="flex-1 py-3 rounded-lg bg-[#1a1a1a] text-gray-400 font-mono hover:bg-[#222] transition-colors"
                >
                  Back
                </button>
                <button
                  onClick={handleConfirm}
                  disabled={isLoading}
                  className="flex-1 py-3 rounded-lg bg-purple-500 text-white font-mono font-bold hover:bg-purple-400 disabled:opacity-50 transition-colors"
                >
                  {isLoading
                    ? "Linking..."
                    : existingMembership
                      ? "Claim Membership"
                      : "Link Account"}
                </button>
              </div>
            </>
          )}

          {step === "success" && farcasterUser && (
            <div className="text-center py-4">
              <div className="mb-4 flex justify-center"><CheckCircleIcon size={48} className="text-purple-400" /></div>
              <H4 className="text-purple-400 font-mono mb-2">
                {existingMembership
                  ? "Membership Claimed!"
                  : "Account Linked!"}
              </H4>
              <P className="text-gray-300 font-mono text-sm mb-4">
                {existingMembership
                  ? `Your wallet is now linked to your membership as @${farcasterUser.username}.`
                  : `Your Farcaster account @${farcasterUser.username} is now linked to your membership.`}
              </P>
              <div className="p-3 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 mb-4">
                <Small className="text-[#00ff00] font-mono">
                  {existingMembership
                    ? `Welcome back! You're member #${existingMembership.memberId}.`
                    : `You can now access Net Library from the Farcaster Mini App with the same member #${memberId}!`}
                </Small>
              </div>
              <button
                onClick={handleClose}
                className="w-full py-3 rounded-lg bg-purple-500 text-white font-mono font-bold hover:bg-purple-400 transition-colors"
              >
                Done
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
src/features/app/components/link-to-net-modal.tsx
"use client";

import { useState, useEffect } from "react";
import { P, Small, H4 } from "@neynar/ui";

interface LinkToNetModalProps {
  isOpen: boolean;
  onClose: () => void;
  address: string;
  fid?: number; // For cross-platform sync
  onSave: (url: string, label: string) => void;
  existingLink?: { url: string; label: string } | null;
}

// Validate Net Protocol URL
function isValidNetProtocolUrl(url: string): boolean {
  if (!url.trim()) return false;
  try {
    const parsed = new URL(url);
    const validHosts = [
      "netprotocol.app",
      "www.netprotocol.app",
      "storedon.net",
      "www.storedon.net",
    ];
    return validHosts.some(
      (host) => parsed.hostname === host || parsed.hostname.endsWith(`.${host}`)
    );
  } catch {
    return false;
  }
}

export function LinkToNetModal({
  isOpen,
  onClose,
  address,
  fid,
  onSave,
  existingLink,
}: LinkToNetModalProps) {
  const [url, setUrl] = useState(existingLink?.url || "");
  const [label, setLabel] = useState(existingLink?.label || "");
  const [error, setError] = useState<string | null>(null);
  const [isSaving, setIsSaving] = useState(false);

  // Reset form when modal opens
  useEffect(() => {
    if (isOpen) {
      setUrl(existingLink?.url || "");
      setLabel(existingLink?.label || "");
      setError(null);
    }
  }, [isOpen, existingLink]);

  const isUrlValid = isValidNetProtocolUrl(url);
  const isLabelValid = label.trim().length > 0 && label.trim().length <= 30;
  const canSave = isUrlValid && isLabelValid && !isSaving;

  const handleSave = async () => {
    if (!canSave) return;

    // Validate URL one more time
    if (!isValidNetProtocolUrl(url)) {
      setError("Please enter a valid Net Protocol link (netprotocol.app or storedon.net)");
      return;
    }

    setIsSaving(true);
    setError(null);

    try {
      const response = await fetch("/api/user-net-link", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          address,
          fid, // Include FID for cross-platform sync
          url: url.trim(),
          label: label.trim(),
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        setError(data.error || "Failed to save link");
        return;
      }

      onSave(url.trim(), label.trim());
      onClose();
    } catch {
      setError("Failed to save link. Please try again.");
    } finally {
      setIsSaving(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="w-full max-w-sm bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 py-3 border-b border-[#00ff00]/30 flex items-center justify-between bg-[#00ff00]/5">
          <H4 className="text-[#00ff00] font-mono">Link to Net</H4>
          <button
            onClick={onClose}
            className="w-7 h-7 rounded-full bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white hover:bg-[#222] transition-colors"
          >
            ✕
          </button>
        </div>

        {/* Content */}
        <div className="p-4 space-y-4">
          <P className="text-gray-400 font-mono text-sm">
            Add a link to your Net Protocol page that will appear on your library card.
          </P>

          {/* URL Input */}
          <div className="space-y-1.5">
            <label className="text-[10px] font-mono text-[#00ff00] uppercase tracking-wider">
              Insert Net Page Link
            </label>
            <input
              type="url"
              value={url}
              onChange={(e) => {
                setUrl(e.target.value);
                setError(null);
              }}
              placeholder="https://netprotocol.app/..."
              className="w-full px-3 py-2.5 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm placeholder-gray-600 focus:outline-none focus:border-[#00ff00] transition-colors"
            />
            {url && !isUrlValid && (
              <Small className="text-red-400 font-mono">
                Enter a valid Net Protocol link
              </Small>
            )}
          </div>

          {/* Label Input */}
          <div className="space-y-1.5">
            <label className="text-[10px] font-mono text-[#00ff00] uppercase tracking-wider">
              Custom Link Label
            </label>
            <input
              type="text"
              value={label}
              onChange={(e) => {
                if (e.target.value.length <= 30) {
                  setLabel(e.target.value);
                }
              }}
              placeholder="My Net Page"
              className="w-full px-3 py-2.5 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm placeholder-gray-600 focus:outline-none focus:border-[#00ff00] transition-colors"
            />
            <div className="flex justify-between">
              {label && !isLabelValid && (
                <Small className="text-red-400 font-mono">
                  Label required (max 30 chars)
                </Small>
              )}
              <Small className="text-gray-600 font-mono ml-auto">
                {label.length}/30
              </Small>
            </div>
          </div>

          {/* Error Message */}
          {error && (
            <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30">
              <Small className="text-red-400 font-mono">{error}</Small>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-4 py-3 border-t border-[#00ff00]/30 bg-black/50">
          <button
            onClick={handleSave}
            disabled={!canSave}
            className={`w-full py-2.5 rounded-lg font-mono text-sm uppercase tracking-wider transition-all ${
              canSave
                ? "bg-[#00ff00] text-black hover:shadow-[0_0_20px_rgba(0,255,0,0.5)]"
                : "bg-gray-700 text-gray-500 cursor-not-allowed"
            }`}
          >
            {isSaving ? "Saving..." : "Save"}
          </button>
        </div>
      </div>
    </div>
  );
}
src/features/app/components/media-type-filter.tsx
"use client";

import { useState } from "react";
import type { ContentMediaType } from "@/features/app/types";

// Social platform type (matches SocialPlatform from social-receipt-upload)
export type SocialPlatformFilter = "farcaster" | "twitter" | "youtube" | "instagram" | "tiktok" | "reddit" | "bluesky" | "threads" | "linkedin" | "paragraph";

// Media type hierarchy
export type MediaTypeFilter =
  | "all"           // Everything
  | "documents"     // All documents
  | "documents-pdf" // PDFs only
  | "documents-text"// Text files (txt, md, etc.)
  | "documents-other" // Other readable (epub, etc.)
  | "media"         // All media
  | "media-video"   // Video files
  | "media-audio"   // Audio files
  | "media-other"   // Images, gifs, other
  | "social"        // All social receipts
  | `social-${SocialPlatformFilter}`; // Platform-specific social receipts

interface MediaTypeFilterProps {
  selectedFilter: MediaTypeFilter;
  onSelect: (filter: MediaTypeFilter) => void;
  counts?: {
    all: number;
    documents: number;
    documentsPdf: number;
    documentsText: number;
    documentsOther: number;
    media: number;
    mediaVideo: number;
    mediaAudio: number;
    mediaOther: number;
    social: number;
    socialFarcaster: number;
    socialTwitter: number;
    socialYoutube: number;
    socialInstagram: number;
    socialTiktok: number;
    socialReddit: number;
    socialBluesky: number;
    socialThreads: number;
    socialLinkedin: number;
  };
}

// Map ContentMediaType to our filter categories
export function getMediaFilterForType(mediaType: ContentMediaType | undefined): MediaTypeFilter {
  switch (mediaType) {
    case "pdf":
      return "documents-pdf";
    case "text":
      return "documents-text";
    case "video":
      return "media-video";
    case "audio":
      return "media-audio";
    case "image":
      return "media-other";
    case "unknown":
    default:
      // Unknown types go to documents-other by default
      return "documents-other";
  }
}

// Check if a book matches a filter (basic version for non-social content)
export function matchesMediaFilter(
  mediaType: ContentMediaType | undefined,
  filter: MediaTypeFilter
): boolean {
  if (filter === "all") return true;

  // Social filters never match non-social content in basic check
  if (filter === "social" || filter.startsWith("social-")) {
    return false;
  }

  const bookFilter = getMediaFilterForType(mediaType);

  // Exact match
  if (bookFilter === filter) return true;

  // Parent category match
  if (filter === "documents") {
    return bookFilter.startsWith("documents-");
  }
  if (filter === "media") {
    return bookFilter.startsWith("media-");
  }

  return false;
}

// Extended check that includes social receipt detection
export function matchesMediaFilterWithSocial(
  mediaType: ContentMediaType | undefined,
  filter: MediaTypeFilter,
  isSocialReceipt?: boolean,
  socialPlatform?: SocialPlatformFilter
): boolean {
  if (filter === "all") return true;

  // Handle social receipt filtering
  if (isSocialReceipt) {
    // Social receipts only match social filters (and "all")
    if (filter === "social") return true;
    if (filter.startsWith("social-") && socialPlatform) {
      return filter === `social-${socialPlatform}`;
    }
    // Social receipts don't show in docs/media filters
    return false;
  }

  // Non-social content doesn't match social filters
  if (filter === "social" || filter.startsWith("social-")) {
    return false;
  }

  // Standard media type filtering
  const bookFilter = getMediaFilterForType(mediaType);

  // Exact match
  if (bookFilter === filter) return true;

  // Parent category match
  if (filter === "documents") {
    return bookFilter.startsWith("documents-");
  }
  if (filter === "media") {
    return bookFilter.startsWith("media-");
  }

  return false;
}

export function MediaTypeFilterBar({ selectedFilter, onSelect, counts }: MediaTypeFilterProps) {
  const [expandedSection, setExpandedSection] = useState<"documents" | "media" | "social" | null>(null);

  // Main tabs (compact, no emojis)
  const mainTabs: { id: MediaTypeFilter; label: string }[] = [
    { id: "all", label: "All" },
    { id: "documents", label: "Docs" },
    { id: "media", label: "Media" },
    { id: "social", label: "Social" },
  ];

  // Sub-tabs for documents (compact, no emojis)
  const documentSubTabs: { id: MediaTypeFilter; label: string }[] = [
    { id: "documents", label: "All" },
    { id: "documents-pdf", label: "PDF" },
    { id: "documents-text", label: "Text" },
    { id: "documents-other", label: "Other" },
  ];

  // Sub-tabs for media (compact, no emojis)
  const mediaSubTabs: { id: MediaTypeFilter; label: string }[] = [
    { id: "media", label: "All" },
    { id: "media-video", label: "Video" },
    { id: "media-audio", label: "Audio" },
    { id: "media-other", label: "Image" },
  ];

  // Sub-tabs for social platforms (compact labels, no emojis to fit on one line)
  const socialSubTabs: { id: MediaTypeFilter; label: string }[] = [
    { id: "social", label: "All" },
    { id: "social-farcaster", label: "FC" },
    { id: "social-twitter", label: "X" },
    { id: "social-youtube", label: "YT" },
    { id: "social-instagram", label: "IG" },
    { id: "social-tiktok", label: "TT" },
    { id: "social-reddit", label: "RD" },
    { id: "social-bluesky", label: "BS" },
    { id: "social-threads", label: "TH" },
    { id: "social-linkedin", label: "LI" },
  ];

  const handleMainTabClick = (tabId: MediaTypeFilter) => {
    if (tabId === "documents") {
      setExpandedSection(expandedSection === "documents" ? null : "documents");
      onSelect("documents");
    } else if (tabId === "media") {
      setExpandedSection(expandedSection === "media" ? null : "media");
      onSelect("media");
    } else if (tabId === "social") {
      setExpandedSection(expandedSection === "social" ? null : "social");
      onSelect("social");
    } else {
      setExpandedSection(null);
      onSelect(tabId);
    }
  };

  const handleSubTabClick = (tabId: MediaTypeFilter) => {
    onSelect(tabId);
  };

  // Determine if a main tab is active (including when sub-tab is selected)
  const isMainTabActive = (tabId: MediaTypeFilter) => {
    if (tabId === "all") return selectedFilter === "all";
    if (tabId === "documents") return selectedFilter.startsWith("documents");
    if (tabId === "media") return selectedFilter.startsWith("media");
    if (tabId === "social") return selectedFilter.startsWith("social");
    return selectedFilter === tabId;
  };

  // Get count for a tab
  const getCount = (tabId: MediaTypeFilter): number | undefined => {
    if (!counts) return undefined;
    switch (tabId) {
      case "all": return counts.all;
      case "documents": return counts.documents;
      case "documents-pdf": return counts.documentsPdf;
      case "documents-text": return counts.documentsText;
      case "documents-other": return counts.documentsOther;
      case "media": return counts.media;
      case "media-video": return counts.mediaVideo;
      case "media-audio": return counts.mediaAudio;
      case "media-other": return counts.mediaOther;
      case "social": return counts.social;
      case "social-farcaster": return counts.socialFarcaster;
      case "social-twitter": return counts.socialTwitter;
      case "social-youtube": return counts.socialYoutube;
      case "social-instagram": return counts.socialInstagram;
      case "social-tiktok": return counts.socialTiktok;
      case "social-reddit": return counts.socialReddit;
      case "social-bluesky": return counts.socialBluesky;
      case "social-threads": return counts.socialThreads;
      case "social-linkedin": return counts.socialLinkedin;
      default: return undefined;
    }
  };

  return (
    <div className="space-y-2 overflow-hidden">
      {/* Main tabs */}
      <div className="flex gap-1">
        {mainTabs.map((tab) => {
          const isActive = isMainTabActive(tab.id);
          const count = getCount(tab.id);
          const isExpandable = tab.id === "documents" || tab.id === "media" || tab.id === "social";
          const isExpanded = (tab.id === "documents" && expandedSection === "documents") ||
                            (tab.id === "media" && expandedSection === "media") ||
                            (tab.id === "social" && expandedSection === "social");

          return (
            <button
              key={tab.id}
              onClick={() => handleMainTabClick(tab.id)}
              className={`flex-1 px-2 py-1.5 rounded-md text-xs font-mono transition-all flex items-center justify-center gap-1 ${
                isActive
                  ? "bg-[#00ff00] text-black"
                  : "bg-[#1a1a1a] text-gray-400 hover:bg-[#222] hover:text-[#00ff00]"
              }`}
            >
              <span>{tab.label}</span>
              {count !== undefined && (
                <span className={`text-[9px] ${isActive ? "text-black/60" : "text-gray-500"}`}>
                  ({count})
                </span>
              )}
              {isExpandable && (
                <span className={`text-[9px] transition-transform ${isExpanded ? "rotate-180" : ""}`}>
                  ▼
                </span>
              )}
            </button>
          );
        })}
      </div>

      {/* Sub-tabs for Documents */}
      {expandedSection === "documents" && (
        <div className="flex gap-1.5 overflow-x-auto pb-1 scrollbar-hide min-w-0 w-full">
          {documentSubTabs.map((tab) => {
            const isActive = selectedFilter === tab.id;
            const count = getCount(tab.id);

            return (
              <button
                key={tab.id}
                onClick={() => handleSubTabClick(tab.id)}
                className={`shrink-0 px-2 py-1 rounded text-[10px] font-mono transition-all ${
                  isActive
                    ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/50"
                    : "bg-[#0a0a0a] text-gray-400 border border-[#1a1a1a] hover:border-[#00ff00]/30 hover:text-[#00ff00]/70"
                }`}
              >
                {tab.label}
                {count !== undefined && (
                  <span className={`ml-0.5 ${isActive ? "text-[#00ff00]/60" : "text-gray-500"}`}>
                    ({count})
                  </span>
                )}
              </button>
            );
          })}
        </div>
      )}

      {/* Sub-tabs for Media - white theme to match media border color */}
      {expandedSection === "media" && (
        <div className="flex gap-1.5 overflow-x-auto pb-1 scrollbar-hide min-w-0 w-full">
          {mediaSubTabs.map((tab) => {
            const isActive = selectedFilter === tab.id;
            const count = getCount(tab.id);

            return (
              <button
                key={tab.id}
                onClick={() => handleSubTabClick(tab.id)}
                className={`shrink-0 px-2 py-1 rounded text-[10px] font-mono transition-all ${
                  isActive
                    ? "bg-white/20 text-white border border-white/50"
                    : "bg-[#0a0a0a] text-gray-400 border border-[#1a1a1a] hover:border-white/30 hover:text-white/70"
                }`}
              >
                {tab.label}
                {count !== undefined && (
                  <span className={`ml-0.5 ${isActive ? "text-white/60" : "text-gray-500"}`}>
                    ({count})
                  </span>
                )}
              </button>
            );
          })}
        </div>
      )}

      {/* Sub-tabs for Social - scrollable row, neon green theme */}
      {expandedSection === "social" && (
        <div className="flex gap-1 overflow-x-auto pb-1 scrollbar-hide min-w-0 w-full">
          {socialSubTabs.map((tab) => {
            const isActive = selectedFilter === tab.id;
            const count = getCount(tab.id);
            // Only show platforms that have content
            if (tab.id !== "social" && count === 0) return null;

            return (
              <button
                key={tab.id}
                onClick={() => handleSubTabClick(tab.id)}
                className={`shrink-0 px-2 py-1 rounded text-[10px] font-mono transition-all ${
                  isActive
                    ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/50"
                    : "bg-[#0a0a0a] text-gray-400 border border-[#1a1a1a] hover:border-[#00ff00]/30 hover:text-[#00ff00]/70"
                }`}
              >
                {tab.label}
                {count !== undefined && count > 0 && (
                  <span className={`ml-0.5 ${isActive ? "text-[#00ff00]/60" : "text-gray-500"}`}>
                    ({count})
                  </span>
                )}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}
src/features/app/components/member-directory.tsx
"use client";

import { useState, useEffect } from "react";
import { P, Small, H4 } from "@neynar/ui";
import { BadgeCheck } from "lucide-react";
import { DownloadIcon, LinkIcon, WarningIcon, CheckCircleIcon, ClipboardIcon, ParachuteIcon, ContactBookIcon, UserIcon, SaveIcon, FarcasterIcon, BaseIcon, WebIcon } from "@/components/icons/net-library-icons";
import { safeOpenUrl, openInExternalBrowser } from "@/lib/app-mode";
import type { MemberEntry, SignupPlatform } from "@/lib/net-protocol";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { AirdropModal } from "./airdrop-modal";
import { UserLibraryCardModal } from "./user-library-card-modal";

// Pagination constants
const ITEMS_PER_PAGE = 10;

interface MemberDirectoryProps {
  isOpen: boolean;
  onClose: () => void;
}

// Extend MemberEntry with resolved pfp and net link
export interface MemberWithPfp extends MemberEntry {
  pfpUrl?: string;
  netLink?: { url: string; label: string } | null;
  signupPlatform?: SignupPlatform;
  isAgent?: boolean;
  agentId?: string;
  // Display name vs Farcaster handle
  displayName?: string;          // Display name (e.g., "Cheryl", "GEAUX")
  farcasterUsername?: string;    // Farcaster handle (e.g., "cherylfromnet", "geaux")
  // ERC-8004 Base Identity Registry
  erc8004Verified?: boolean;     // True if verified on ERC-8004
  erc8004TokenId?: number;       // Token ID on the registry
}

// Grouped member - one entry per unique FID/user with all their member numbers
interface GroupedMember {
  fid: number | undefined;
  username: string | undefined;       // Legacy: kept for compatibility, prefer displayName
  displayName: string | undefined;    // Display name (e.g., "Cheryl", "GEAUX") - PRIMARY
  farcasterUsername: string | undefined; // Farcaster handle (e.g., "cherylfromnet")
  address: string; // Primary address (from first/lowest member number) - CANONICAL for airdrops
  pfpUrl?: string;
  netLink?: { url: string; label: string } | null;
  memberNumbers: number[]; // All member IDs for this user
  ensSubnames: string[]; // All ENS subnames
  primaryMemberId: number; // The lowest member ID (displayed prominently)
  signupPlatforms: (SignupPlatform | undefined)[]; // Platform for each member ID
  canonicalPlatform: SignupPlatform | undefined; // Platform of first membership (determines airdrop address)
  isAgent?: boolean; // True if this is a registered AI agent
  agentId?: string;  // The agent's registered ID
  // ERC-8004 verification
  erc8004Verified?: boolean; // True if verified on ERC-8004 Base Identity Registry
}

// Shorten address for display
function shortenAddress(address: string): string {
  return `${address.slice(0, 6)}...${address.slice(-4)}`;
}

// Group members by FID (or by address if no FID)
function groupMembersByFid(members: MemberWithPfp[]): GroupedMember[] {
  const grouped = new Map<string, GroupedMember>();

  // Sort by memberId first so lowest ID becomes primary
  const sortedMembers = [...members].sort((a, b) => a.memberId - b.memberId);

  for (const member of sortedMembers) {
    // Use FID as key if available, otherwise use lowercase address
    const key = member.fid ? `fid:${member.fid}` : `addr:${(member.address || '').toLowerCase()}`;

    if (grouped.has(key)) {
      // Add to existing group
      const existing = grouped.get(key)!;
      existing.memberNumbers.push(member.memberId);
      existing.ensSubnames.push(member.ensSubname);
      existing.signupPlatforms.push(member.signupPlatform);
      // Keep net link if we find one
      if (!existing.netLink && member.netLink) {
        existing.netLink = member.netLink;
      }
    } else {
      // Create new group - first membership determines canonical platform
      // Legacy members (no signupPlatform) default to Farcaster since Base App came later
      const inferredPlatform: SignupPlatform = member.signupPlatform || "farcaster";
      grouped.set(key, {
        fid: member.fid,
        username: member.username,
        // Display name priority: member's display name field, or resolved displayName, or username
        displayName: member.displayName || member.username,
        // Farcaster username: stored farcasterUsername, or if username looks like a handle use that
        farcasterUsername: member.farcasterUsername,
        address: member.address,
        pfpUrl: member.pfpUrl,
        netLink: member.netLink,
        memberNumbers: [member.memberId],
        ensSubnames: [member.ensSubname],
        primaryMemberId: member.memberId,
        signupPlatforms: [member.signupPlatform],
        canonicalPlatform: inferredPlatform,
        isAgent: member.isAgent,
        agentId: member.agentId,
        erc8004Verified: member.erc8004Verified,
      });
    }
  }

  // Convert to array and sort by primary member ID
  return Array.from(grouped.values()).sort((a, b) => a.primaryMemberId - b.primaryMemberId);
}

export function MemberDirectory({ isOpen, onClose }: MemberDirectoryProps) {
  const [members, setMembers] = useState<MemberWithPfp[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showAirdropModal, setShowAirdropModal] = useState(false);
  const [selectedMember, setSelectedMember] = useState<MemberWithPfp | null>(null);
  const [selectedGroupedMember, setSelectedGroupedMember] = useState<GroupedMember | null>(null);
  const [showUnlinkedInfo, setShowUnlinkedInfo] = useState(false);
  const [showAirdropAddressInfo, setShowAirdropAddressInfo] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [isDownloadingCsv, setIsDownloadingCsv] = useState(false);
  const [showCsvModal, setShowCsvModal] = useState(false);
  const [csvCopied, setCsvCopied] = useState(false);

  // Check if current user is a member
  const { isMember } = useMembershipStatus();

  // Group members by FID for display
  const groupedMembers = groupMembersByFid(members);
  const uniqueUserCount = groupedMembers.length;

  // Count members by signup platform (canonical platform for each user)
  const platformCounts = groupedMembers.reduce(
    (acc, member) => {
      if (member.canonicalPlatform === "farcaster") {
        acc.farcaster += 1;
      } else if (member.canonicalPlatform === "web") {
        acc.web += 1;
      } else {
        acc.baseApp += 1;
      }
      return acc;
    },
    { farcaster: 0, baseApp: 0, web: 0 }
  );

  // Pagination
  const totalPages = Math.ceil(groupedMembers.length / ITEMS_PER_PAGE);
  const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
  const endIndex = startIndex + ITEMS_PER_PAGE;
  const paginatedMembers = groupedMembers.slice(startIndex, endIndex);

  // Reset to page 1 when modal opens
  useEffect(() => {
    if (isOpen) {
      setCurrentPage(1);
    }
  }, [isOpen]);

  // Generate CSV content string
  const generateCsvContent = () => {
    const headers = ["member_id", "address", "username", "fid", "signup_platform", "ens_subname"];
    const rows = members.map((m) => [
      m.memberId,
      m.address,
      m.username || "",
      m.fid || "",
      m.signupPlatform || "farcaster",
      m.ensSubname || "",
    ]);

    return [
      headers.join(","),
      ...rows.map((row) => row.map((cell) => `"${cell}"`).join(",")),
    ].join("\n");
  };

  // Download CSV file (member-gated)
  // Opens in external browser for proper download handling on mobile
  const downloadMembersCsv = async () => {
    if (!isMember) return;

    setIsDownloadingCsv(true);
    try {
      // Build full URL for external browser
      const csvUrl = `${window.location.origin}/api/member-registry/csv`;
      // Use openInExternalBrowser to bypass in-app browser limitations
      await openInExternalBrowser(csvUrl);
      setShowCsvModal(false);
    } catch (err) {
      console.error("Failed to download CSV:", err);
      alert("Unable to download CSV. Please try again.");
    } finally {
      setIsDownloadingCsv(false);
    }
  };

  // Copy CSV to clipboard (member-gated)
  const copyMembersCsv = async () => {
    if (!isMember) return;

    try {
      const csvContent = generateCsvContent();
      await navigator.clipboard.writeText(csvContent);
      setCsvCopied(true);
      setTimeout(() => setCsvCopied(false), 2000);
    } catch (err) {
      console.error("Failed to copy CSV:", err);
      alert("Unable to copy to clipboard. Please try again.");
    }
  };

  // Open Farcaster profile
  const openProfile = async (username: string) => {
    const profileUrl = `https://warpcast.com/${username}`;
    await safeOpenUrl(profileUrl);
  };

  // Open Net link
  const openNetLink = async (url: string) => {
    await safeOpenUrl(url);
  };

  // Fetch members when modal opens
  useEffect(() => {
    if (!isOpen) return;

    async function fetchMembers() {
      setIsLoading(true);
      setError(null);

      try {
        // Fetch full registry from member-registry endpoint
        const response = await fetch("/api/member-registry");
        if (!response.ok) {
          throw new Error("Failed to fetch members");
        }
        const registry = await response.json();
        const memberList: MemberEntry[] = registry.members || [];

        // Resolve pfps - first try FIDs, then addresses for those without FIDs
        const membersWithFids = memberList.filter((m) => m.fid);
        const membersWithoutFids = memberList.filter((m) => !m.fid);

        const fidToPfp: Record<number, string> = {};
        const fidToDisplayName: Record<number, string> = {};
        const fidToUsername: Record<number, string> = {};
        const addressToPfp: Record<string, string> = {};
        // Store resolved FID and username for members without FID in registry
        const addressToFid: Record<string, number> = {};
        const addressToUsername: Record<string, string> = {};
        const addressToDisplayName: Record<string, string> = {};

        // Resolve by FID first
        if (membersWithFids.length > 0) {
          try {
            const fidsToResolve = membersWithFids.map((m) => m.fid as number);
            const pfpResponse = await fetch("/api/resolve-user", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ fids: fidsToResolve }),
            });

            if (pfpResponse.ok) {
              const pfpData = await pfpResponse.json();
              if (pfpData.users) {
                for (const user of pfpData.users) {
                  fidToPfp[user.fid] = user.pfp_url;
                  // Store display_name (e.g., "GEAUX") and username (e.g., "geaux")
                  if (user.display_name) {
                    fidToDisplayName[user.fid] = user.display_name;
                  }
                  if (user.username) {
                    fidToUsername[user.fid] = user.username;
                  }
                }
              }
            }
          } catch (pfpErr) {
            console.error("Failed to resolve pfps by FID:", pfpErr);
          }
        }

        // Resolve by address for members without FIDs (Neynar can find FID from address)
        if (membersWithoutFids.length > 0) {
          try {
            const addressesToResolve = membersWithoutFids.map((m) => m.address);
            const addrResponse = await fetch("/api/resolve-user", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({ addresses: addressesToResolve }),
            });

            if (addrResponse.ok) {
              const addrData = await addrResponse.json();
              if (addrData.users) {
                // Response format: { [address]: { username, pfpUrl, fid, displayName } }
                for (const [addr, userData] of Object.entries(addrData.users)) {
                  const user = userData as { pfpUrl?: string; fid?: number; username?: string; displayName?: string };
                  const lowerAddr = addr.toLowerCase();
                  if (user.pfpUrl) {
                    addressToPfp[lowerAddr] = user.pfpUrl;
                  }
                  // Also capture FID, username, and displayName for members without FID in registry
                  if (user.fid) {
                    addressToFid[lowerAddr] = user.fid;
                  }
                  if (user.username) {
                    addressToUsername[lowerAddr] = user.username;
                  }
                  if (user.displayName) {
                    addressToDisplayName[lowerAddr] = user.displayName;
                  }
                }
              }
            }
          } catch (addrErr) {
            console.error("Failed to resolve pfps by address:", addrErr);
          }
        }

        // Merge pfps, FIDs, usernames, and displayNames into members
        // For members with FID in registry, use registry data
        // For members without FID, try to resolve via Neynar address lookup
        const membersWithPfp = memberList.map((m) => {
          const lowerAddr = (m.address || '').toLowerCase();
          const resolvedFid = m.fid || addressToFid[lowerAddr];

          // For agents, username field IS the display name (e.g., "Cheryl")
          // For regular users, display name comes from Neynar API
          // farcasterUsername is the Farcaster handle (for linking)
          let displayName: string | undefined;
          let farcasterUsername: string | undefined;

          if (m.isAgent) {
            // Agent: username = display name, farcasterUsername = handle
            displayName = m.username;  // "Cheryl"
            farcasterUsername = m.farcasterUsername;  // "cherylfromnet"
          } else if (resolvedFid) {
            // Regular user with FID: get display name and username from Neynar
            displayName = fidToDisplayName[resolvedFid] || m.username;
            farcasterUsername = fidToUsername[resolvedFid] || m.username;
          } else {
            // Fallback for address-only resolution
            displayName = addressToDisplayName[lowerAddr] || m.username;
            farcasterUsername = addressToUsername[lowerAddr] || m.username;
          }

          // PFP priority: registry pfpUrl > FID-resolved > address-resolved
          let pfpUrl = m.pfpUrl;  // Check registry first
          if (!pfpUrl && resolvedFid) {
            pfpUrl = fidToPfp[resolvedFid];
          }
          if (!pfpUrl) {
            pfpUrl = addressToPfp[lowerAddr];
          }

          return {
            ...m,
            // Use registry FID, or resolved FID from address lookup
            fid: resolvedFid,
            // Keep original username for compatibility
            username: m.username || addressToUsername[lowerAddr],
            // Display name (e.g., "GEAUX", "Cheryl")
            displayName,
            // Farcaster handle (e.g., "geaux", "cherylfromnet")
            farcasterUsername,
            // PFP URL with priority chain
            pfpUrl,
          };
        });

        // Fetch net links for all members
        const membersWithLinks = await Promise.all(
          membersWithPfp.map(async (m) => {
            try {
              const linkRes = await fetch(`/api/user-net-link?address=${m.address}`);
              if (linkRes.ok) {
                const linkData = await linkRes.json();
                return { ...m, netLink: linkData.link || null };
              }
            } catch {
              // Ignore errors
            }
            return { ...m, netLink: null };
          })
        );

        setMembers(membersWithLinks);
      } catch (err) {
        setError(err instanceof Error ? err.message : "Failed to load members");
      } finally {
        setIsLoading(false);
      }
    }

    fetchMembers();
  }, [isOpen]);

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black z-50 flex flex-col">
      {/* Header */}
      <div className="shrink-0 px-4 py-3 border-b border-[#00ff00]/30 flex items-center justify-between bg-black">
        <div>
          <H4 className="text-[#00ff00] font-mono">Member Directory</H4>
          <Small className="text-gray-500 font-mono">
            {uniqueUserCount} member{uniqueUserCount !== 1 ? "s" : ""}
          </Small>
          {/* Platform breakdown - purple for Farcaster, blue for Base App, yellow for Web */}
          <div className="flex items-center gap-2 mt-0.5">
            <span className="text-purple-400 font-mono text-[11px]">
              ● {platformCounts.farcaster} FC
            </span>
            <span className="text-gray-600 text-[10px]">/</span>
            <span className="text-blue-400 font-mono text-[11px]">
              ● {platformCounts.baseApp} Base
            </span>
            <span className="text-gray-600 text-[10px]">/</span>
            <span className="text-yellow-400 font-mono text-[11px]">
              ● {platformCounts.web} Web
            </span>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {/* CSV Export - Member Only */}
          {isMember ? (
            <button
              onClick={() => setShowCsvModal(true)}
              disabled={isLoading}
              className="px-2 py-1.5 rounded-lg bg-[#0a0a0a] border border-[#00ff00]/20 text-[#00ff00] font-mono text-[10px] hover:bg-[#00ff00]/10 transition-colors disabled:opacity-50"
              title="Export member addresses"
            >
              <DownloadIcon size={12} className="inline mr-1" /> CSV
            </button>
          ) : (
            <button
              disabled
              className="px-2 py-1.5 rounded-lg bg-[#0a0a0a] border border-gray-700 text-gray-500 font-mono text-[10px] cursor-not-allowed"
              title="Members only: Export member addresses"
            >
              <DownloadIcon size={12} className="inline mr-1 opacity-50" /> CSV
            </button>
          )}
          <button
            onClick={() => setShowAirdropModal(true)}
            className="px-3 py-1.5 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] font-mono text-xs font-bold hover:bg-[#00ff00]/20 transition-colors flex items-center gap-1"
          >
            <ParachuteIcon size={14} /> AIRDROP
          </button>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors"
          >
            ✕
          </button>
        </div>
      </div>

      {/* Content */}
      <div className="flex-1 overflow-y-auto">
        {isLoading ? (
          <div className="flex flex-col items-center justify-center py-20">
            <ContactBookIcon size={40} className="text-[#00ff00] mb-4 animate-pulse" />
            <P className="text-[#00ff00] font-mono">Loading members...</P>
          </div>
        ) : error ? (
          <div className="flex flex-col items-center justify-center py-20">
            <WarningIcon size={40} className="text-red-400 mb-4" />
            <P className="text-red-400 font-mono mb-2">Failed to load members</P>
            <Small className="text-gray-500 font-mono">{error}</Small>
          </div>
        ) : groupedMembers.length === 0 ? (
          <div className="flex flex-col items-center justify-center py-20">
            <UserIcon size={40} className="text-gray-400 mb-4" />
            <P className="text-gray-400 font-mono">No members yet</P>
            <Small className="text-gray-500 font-mono">Be the first to join!</Small>
          </div>
        ) : (
          <div className="divide-y divide-[#1a1a1a]">
            {paginatedMembers.map((grouped) => {
              // Find the primary member entry for the library card modal
              const primaryMember = members.find(m => m.memberId === grouped.primaryMemberId);
              const _hasMultipleMemberships = grouped.memberNumbers.length > 1;

              // Determine ring color based on canonical platform (purple = FC, blue = Base, yellow = Web)
              // Override with orange if ERC-8004 verified agent
              const platform = grouped.canonicalPlatform;
              const is8004Verified = grouped.erc8004Verified && grouped.isAgent;

              const ringColor = is8004Verified
                ? "border-orange-500 hover:border-orange-400 hover:shadow-[0_0_10px_rgba(249,115,22,0.4)] ring-2 ring-orange-500"
                : platform === "farcaster"
                ? "border-purple-500 hover:border-purple-400 hover:shadow-[0_0_10px_rgba(168,85,247,0.4)]"
                : platform === "web"
                ? "border-yellow-500 hover:border-yellow-400 hover:shadow-[0_0_10px_rgba(234,179,8,0.4)]"
                : "border-blue-500 hover:border-blue-400 hover:shadow-[0_0_10px_rgba(59,130,246,0.4)]";
              const bgColor = is8004Verified
                ? "bg-orange-500/10"
                : platform === "farcaster" ? "bg-purple-500/10" : platform === "web" ? "bg-yellow-500/10" : "bg-blue-500/10";
              const textColor = is8004Verified
                ? "text-orange-400"
                : platform === "farcaster" ? "text-purple-400" : platform === "web" ? "text-yellow-400" : "text-blue-400";

              return (
                <div
                  key={grouped.fid ? `fid-${grouped.fid}` : `addr-${grouped.address}`}
                  className="flex items-center gap-3 px-4 py-2.5"
                >
                  {/* PFP or Member # Badge - Ring color shows canonical platform */}
                  <button
                    onClick={() => {
                      if (primaryMember) {
                        setSelectedMember(primaryMember);
                        setSelectedGroupedMember(grouped);
                      }
                    }}
                    className="shrink-0 focus:outline-none focus:ring-2 focus:ring-[#00ff00]/50 rounded-full"
                    title={`Airdrop goes to ${platform === "farcaster" ? "Farcaster" : platform === "web" ? "Web" : "Base App"} wallet`}
                  >
                    {grouped.pfpUrl ? (
                      <img
                        src={grouped.pfpUrl}
                        alt={grouped.username || `Member ${grouped.primaryMemberId}`}
                        className={`w-8 h-8 rounded-full border-2 object-cover transition-all cursor-pointer ${ringColor}`}
                      />
                    ) : (
                      <div className={`w-8 h-8 rounded-full flex items-center justify-center border-2 transition-all cursor-pointer ${bgColor} ${ringColor}`}>
                        <span className={`font-mono text-xs font-bold ${textColor}`}>
                          {grouped.primaryMemberId}
                        </span>
                      </div>
                    )}
                  </button>

                  {/* Member Info: display name, @handle, FID, member numbers, ENS subnames */}
                  <div className="flex-1 min-w-0">
                    {/* Row 1: Display Name + @handle + Agent badge */}
                    <div className="flex items-center gap-2 flex-wrap">
                      {/* Display Name - primary name (e.g., "GEAUX", "Cheryl") */}
                      {grouped.displayName ? (
                        <span className={`text-sm font-mono font-bold truncate ${
                          grouped.isAgent ? "text-[#B794F4]" : "text-white"
                        }`}>
                          {grouped.displayName}
                        </span>
                      ) : (
                        <span className={`text-sm font-mono truncate ${grouped.isAgent ? "text-[#B794F4]" : "text-white"}`}>
                          {shortenAddress(grouped.address)}
                        </span>
                      )}
                      {/* Farcaster handle link - secondary (e.g., @geaux, @cherylfromnet) */}
                      {grouped.farcasterUsername && (
                        <button
                          onClick={() => openProfile(grouped.farcasterUsername!)}
                          className={`text-[11px] font-mono truncate underline transition-colors ${
                            grouped.isAgent
                              ? "text-[#B794F4]/70 hover:text-[#B794F4]"
                              : "text-gray-400 hover:text-[#00ff00]"
                          }`}
                        >
                          @{grouped.farcasterUsername}
                        </button>
                      )}
                      {grouped.isAgent && (
                        <span className="inline-flex items-center gap-0.5 text-[8px] font-mono font-bold text-[#B794F4] bg-[#B794F4]/10 px-1 py-0.5 rounded border border-[#B794F4]/30">
                          AGENT
                          {grouped.erc8004Verified && (
                            <BadgeCheck className="w-3 h-3 text-orange-500" />
                          )}
                        </span>
                      )}
                      {grouped.fid && (
                        <span className="text-[10px] font-mono text-purple-400">
                          FID {grouped.fid}
                        </span>
                      )}
                    </div>
                    {/* Row 2: ENS subnames with member numbers - each on own line for users with multiple */}
                    <div className="flex flex-col gap-0.5 mt-0.5">
                      {grouped.ensSubnames.map((ens, idx) => {
                        const memberNum = grouped.memberNumbers[idx];
                        const memberPlatform = grouped.signupPlatforms[idx];
                        const colorClass = memberPlatform === "farcaster"
                          ? "text-purple-400"
                          : memberPlatform === "base-app"
                          ? "text-blue-400"
                          : memberPlatform === "web"
                          ? "text-yellow-400"
                          : "text-[#00ff00]";
                        const PlatformIcon = memberPlatform === "farcaster"
                          ? <FarcasterIcon size={10} className="text-purple-400" />
                          : memberPlatform === "base-app"
                          ? <BaseIcon size={10} className="text-blue-400" />
                          : memberPlatform === "web"
                          ? <WebIcon size={10} className="text-yellow-400" />
                          : null;
                        return (
                          <div key={memberNum} className="flex items-center gap-1.5">
                            <span className={`text-[10px] font-mono ${colorClass}`}>#{memberNum}</span>
                            <span className="text-[9px] font-mono text-[#00ff00]/60 truncate">{ens}</span>
                            {PlatformIcon}
                          </div>
                        );
                      })}
                    </div>
                  </div>

                  {/* LINKED or unlinked on right */}
                  {grouped.netLink ? (
                    <button
                      onClick={() => openNetLink(grouped.netLink!.url)}
                      className="text-[10px] text-[#00ff00] font-mono shrink-0 underline underline-offset-2 hover:text-[#00ff00]/80 transition-colors"
                    >
                      LINKED
                    </button>
                  ) : (
                    <button
                      onClick={() => setShowUnlinkedInfo(true)}
                      className="text-[10px] text-gray-500 font-mono shrink-0 hover:text-gray-400 transition-colors"
                    >
                      unlinked<sup className="text-[8px] ml-0.5">ⓘ</sup>
                    </button>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Footer with Pagination */}
      <div className="shrink-0 px-4 py-3 border-t border-[#00ff00]/30 bg-black space-y-3">
        {/* Pagination Controls - prominent and easy to tap */}
        {totalPages > 1 && (
          <div className="flex items-center justify-center gap-3">
            <button
              onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
              disabled={currentPage === 1}
              className="px-4 py-2 rounded-lg bg-[#0a0a0a] border border-[#00ff00]/30 text-[#00ff00] font-mono text-sm disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#00ff00]/10 transition-colors min-w-[80px]"
            >
              ← Prev
            </button>
            <div className="flex flex-col items-center">
              <span className="text-[#00ff00] font-mono text-sm font-bold">
                {currentPage} / {totalPages}
              </span>
              <span className="text-gray-500 font-mono text-[9px]">
                {startIndex + 1}-{Math.min(endIndex, groupedMembers.length)} of {groupedMembers.length}
              </span>
            </div>
            <button
              onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
              disabled={currentPage === totalPages}
              className="px-4 py-2 rounded-lg bg-[#0a0a0a] border border-[#00ff00]/30 text-[#00ff00] font-mono text-sm disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#00ff00]/10 transition-colors min-w-[80px]"
            >
              Next →
            </button>
          </div>
        )}

        {/* Info row */}
        <div className="flex items-center justify-center gap-2">
          <span className="text-[9px] text-gray-500 font-mono">
            Tap PFP to view library card
          </span>
          <span className="text-gray-700 text-[8px]">•</span>
          <button
            onClick={() => setShowAirdropAddressInfo(true)}
            className="text-[9px] font-mono text-gray-500 hover:text-gray-400"
          >
            <span className="inline-block w-2 h-2 rounded-full border border-purple-500 mr-0.5"></span>
            <span className="inline-block w-2 h-2 rounded-full border border-blue-500 mr-0.5"></span>
            <span className="inline-block w-2 h-2 rounded-full border border-yellow-500"></span>
            {" "}= airdrop wallet<sup className="text-[7px] ml-0.5">ⓘ</sup>
          </button>
        </div>
      </div>

      {/* Airdrop Modal */}
      <AirdropModal
        isOpen={showAirdropModal}
        onClose={() => setShowAirdropModal(false)}
        isMember={isMember}
        members={members}
      />

      {/* User Library Card Modal */}
      {selectedMember && (
        <UserLibraryCardModal
          isOpen={!!selectedMember}
          onClose={() => {
            setSelectedMember(null);
            setSelectedGroupedMember(null);
          }}
          member={selectedMember}
          allMemberships={selectedGroupedMember ? selectedGroupedMember.memberNumbers.map((memberId, idx) => ({
            memberId,
            address: selectedGroupedMember.address,
            ensSubname: selectedGroupedMember.ensSubnames[idx],
            signupPlatform: selectedGroupedMember.signupPlatforms[idx],
          })) : undefined}
        />
      )}

      {/* Unlinked Info Modal */}
      {showUnlinkedInfo && (
        <div
          className="fixed inset-0 bg-black/80 z-[70] flex items-center justify-center p-4"
          onClick={() => setShowUnlinkedInfo(false)}
        >
          <div
            className="bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl p-4 max-w-sm w-full"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-3">
              <span className="text-[#00ff00] font-mono font-bold text-sm flex items-center gap-1"><LinkIcon size={14} /> Net Protocol Links</span>
              <button
                onClick={() => setShowUnlinkedInfo(false)}
                className="w-6 h-6 rounded-full bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white text-xs"
              >
                ✕
              </button>
            </div>
            <P className="text-gray-300 font-mono text-xs mb-3">
              Members can link their profile to any Net Protocol URL. This could be:
            </P>
            <ul className="text-gray-400 font-mono text-[11px] space-y-1.5 mb-4 ml-2">
              <li>• A personal website stored onchain</li>
              <li>• A portfolio or gallery</li>
              <li>• Documentation or writing</li>
              <li>• Any content on Net Protocol</li>
            </ul>
            <P className="text-[#00ff00]/80 font-mono text-xs">
              To link your profile, go to My Library → tap your card → &quot;Link to Net&quot;
            </P>
          </div>
        </div>
      )}

      {/* Airdrop Address Info Modal */}
      {showAirdropAddressInfo && (
        <div
          className="fixed inset-0 bg-black/80 z-[70] flex items-center justify-center p-4"
          onClick={() => setShowAirdropAddressInfo(false)}
        >
          <div
            className="bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl p-4 max-w-sm w-full"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-3">
              <span className="text-[#00ff00] font-mono font-bold text-sm flex items-center gap-1"><ParachuteIcon size={14} /> Airdrop Addresses</span>
              <button
                onClick={() => setShowAirdropAddressInfo(false)}
                className="w-6 h-6 rounded-full bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white text-xs"
              >
                ✕
              </button>
            </div>
            <P className="text-gray-300 font-mono text-xs mb-3">
              The colored ring around each member&apos;s PFP shows where their airdrops go. This is the wallet they used to become a member.
            </P>
            <div className="space-y-2 mb-4">
              <div className="flex items-center gap-3 p-2 rounded bg-purple-500/10 border border-purple-500/20">
                <div className="w-6 h-6 rounded-full border-2 border-purple-500 bg-purple-500/20 shrink-0"></div>
                <P className="text-gray-300 font-mono text-[11px]">
                  <strong className="text-purple-400">Purple ring</strong> = Joined via Farcaster
                </P>
              </div>
              <div className="flex items-center gap-3 p-2 rounded bg-blue-500/10 border border-blue-500/20">
                <div className="w-6 h-6 rounded-full border-2 border-blue-500 bg-blue-500/20 shrink-0"></div>
                <P className="text-gray-300 font-mono text-[11px]">
                  <strong className="text-blue-400">Blue ring</strong> = Joined via Base App
                </P>
              </div>
              <div className="flex items-center gap-3 p-2 rounded bg-yellow-500/10 border border-yellow-500/20">
                <div className="w-6 h-6 rounded-full border-2 border-yellow-500 bg-yellow-500/20 shrink-0"></div>
                <P className="text-gray-300 font-mono text-[11px]">
                  <strong className="text-yellow-400">Yellow ring</strong> = Joined via Web Browser
                </P>
              </div>
            </div>
            <P className="text-gray-400 font-mono text-[10px]">
              Even if a member links multiple wallets, airdrops always go to their original signup wallet.
            </P>
          </div>
        </div>
      )}

      {/* CSV Export Modal */}
      {showCsvModal && (
        <div
          className="fixed inset-0 bg-black/80 z-[70] flex items-center justify-center p-4"
          onClick={() => setShowCsvModal(false)}
        >
          <div
            className="bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl p-5 max-w-sm w-full"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-4">
              <span className="text-[#00ff00] font-mono font-bold text-sm flex items-center gap-1"><DownloadIcon size={14} /> Export Members</span>
              <button
                onClick={() => setShowCsvModal(false)}
                className="w-6 h-6 rounded-full bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white text-xs"
              >
                ✕
              </button>
            </div>
            <P className="text-gray-400 font-mono text-xs mb-4">
              Export {members.length} member addresses as CSV
            </P>
            <div className="space-y-3">
              {/* Save File Option */}
              <button
                onClick={downloadMembersCsv}
                disabled={isDownloadingCsv}
                className="w-full p-3 rounded-lg border border-[#00ff00]/30 bg-[#00ff00]/10 hover:bg-[#00ff00]/20 transition-colors disabled:opacity-50"
              >
                <div className="flex items-center gap-3">
                  <SaveIcon size={20} className="text-[#00ff00]" />
                  <div className="text-left">
                    <P className="text-[#00ff00] font-mono text-sm font-bold">
                      {isDownloadingCsv ? "Opening..." : "Save File"}
                    </P>
                    <Small className="text-gray-500 font-mono">
                      Download CSV to your device
                    </Small>
                  </div>
                </div>
              </button>

              {/* Copy to Clipboard Option */}
              <button
                onClick={copyMembersCsv}
                className="w-full p-3 rounded-lg border border-gray-600/30 bg-[#1a1a1a] hover:bg-[#222] transition-colors"
              >
                <div className="flex items-center gap-3">
                  <span className="text-xl">{csvCopied ? <CheckCircleIcon size={20} className="text-green-400" /> : <ClipboardIcon size={20} className="text-[#00ff00]" />}</span>
                  <div className="text-left">
                    <P className="text-white font-mono text-sm font-bold">
                      {csvCopied ? "Copied!" : "Copy to Clipboard"}
                    </P>
                    <Small className="text-gray-500 font-mono">
                      Paste into email, notes, etc.
                    </Small>
                  </div>
                </div>
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
src/features/app/components/member-upvote-modal.tsx
"use client";

import { useState, useMemo } from "react";
import { Button, P, Small, H4 } from "@neynar/ui";
import { MEMBER_UPVOTE_COST_ETH } from "@/hooks/use-member-upvotes";

// Current ETH price in USD (could be fetched from an API in the future)
const ETH_PRICE_USD = 2500;

interface MemberUpvoteModalProps {
  isOpen: boolean;
  onClose: () => void;
  onUpvote: (count: number) => void;
  isUpvoting: boolean;
  isConfirmed?: boolean;
  memberName: string;
  currentUpvotes: number;
}

type InputMode = "count" | "eth" | "usdc";

const PRESET_AMOUNTS = [1, 10, 100, 1000];

export function MemberUpvoteModal({
  isOpen,
  onClose,
  onUpvote,
  isUpvoting,
  isConfirmed = false,
  memberName,
  currentUpvotes,
}: MemberUpvoteModalProps) {
  const [selectedPreset, setSelectedPreset] = useState<number | "custom">(1);
  const [customAmount, setCustomAmount] = useState("");
  const [inputMode, setInputMode] = useState<InputMode>("count");

  // Calculate upvote count based on input mode
  const upvoteCount = useMemo(() => {
    if (selectedPreset !== "custom") {
      return selectedPreset;
    }

    const value = parseFloat(customAmount) || 0;
    if (value <= 0) return 0;

    switch (inputMode) {
      case "count":
        return Math.floor(value);
      case "eth":
        return Math.floor(value / MEMBER_UPVOTE_COST_ETH);
      case "usdc": {
        const ethValue = value / ETH_PRICE_USD;
        return Math.floor(ethValue / MEMBER_UPVOTE_COST_ETH);
      }
      default:
        return 0;
    }
  }, [selectedPreset, customAmount, inputMode]);

  const totalCostEth = upvoteCount * MEMBER_UPVOTE_COST_ETH;
  const totalCostUsd = totalCostEth * ETH_PRICE_USD;

  const handleSubmit = () => {
    if (upvoteCount > 0) {
      onUpvote(upvoteCount);
    }
  };

  const handlePresetClick = (amount: number) => {
    setSelectedPreset(amount);
    setCustomAmount("");
  };

  const handleCustomClick = () => {
    setSelectedPreset("custom");
    setInputMode("count");
    setCustomAmount("");
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 bg-black/90 z-[60] flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl w-full max-w-sm overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 py-3 border-b border-[#00ff00]/20 flex items-center justify-between">
          <H4 className="text-[#00ff00] font-mono">▲ Upvote Member</H4>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors"
          >
            ✕
          </button>
        </div>

        {/* Content */}
        <div className="p-4 space-y-4">
          {/* Explanation banner */}
          <div className="bg-purple-500/10 border border-purple-500/30 rounded-lg p-3">
            <div className="flex items-start gap-2">
              <span className="text-purple-400 text-lg">⛓️</span>
              <div>
                <P className="text-purple-300 font-mono text-xs font-bold">Onchain Support</P>
                <Small className="text-purple-300/70 font-mono text-[10px] leading-tight block mt-0.5">
                  Member upvotes are permanent onchain tips stored forever on Net Protocol. Your support directly rewards this member!
                </Small>
              </div>
            </div>
          </div>

          {/* Member info */}
          <div className="text-center">
            <P className="text-white font-mono text-sm truncate">{memberName}</P>
            <Small className="text-gray-500 font-mono">Currently: {currentUpvotes} upvote{currentUpvotes !== 1 ? "s" : ""}</Small>
          </div>

          {/* Preset amounts */}
          <div className="grid grid-cols-4 gap-2">
            {PRESET_AMOUNTS.map((amount) => (
              <button
                key={amount}
                onClick={() => handlePresetClick(amount)}
                className={`py-3 rounded-lg font-mono text-sm font-bold transition-all ${
                  selectedPreset === amount
                    ? "bg-[#00ff00] text-black"
                    : "bg-[#1a1a1a] text-white border border-[#333] hover:border-[#00ff00]/50"
                }`}
              >
                {amount}
              </button>
            ))}
          </div>

          {/* Custom amount button */}
          <button
            onClick={handleCustomClick}
            className={`w-full py-3 rounded-lg font-mono text-sm font-bold transition-all ${
              selectedPreset === "custom"
                ? "bg-[#00ff00] text-black"
                : "bg-[#1a1a1a] text-white border border-[#333] hover:border-[#00ff00]/50"
            }`}
          >
            Custom Amount
          </button>

          {/* Custom input section */}
          {selectedPreset === "custom" && (
            <div className="space-y-3">
              {/* Input mode selector */}
              <div className="flex gap-1 bg-[#1a1a1a] rounded-lg p-1">
                {[
                  { mode: "count" as InputMode, label: "# Upvotes" },
                  { mode: "eth" as InputMode, label: "ETH" },
                  { mode: "usdc" as InputMode, label: "USDC" },
                ].map(({ mode, label }) => (
                  <button
                    key={mode}
                    onClick={() => {
                      setInputMode(mode);
                      setCustomAmount("");
                    }}
                    className={`flex-1 py-2 rounded-md font-mono text-xs transition-all ${
                      inputMode === mode
                        ? "bg-[#00ff00]/20 text-[#00ff00]"
                        : "text-gray-400 hover:text-white"
                    }`}
                  >
                    {label}
                  </button>
                ))}
              </div>

              {/* Input field */}
              <div className="relative">
                <input
                  type="number"
                  value={customAmount}
                  onChange={(e) => setCustomAmount(e.target.value)}
                  placeholder={
                    inputMode === "count"
                      ? "Enter number of upvotes"
                      : inputMode === "eth"
                      ? "Enter ETH amount"
                      : "Enter USDC amount"
                  }
                  className="w-full px-4 py-3 bg-[#1a1a1a] border border-[#333] rounded-lg text-white font-mono text-sm placeholder-gray-500 focus:outline-none focus:border-[#00ff00]/50"
                  min="0"
                  step={inputMode === "count" ? "1" : "0.0001"}
                />
                {inputMode !== "count" && customAmount && upvoteCount > 0 && (
                  <div className="absolute right-3 top-1/2 -translate-y-1/2">
                    <Small className="text-[#00ff00] font-mono">
                      = {upvoteCount} upvote{upvoteCount !== 1 ? "s" : ""}
                    </Small>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Cost summary */}
          {upvoteCount > 0 && (
            <div className="bg-[#1a1a1a] rounded-lg p-3 space-y-1">
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">Upvotes</Small>
                <Small className="text-white font-mono font-bold">{upvoteCount}</Small>
              </div>
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">Cost</Small>
                <Small className="text-[#00ff00] font-mono font-bold">
                  {totalCostEth.toFixed(6)} ETH
                </Small>
              </div>
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">≈ USD</Small>
                <Small className="text-gray-400 font-mono">
                  ${totalCostUsd.toFixed(2)}
                </Small>
              </div>
            </div>
          )}

          {/* Confirmed success state */}
          {isConfirmed ? (
            <div className="bg-[#00ff00]/10 border border-[#00ff00]/50 rounded-lg p-4 text-center space-y-1">
              <P className="text-[#00ff00] font-mono font-bold text-lg">✓ Upvote Confirmed!</P>
              <Small className="text-[#00ff00]/70 font-mono block">
                {upvoteCount} upvote{upvoteCount !== 1 ? "s" : ""} sent to {memberName} onchain
              </Small>
            </div>
          ) : (
            <>
              {/* Submit button */}
              <Button
                onClick={handleSubmit}
                disabled={isUpvoting || upvoteCount === 0}
                className={`w-full h-12 font-mono font-bold ${
                  isUpvoting
                    ? "bg-[#00ff00]/20 text-[#00ff00] cursor-wait"
                    : upvoteCount === 0
                    ? "bg-gray-600 text-gray-400 cursor-not-allowed"
                    : "bg-[#00ff00] text-black hover:bg-[#00dd00]"
                }`}
              >
                {isUpvoting ? (
                  "Confirming on Base..."
                ) : upvoteCount === 0 ? (
                  "Select Amount"
                ) : (
                  `▲ Upvote ${upvoteCount}x`
                )}
              </Button>

              {/* Info */}
              <Small className="text-gray-500 font-mono text-center block text-[10px]">
                Each upvote costs {MEMBER_UPVOTE_COST_ETH} ETH (~${(MEMBER_UPVOTE_COST_ETH * ETH_PRICE_USD).toFixed(4)})
              </Small>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
src/features/app/components/multi-file-upload.tsx
"use client";

import { useState, useRef, useCallback, useMemo, useEffect } from "react";
import { Card, CardContent, Button, Small, H4, P } from "@neynar/ui";
import type { Category, Stack } from "@/features/app/types";
import { createQueuedUpload, getQueueSummary, findDraftForFile, type QueuedUpload } from "@/lib/upload-queue";
import { usePdfCover } from "@/hooks/use-pdf-cover";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { useRelayBatchUploadV2 as useRelayBatchUpload } from "@/hooks/use-relay-batch-upload-v2";
import {
  MAX_FILE_SIZE,
  FREE_TIER_MEMBER_MAX_SIZE,
  FREE_TIER_NON_MEMBER_MAX_SIZE,
  PREMIUM_PRICE_PER_MB,
} from "@/lib/net-protocol";
import { RELAY_PRICING } from "@/lib/net-relay";
import { LibraryIcon, DocumentIcon, WarningIcon, PartyIcon, RefreshIcon, CloseIcon, LockIcon, CheckIcon, PackageIcon } from "@/components/icons/net-library-icons";
// Lazy load EPUB converter to avoid build-time bundling issues with jspdf/jszip
import type { EpubConversionProgress } from "@/lib/epub-to-pdf";

// Compact stack dropdown for batch upload
function CompactStackDropdown({
  stacks,
  selectedStackIds,
  onToggle,
  isLoading,
}: {
  stacks: Stack[];
  selectedStackIds: string[];
  onToggle: (stackId: string) => void;
  isLoading: boolean;
}) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };
    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      return () => document.removeEventListener("mousedown", handleClickOutside);
    }
  }, [isOpen]);

  const selectedStacks = stacks.filter(s => selectedStackIds.includes(s.id));

  if (isLoading) {
    return (
      <div className="w-full px-2 py-1.5 rounded bg-black/50 border border-[#00ff00]/20 text-gray-500 font-mono text-xs">
        Loading stacks...
      </div>
    );
  }

  if (stacks.length === 0) {
    return (
      <div className="w-full px-2 py-1.5 rounded bg-black/50 border border-[#00ff00]/10 text-gray-500 font-mono text-xs">
        No stacks yet
      </div>
    );
  }

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="w-full px-2 py-1.5 rounded bg-black/50 border border-[#00ff00]/20 text-left font-mono text-xs focus:outline-none focus:border-[#00ff00]/50 transition-colors flex items-center justify-between"
      >
        <div className="flex-1 min-w-0">
          {selectedStacks.length === 0 ? (
            <span className="text-gray-500">Add to stacks (optional)...</span>
          ) : (
            <div className="flex flex-wrap gap-1">
              {selectedStacks.map(stack => (
                <span
                  key={stack.id}
                  className="inline-flex items-center gap-0.5 px-1.5 py-0.5 bg-[#00ff00]/20 text-[#00ff00] rounded text-[10px]"
                >
                  <LibraryIcon size={10} className="inline" /> {stack.name.slice(0, 10)}{stack.name.length > 10 ? "..." : ""}
                </span>
              ))}
            </div>
          )}
        </div>
        <svg
          className={`w-4 h-4 text-[#00ff00]/50 transition-transform shrink-0 ml-1 ${isOpen ? "rotate-180" : ""}`}
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {isOpen && (
        <div className="absolute top-full left-0 right-0 mt-1 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg overflow-hidden z-30 max-h-48 overflow-y-auto">
          {stacks.map((stack) => {
            const isSelected = selectedStackIds.includes(stack.id);
            const isFull = !stack.unlocked && (stack.itemCount || 0) >= 20;
            return (
              <button
                key={stack.id}
                type="button"
                onClick={() => !isFull && onToggle(stack.id)}
                disabled={isFull}
                className={`w-full px-2 py-2 text-left font-mono text-xs flex items-center gap-2 transition-colors ${
                  isFull
                    ? "opacity-50 cursor-not-allowed text-gray-500"
                    : isSelected
                    ? "bg-[#00ff00]/20 text-[#00ff00]"
                    : "text-gray-300 hover:bg-[#1a1a1a] hover:text-white"
                }`}
              >
                <span className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${
                  isFull ? 'border-gray-600 bg-gray-800' : isSelected ? 'border-[#00ff00] bg-[#00ff00]' : 'border-gray-600'
                }`}>
                  {isSelected && !isFull && <CheckIcon size={10} className="text-black" />}
                  {isFull && <CloseIcon size={8} className="text-gray-500" />}
                </span>
                <LibraryIcon size={12} />
                <span className="truncate">{stack.name}</span>
                {stack.isPrivate && <LockIcon size={10} className="text-gray-500" />}
                <span className={`text-[9px] ml-auto shrink-0 ${
                  isFull
                    ? "text-red-400 font-bold"
                    : !stack.unlocked && (stack.itemCount || 0) >= 15
                    ? "text-yellow-400"
                    : "text-gray-500"
                }`}>
                  {isFull ? "FULL" : `${stack.itemCount || 0}/${stack.unlocked ? "∞" : "20"}`}
                </span>
              </button>
            );
          })}
          {/* Done button for mobile */}
          <button
            type="button"
            onClick={() => setIsOpen(false)}
            className="w-full px-2 py-1.5 text-center font-mono text-xs text-[#00ff00] bg-[#00ff00]/10 border-t border-[#00ff00]/20 hover:bg-[#00ff00]/20 transition-colors"
          >
            Done
          </button>
        </div>
      )}
    </div>
  );
}

// Compact category dropdown for batch upload
function CompactCategoryDropdown({
  categories,
  selectedCategories,
  onToggle,
}: {
  categories: Category[];
  selectedCategories: string[];
  onToggle: (categoryId: string) => void;
}) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };
    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      return () => document.removeEventListener("mousedown", handleClickOutside);
    }
  }, [isOpen]);

  const filteredCategories = categories.filter(c => c.id !== "all");
  const selectedCats = filteredCategories.filter(c => selectedCategories.includes(c.id));

  return (
    <div className="relative" ref={dropdownRef}>
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="w-full px-2 py-1.5 rounded bg-black/50 border border-[#00ff00]/20 text-left font-mono text-xs focus:outline-none focus:border-[#00ff00]/50 transition-colors flex items-center justify-between"
      >
        <div className="flex-1 min-w-0">
          {selectedCats.length === 0 ? (
            <span className="text-gray-500">Select categories...</span>
          ) : (
            <div className="flex flex-wrap gap-1">
              {selectedCats.map(cat => (
                <span
                  key={cat.id}
                  className="inline-flex items-center gap-0.5 px-1.5 py-0.5 bg-[#00ff00]/20 text-[#00ff00] rounded text-[10px]"
                >
                  {cat.emoji}
                </span>
              ))}
            </div>
          )}
        </div>
        <svg
          className={`w-4 h-4 text-[#00ff00]/50 transition-transform shrink-0 ml-1 ${isOpen ? "rotate-180" : ""}`}
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {isOpen && (
        <div className="absolute top-full left-0 right-0 mt-1 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg overflow-hidden z-30 max-h-48 overflow-y-auto">
          {filteredCategories.map((cat) => {
            const isSelected = selectedCategories.includes(cat.id);
            const isDisabled = !isSelected && selectedCategories.length >= 3;
            return (
              <button
                key={cat.id}
                type="button"
                onClick={() => {
                  if (!isDisabled) onToggle(cat.id);
                }}
                disabled={isDisabled}
                className={`w-full px-2 py-2 text-left font-mono text-xs flex items-center gap-2 transition-colors ${
                  isSelected
                    ? "bg-[#00ff00]/20 text-[#00ff00]"
                    : isDisabled
                    ? "text-gray-600 cursor-not-allowed"
                    : "text-gray-300 hover:bg-[#1a1a1a] hover:text-white"
                }`}
              >
                <span className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${
                  isSelected ? 'border-[#00ff00] bg-[#00ff00]' : 'border-gray-600'
                }`}>
                  {isSelected && <span className="text-black text-[10px] font-bold">✓</span>}
                </span>
                <span>{cat.emoji}</span>
                <span className="truncate">{cat.label}</span>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

const loadEpubConverter = () => import("@/lib/epub-to-pdf");

// Helper to check if a file is an EPUB (inlined to avoid importing the module)
const isEpubFile = (file: File): boolean =>
  file.name.toLowerCase().endsWith(".epub") || file.type === "application/epub+zip";

// Maximum batch upload size (100MB total)
const MAX_BATCH_SIZE = 100 * 1024 * 1024;

interface MultiFileUploadProps {
  categories: Category[];
  stacks?: Stack[];
  isLoadingStacks?: boolean;
  onFilesSelected: (files: QueuedUpload[], premiumPaid?: boolean) => void;
  onCancel: () => void;
  onNavigateToProfile?: () => void;
}

type BatchStep = "select" | "confirm" | "premium-choice";

// Track EPUB conversion state for batch
interface EpubConversionState {
  fileName: string;
  progress: EpubConversionProgress;
}

export function MultiFileUpload({ categories, stacks = [], isLoadingStacks = false, onFilesSelected, onCancel, onNavigateToProfile }: MultiFileUploadProps) {
  const [queuedFiles, setQueuedFiles] = useState<QueuedUpload[]>([]);
  const [isDragging, setIsDragging] = useState(false);
  const [step, setStep] = useState<BatchStep>("select");
  const [errors, setErrors] = useState<string[]>([]);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const { extractCover, isExtracting } = usePdfCover();
  const { isMember } = useMembershipStatus();
  const { estimateBatchCost } = useRelayBatchUpload();

  // Stack selection for batch upload - applies to all files in batch
  const [selectedStackIds, setSelectedStackIds] = useState<string[]>([]);

  const _toggleStackSelection = (stackId: string) => {
    setSelectedStackIds(prev =>
      prev.includes(stackId)
        ? prev.filter(id => id !== stackId)
        : [...prev, stackId]
    );
  };

  // EPUB conversion state
  const [epubConversions, setEpubConversions] = useState<EpubConversionState[]>([]);
  const [isConvertingEpubs, setIsConvertingEpubs] = useState(false);

  // x402 Relay cost estimation state
  const [relayCostEstimate, setRelayCostEstimate] = useState<{
    estimatedCostUsdc: number;
    currentBalanceUsdc: number;
    sufficient: boolean;
    lowBalance: boolean;
    shortfallUsdc: number;
  } | null>(null);
  const [isEstimatingCost, setIsEstimatingCost] = useState(false);

  // Calculate batch statistics
  const batchStats = useMemo(() => {
    const totalSize = queuedFiles.reduce((acc, f) => acc + f.file.size, 0);
    const oversizedFiles = queuedFiles.filter(f => f.file.size > MAX_FILE_SIZE);
    const exceedsBatchLimit = totalSize > MAX_BATCH_SIZE;

    // For members: check if total exceeds free tier (15MB)
    const requiresPremium = isMember && totalSize > FREE_TIER_MEMBER_MAX_SIZE;
    const premiumFee = requiresPremium
      ? Math.ceil((totalSize - FREE_TIER_MEMBER_MAX_SIZE) / (1024 * 1024)) * PREMIUM_PRICE_PER_MB
      : 0;

    // For non-members: check if ANY file or total exceeds 200KB
    const exceedsNonMemberLimit = !isMember && totalSize > FREE_TIER_NON_MEMBER_MAX_SIZE;

    return {
      totalSize,
      totalSizeMB: (totalSize / (1024 * 1024)).toFixed(1),
      oversizedFiles,
      exceedsBatchLimit,
      requiresPremium,
      premiumFee,
      exceedsNonMemberLimit,
      isValid: oversizedFiles.length === 0 && !exceedsBatchLimit && (isMember || !exceedsNonMemberLimit),
    };
  }, [queuedFiles, isMember]);

  // Handle files being dropped or selected
  const handleFilesAdded = useCallback(async (files: FileList | File[]) => {
    const newFiles: QueuedUpload[] = [];
    const newErrors: string[] = [];
    const fileArray = Array.from(files);

    // Separate EPUBs from other files
    const epubFiles = fileArray.filter(f => isEpubFile(f));
    const otherFiles = fileArray.filter(f => !isEpubFile(f));

    // Convert EPUBs first
    if (epubFiles.length > 0) {
      setIsConvertingEpubs(true);

      for (const epubFile of epubFiles) {
        // Check size before converting
        if (epubFile.size > MAX_FILE_SIZE) {
          newErrors.push(`"${epubFile.name}" exceeds 100MB limit (${(epubFile.size / (1024 * 1024)).toFixed(1)}MB)`);
          continue;
        }

        // Initialize conversion state for this file
        setEpubConversions(prev => [...prev, {
          fileName: epubFile.name,
          progress: { stage: "extracting", percent: 0, message: "Starting..." }
        }]);

        try {
          // Lazy load the converter to avoid build-time bundling issues
          const { convertEpubToPdf } = await loadEpubConverter();
          const result = await convertEpubToPdf(epubFile, (progress) => {
            setEpubConversions(prev =>
              prev.map(c => c.fileName === epubFile.name ? { ...c, progress } : c)
            );
          });

          if (result.success && result.pdfFile) {
            const queued = createQueuedUpload(result.pdfFile);
            queued.originalEpubName = epubFile.name; // Track original name

            // Check for saved draft metadata (from previous failed upload)
            const draft = findDraftForFile(result.pdfFile);
            if (draft) {
              console.log(`[MultiFileUpload] Found saved draft for "${result.pdfFile.name}"`);
              queued.title = draft.title || queued.title;
              queued.author = draft.author || queued.author;
              queued.categories = draft.categories.length > 0 ? draft.categories : queued.categories;
              queued.publicationYear = draft.publicationYear;
              queued.publisher = draft.publisher;
              queued.isbn = draft.isbn;
              queued.description = draft.description;
              queued.stackIds = draft.stackIds;
              queued.fromDraft = true; // Mark as restored from draft
              // Use saved cover if no new cover and draft has one
              if (draft.coverUrl && !queued.coverUrl) {
                queued.coverUrl = draft.coverUrl;
              }
            }

            // Extract cover from converted PDF (will override draft cover if successful)
            try {
              const cover = await extractCover(result.pdfFile, 200);
              if (cover) {
                queued.coverUrl = cover.dataUrl;
              }
            } catch (e) {
              console.log("[MultiFileUpload] Cover extraction from converted PDF failed:", e);
            }

            newFiles.push(queued);
          } else {
            newErrors.push(`Failed to convert "${epubFile.name}": ${result.error || "Unknown error"}`);
          }
        } catch (e) {
          newErrors.push(`Error converting "${epubFile.name}": ${e instanceof Error ? e.message : "Unknown error"}`);
        }

        // Remove from conversion state
        setEpubConversions(prev => prev.filter(c => c.fileName !== epubFile.name));
      }

      setIsConvertingEpubs(false);
    }

    // Process other files (PDFs, text)
    for (const file of otherFiles) {
      // Only accept PDFs and text files
      if (!file.type.includes("pdf") && !file.type.includes("text")) {
        continue;
      }

      // Check individual file size limit (100MB)
      if (file.size > MAX_FILE_SIZE) {
        newErrors.push(`"${file.name}" exceeds 100MB limit (${(file.size / (1024 * 1024)).toFixed(1)}MB)`);
        continue;
      }

      const queued = createQueuedUpload(file);

      // Check for saved draft metadata (from previous failed upload)
      const draft = findDraftForFile(file);
      console.log(`[MultiFileUpload] Checking for draft: "${file.name}" (${file.size} bytes)`, draft ? "FOUND" : "not found");
      if (draft) {
        console.log(`[MultiFileUpload] ♻️ Restoring draft for "${file.name}":`, {
          title: draft.title,
          author: draft.author,
          categories: draft.categories,
          savedAt: new Date(draft.savedAt).toLocaleString(),
        });
        queued.title = draft.title || queued.title;
        queued.author = draft.author || queued.author;
        queued.categories = draft.categories.length > 0 ? draft.categories : queued.categories;
        queued.publicationYear = draft.publicationYear;
        queued.publisher = draft.publisher;
        queued.isbn = draft.isbn;
        queued.description = draft.description;
        queued.stackIds = draft.stackIds;
        queued.fromDraft = true; // Mark as restored from draft
        // Use saved cover if available
        if (draft.coverUrl) {
          queued.coverUrl = draft.coverUrl;
        }
      }

      // Auto-extract cover for PDFs (will override draft cover with fresh one)
      if (file.type.includes("pdf")) {
        try {
          const cover = await extractCover(file, 200);
          if (cover) {
            queued.coverUrl = cover.dataUrl;
          }
        } catch (e) {
          console.log("[MultiFileUpload] Cover extraction failed:", e);
        }
      }

      newFiles.push(queued);
    }

    if (newErrors.length > 0) {
      setErrors(prev => [...prev, ...newErrors]);
    }

    // Check if adding these files would exceed batch limit
    setQueuedFiles(prev => {
      const combined = [...prev, ...newFiles];
      const combinedSize = combined.reduce((acc, f) => acc + f.file.size, 0);

      if (combinedSize > MAX_BATCH_SIZE) {
        setErrors(e => [...e, `Adding these files would exceed the 100MB batch limit. Current: ${(combinedSize / (1024 * 1024)).toFixed(1)}MB`]);
        return prev; // Don't add the files
      }

      return combined;
    });
  }, [extractCover]);

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    if (e.dataTransfer.files?.length > 0) {
      handleFilesAdded(e.dataTransfer.files);
    }
  };

  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files?.length) {
      handleFilesAdded(e.target.files);
    }
  };

  const removeFile = (id: string) => {
    setQueuedFiles(prev => prev.filter(f => f.id !== id));
    setErrors([]); // Clear errors when removing files
  };

  const updateFileMetadata = (id: string, updates: Partial<QueuedUpload>) => {
    setQueuedFiles(prev => prev.map(f =>
      f.id === id ? { ...f, ...updates } : f
    ));
  };

  const clearErrors = () => setErrors([]);

  const handleProceedToConfirm = async () => {
    // For non-members exceeding limit, don't proceed
    if (batchStats.exceedsNonMemberLimit) {
      return;
    }

    // For members with premium required, show premium choice
    if (batchStats.requiresPremium) {
      setStep("premium-choice");
    } else {
      setStep("confirm");
    }

    // Estimate x402 relay cost when entering confirm or premium-choice step
    setIsEstimatingCost(true);
    try {
      const estimate = await estimateBatchCost(queuedFiles.map(f => ({
        file: f.file,
        metadata: {
          title: f.title,
          author: f.author,
          categories: f.categories,
          coverUrl: f.coverUrl,
          publicationYear: f.publicationYear ? parseInt(f.publicationYear, 10) : undefined,
          publisher: f.publisher,
          isbn: f.isbn,
        }
      })));
      setRelayCostEstimate({
        estimatedCostUsdc: estimate.totalCostUsdc,
        currentBalanceUsdc: estimate.balanceInfo?.balanceUsdc ?? 0,
        sufficient: estimate.canProceed,
        lowBalance: estimate.lowBalance,
        shortfallUsdc: estimate.balanceInfo?.shortfallUsdc ?? 0,
      });
    } catch (e) {
      console.error("[MultiFileUpload] Cost estimation failed:", e);
    } finally {
      setIsEstimatingCost(false);
    }
  };

  const handleStartUpload = (premiumPaid: boolean = false) => {
    // Each file now has its own stackIds, no need for separate batch param
    onFilesSelected(queuedFiles, premiumPaid);
  };

  const summary = getQueueSummary(queuedFiles);

  // Non-member limit exceeded view
  if (batchStats.exceedsNonMemberLimit && queuedFiles.length > 0) {
    return (
      <div className="space-y-4">
        {/* Header with back button */}
        <div className="flex items-center gap-3">
          <button
            onClick={onCancel}
            className="w-10 h-10 rounded-full bg-[#1a1a1a] border border-[#00ff00]/30 flex items-center justify-center text-[#00ff00] hover:bg-[#00ff00]/10 hover:border-[#00ff00] transition-all"
            aria-label="Go back"
          >
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
          </button>
          <H4 className="text-[#00ff00] font-mono flex items-center gap-2"><PackageIcon size={18} /> Batch Upload</H4>
        </div>

        {/* Membership required card */}
        <Card className="bg-yellow-500/10 border-2 border-yellow-500/50">
          <CardContent className="p-4 space-y-4">
            <div className="text-center">
              <div className="text-5xl mb-3">🎫</div>
              <H4 className="text-yellow-400 font-mono">Membership Required</H4>
            </div>

            <div className="bg-black/30 rounded-lg p-3 space-y-2">
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">Your batch size:</Small>
                <Small className="text-white font-mono font-bold">{batchStats.totalSizeMB} MB</Small>
              </div>
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">Non-member limit:</Small>
                <Small className="text-yellow-400 font-mono">200 KB</Small>
              </div>
            </div>

            <P className="text-gray-300 font-mono text-sm text-center">
              Become a Net Library member to unlock batch uploads up to 15MB free, or up to 100MB with premium!
            </P>

            <div className="space-y-2">
              <Button
                onClick={onNavigateToProfile}
                className="w-full bg-yellow-500 text-black hover:bg-yellow-400 font-mono font-bold"
              >
                🎫 Become a Member
              </Button>
              <Button
                onClick={() => setQueuedFiles([])}
                variant="outline"
                className="w-full border-[#333] text-gray-400 hover:border-yellow-500/30 hover:text-yellow-400"
              >
                Clear & Start Over
              </Button>
            </div>

            <Small className="text-gray-500 font-mono text-[10px] text-center block">
              Members can upload files up to 15MB for free!
            </Small>
          </CardContent>
        </Card>
      </div>
    );
  }

  // Premium choice view (for members exceeding 15MB)
  if (step === "premium-choice") {
    return (
      <div className="space-y-4">
        {/* Header with back button */}
        <div className="flex items-center gap-3">
          <button
            onClick={() => setStep("select")}
            className="w-10 h-10 rounded-full bg-[#1a1a1a] border border-[#00ff00]/30 flex items-center justify-center text-[#00ff00] hover:bg-[#00ff00]/10 hover:border-[#00ff00] transition-all"
            aria-label="Go back"
          >
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
          </button>
          <H4 className="text-[#00ff00] font-mono">💎 Premium Upload</H4>
        </div>

        <Card className="bg-purple-500/10 border-2 border-purple-500/50">
          <CardContent className="p-4 space-y-4">
            <div className="text-center">
              <div className="text-5xl mb-3">💎</div>
              <H4 className="text-purple-400 font-mono">Premium Tier Required</H4>
            </div>

            <div className="bg-black/30 rounded-lg p-3 space-y-2">
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">Total batch size:</Small>
                <Small className="text-white font-mono font-bold">{batchStats.totalSizeMB} MB</Small>
              </div>
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">Free tier limit:</Small>
                <Small className="text-green-400 font-mono">15 MB</Small>
              </div>
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">Excess data:</Small>
                <Small className="text-yellow-400 font-mono">
                  {Math.ceil((batchStats.totalSize - FREE_TIER_MEMBER_MAX_SIZE) / (1024 * 1024))} MB
                </Small>
              </div>
              <div className="h-px bg-purple-500/30 my-1" />
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">Rate:</Small>
                <Small className="text-purple-400 font-mono">${PREMIUM_PRICE_PER_MB}/MB</Small>
              </div>
              <div className="flex justify-between">
                <Small className="text-purple-400 font-mono font-bold">Premium fee:</Small>
                <Small className="text-purple-400 font-mono font-bold">${batchStats.premiumFee} USDC</Small>
              </div>
            </div>

            <P className="text-gray-300 font-mono text-sm text-center">
              Your batch exceeds the 15MB free tier. You can pay the premium fee to proceed, or remove some files.
            </P>

            <div className="space-y-2">
              <Button
                onClick={() => {
                  setStep("confirm");
                }}
                className="w-full bg-purple-500 text-white hover:bg-purple-600 font-mono font-bold"
              >
                Pay ${batchStats.premiumFee} USDC & Continue
              </Button>
              <Button
                onClick={() => setStep("select")}
                variant="outline"
                className="w-full border-[#333] text-gray-400 hover:border-purple-500/30 hover:text-purple-400"
              >
                Go Back & Remove Files
              </Button>
            </div>
          </CardContent>
        </Card>
      </div>
    );
  }

  // Confirmation view
  if (step === "confirm") {
    return (
      <div className="space-y-4">
        {/* Header with back button */}
        <div className="flex items-center gap-3">
          <button
            onClick={() => setStep(batchStats.requiresPremium ? "premium-choice" : "select")}
            className="w-10 h-10 rounded-full bg-[#1a1a1a] border border-[#00ff00]/30 flex items-center justify-center text-[#00ff00] hover:bg-[#00ff00]/10 hover:border-[#00ff00] transition-all"
            aria-label="Go back"
          >
            <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
            </svg>
          </button>
          <H4 className="text-[#00ff00] font-mono">✓ Confirm Upload</H4>
        </div>

        {/* Summary card */}
        <Card className="bg-[#00ff00]/5 border-2 border-[#00ff00]/30">
          <CardContent className="p-4 space-y-3">
            <div className="flex items-center justify-between">
              <P className="text-[#00ff00] font-mono font-bold">
                {queuedFiles.length} file{queuedFiles.length !== 1 ? "s" : ""} ready
              </P>
              <Small className="text-white font-mono font-bold">{batchStats.totalSizeMB} MB</Small>
            </div>

            {/* File list preview */}
            <div className="max-h-32 overflow-y-auto space-y-1 bg-black/30 rounded-lg p-2">
              {queuedFiles.map((file, idx) => (
                <div key={file.id} className="flex items-center gap-2 text-xs font-mono">
                  <span className="text-[#00ff00]/50">{idx + 1}.</span>
                  <span className="text-white truncate flex-1">{file.title}</span>
                  <span className="text-gray-500 shrink-0">
                    {(file.file.size / (1024 * 1024)).toFixed(1)}MB
                  </span>
                </div>
              ))}
            </div>

            {batchStats.requiresPremium && (
              <div className="bg-purple-500/10 border border-purple-500/30 rounded-lg p-2">
                <Small className="text-purple-400 font-mono">
                  💎 Premium fee: ${batchStats.premiumFee} USDC
                </Small>
              </div>
            )}
          </CardContent>
        </Card>

        {/* x402 Relay Cost Card */}
        {isEstimatingCost ? (
          <Card className="bg-cyan-500/5 border border-cyan-500/30">
            <CardContent className="p-3">
              <div className="flex items-center gap-2">
                <div className="w-4 h-4 border-2 border-cyan-400 border-t-transparent rounded-full animate-spin" />
                <Small className="text-cyan-400 font-mono">Estimating upload cost...</Small>
              </div>
            </CardContent>
          </Card>
        ) : relayCostEstimate && (
          <Card className={`border ${relayCostEstimate.sufficient ? "bg-green-500/5 border-green-500/30" : "bg-yellow-500/5 border-yellow-500/30"}`}>
            <CardContent className="p-3 space-y-2">
              <div className="flex items-center gap-2 mb-1">
                <span className="text-sm">💳</span>
                <Small className={`font-mono font-bold ${relayCostEstimate.sufficient ? "text-green-400" : "text-yellow-400"}`}>
                  x402 Gasless Upload
                </Small>
              </div>
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono text-[10px]">Estimated cost:</Small>
                <Small className="text-white font-mono text-[10px]">${relayCostEstimate.estimatedCostUsdc.toFixed(2)} USDC</Small>
              </div>
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono text-[10px]">Your balance:</Small>
                <Small className={`font-mono text-[10px] ${relayCostEstimate.sufficient ? "text-green-400" : "text-yellow-400"}`}>
                  ${relayCostEstimate.currentBalanceUsdc.toFixed(2)} USDC
                </Small>
              </div>
              {!relayCostEstimate.sufficient && (
                <div className="pt-2 border-t border-yellow-500/20">
                  <Small className="text-yellow-400 font-mono text-[10px] flex items-center gap-1">
                    <WarningIcon size={12} /> Add ${relayCostEstimate.shortfallUsdc.toFixed(2)} USDC to your relay balance before uploading.
                  </Small>
                  <Small className="text-gray-500 font-mono text-[10px] block mt-1">
                    You&apos;ll be prompted to fund when upload starts.
                  </Small>
                </div>
              )}
              {relayCostEstimate.sufficient && relayCostEstimate.lowBalance && (
                <div className="pt-2 border-t border-cyan-500/20">
                  <Small className="text-cyan-400 font-mono text-[10px] block">
                    💡 Balance below ${RELAY_PRICING.lowBalanceThresholdUsdc}. Consider adding more for future uploads.
                  </Small>
                </div>
              )}
              <div className="pt-1 border-t border-[#00ff00]/10">
                <Small className="text-gray-500 font-mono text-[9px] flex items-center gap-1">
                  <PartyIcon size={10} /> One payment • No gas signatures • Instant upload
                </Small>
              </div>
            </CardContent>
          </Card>
        )}

        {/* Stack assignment summary - if any files have stacks */}
        {queuedFiles.some(f => f.stackIds && f.stackIds.length > 0) && (
          <Card className="bg-[#00ff00]/5 border border-[#00ff00]/30">
            <CardContent className="p-3">
              <div className="flex items-center gap-2 mb-2">
                <span className="text-lg text-[#00ff00]"><LibraryIcon size={18} /></span>
                <Small className="text-[#00ff00] font-mono font-bold">
                  Stack Assignments
                </Small>
              </div>
              <div className="space-y-1 max-h-24 overflow-y-auto">
                {queuedFiles.filter(f => f.stackIds && f.stackIds.length > 0).map((file) => (
                  <div key={file.id} className="flex items-center gap-2 text-[10px] font-mono">
                    <span className="text-gray-400 truncate flex-1 max-w-[120px]">{file.title}</span>
                    <span className="text-[#00ff00]">→</span>
                    <span className="text-[#00ff00]/70">
                      {file.stackIds!.length} stack{file.stackIds!.length !== 1 ? "s" : ""}
                    </span>
                  </div>
                ))}
              </div>
            </CardContent>
          </Card>
        )}

        {/* Confirmation checklist */}
        <Card className="bg-yellow-500/5 border border-yellow-500/30">
          <CardContent className="p-4 space-y-2">
            <Small className="text-yellow-400 font-mono font-bold flex items-center gap-1"><WarningIcon size={12} /> Please confirm:</Small>
            <div className="space-y-1">
              <Small className="text-gray-300 font-mono text-[11px] block">• All titles and authors are correct</Small>
              <Small className="text-gray-300 font-mono text-[11px] block">• Categories are properly assigned</Small>
              <Small className="text-gray-300 font-mono text-[11px] block">• All content is my own work OR CC0/public domain</Small>
              <Small className="text-gray-300 font-mono text-[11px] block">• I understand uploads are permanent onchain</Small>
            </div>
          </CardContent>
        </Card>

        {/* Actions */}
        <div className="flex gap-2">
          <Button
            onClick={() => setStep("select")}
            variant="outline"
            className="flex-1 border-[#333] text-gray-400 hover:border-[#00ff00]/30 hover:text-[#00ff00]"
          >
            Edit Files
          </Button>
          <Button
            onClick={() => handleStartUpload(batchStats.requiresPremium)}
            disabled={isEstimatingCost}
            className="flex-1 bg-[#00ff00] text-black hover:bg-[#00dd00] font-mono font-bold disabled:opacity-50"
          >
            {relayCostEstimate && !relayCostEstimate.sufficient ? "Fund & Upload" : "Start Upload"}
          </Button>
        </div>
      </div>
    );
  }

  // Selection view (default)
  return (
    <div className="space-y-4">
      {/* Header with back button */}
      <div className="flex items-center gap-3">
        <button
          onClick={onCancel}
          className="w-10 h-10 rounded-full bg-[#1a1a1a] border border-[#00ff00]/30 flex items-center justify-center text-[#00ff00] hover:bg-[#00ff00]/10 hover:border-[#00ff00] transition-all"
          aria-label="Go back"
        >
          <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
          </svg>
        </button>
        <H4 className="text-[#00ff00] font-mono flex items-center gap-2"><PackageIcon size={18} /> Batch Upload</H4>
      </div>

      {/* Error messages */}
      {errors.length > 0 && (
        <Card className="bg-red-500/10 border border-red-500/30">
          <CardContent className="p-3">
            <div className="flex items-start justify-between gap-2">
              <div className="space-y-1">
                {errors.map((error, idx) => (
                  <Small key={idx} className="text-red-400 font-mono text-[11px] flex items-center gap-1">
                    <WarningIcon size={10} /> {error}
                  </Small>
                ))}
              </div>
              <button onClick={clearErrors} className="text-red-400/50 hover:text-red-400 shrink-0">
                <CloseIcon size={14} />
              </button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Drop zone */}
      <input
        ref={fileInputRef}
        type="file"
        multiple
        accept=".pdf,.txt,.epub"
        onChange={handleFileInputChange}
        className="hidden"
      />

      <div
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        onClick={() => !isConvertingEpubs && fileInputRef.current?.click()}
        className={`border-2 border-dashed rounded-lg p-6 cursor-pointer transition-all flex flex-col items-center justify-center ${
          isConvertingEpubs
            ? "border-purple-500/50 bg-purple-500/10 cursor-wait"
            : isDragging
            ? "border-[#00ff00] bg-[#00ff00]/20"
            : "border-[#00ff00]/30 bg-black hover:border-[#00ff00] hover:bg-[#00ff00]/5"
        }`}
      >
        {isConvertingEpubs ? (
          <>
            <div className="w-10 h-10 border-2 border-purple-400 border-t-transparent rounded-full animate-spin mb-2" />
            <P className="text-purple-400 font-mono font-medium text-center">
              Converting EPUBs to PDF...
            </P>
            {epubConversions.length > 0 && (
              <div className="mt-2 space-y-1 w-full max-w-[250px]">
                {epubConversions.map((conv) => (
                  <div key={conv.fileName} className="text-center">
                    <Small className="text-purple-300/80 font-mono text-[10px] truncate block">
                      {conv.fileName}
                    </Small>
                    <div className="w-full h-1.5 bg-black rounded-full overflow-hidden border border-purple-400/30 mt-1">
                      <div
                        className="h-full bg-purple-500 transition-all duration-300"
                        style={{ width: `${conv.progress.percent}%` }}
                      />
                    </div>
                    <Small className="text-purple-400/60 font-mono text-[9px]">
                      {conv.progress.message}
                    </Small>
                  </div>
                ))}
              </div>
            )}
          </>
        ) : (
          <>
            <div className="text-4xl mb-2 text-[#00ff00]"><LibraryIcon size={48} /></div>
            <P className="text-[#00ff00] font-mono font-medium text-center">
              {isDragging ? "Drop files here!" : "Drag & Drop Multiple Files"}
            </P>
            <Small className="text-[#00ff00]/50 font-mono text-center">
              or tap to select • PDF, TXT, EPUB
            </Small>
            {isExtracting && (
              <Small className="text-yellow-400 font-mono mt-2 animate-pulse">
                Extracting covers...
              </Small>
            )}
          </>
        )}
      </div>

      {/* Batch limit indicator */}
      <div className="flex items-center justify-between px-1">
        <Small className="text-gray-500 font-mono text-[10px]">
          {isMember ? "Member" : "Non-member"} • Max {isMember ? "100MB" : "200KB"} per batch
        </Small>
        {queuedFiles.length > 0 && (
          <Small className={`font-mono text-[10px] ${batchStats.exceedsBatchLimit ? "text-red-400" : "text-[#00ff00]/70"}`}>
            {batchStats.totalSizeMB} / 100 MB
          </Small>
        )}
      </div>

      {/* Queue summary */}
      {queuedFiles.length > 0 && (
        <Card className={`border ${batchStats.requiresPremium ? "bg-purple-500/5 border-purple-500/30" : "bg-[#00ff00]/5 border-[#00ff00]/30"}`}>
          <CardContent className="p-3">
            <div className="flex items-center justify-between">
              <div>
                <P className={`font-mono font-bold ${batchStats.requiresPremium ? "text-purple-400" : "text-[#00ff00]"}`}>
                  {summary.total} file{summary.total !== 1 ? "s" : ""} queued
                </P>
                <Small className="text-gray-400 font-mono">
                  Total: {batchStats.totalSizeMB} MB
                  {batchStats.requiresPremium && (
                    <span className="text-purple-400"> • ${batchStats.premiumFee} premium</span>
                  )}
                </Small>
              </div>
              <div className="text-right">
                <Small className="text-[#00ff00]/70 font-mono">
                  ~{Math.ceil(batchStats.totalSize / (20 * 1024))} txs
                </Small>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* File list */}
      <div className="space-y-3 max-h-[400px] overflow-y-auto">
        {queuedFiles.map((file, index) => (
          <Card key={file.id} className="bg-[#0a0a0a] border border-[#00ff00]/20 hover:border-[#00ff00]/40 transition-all">
            <CardContent className="p-4">
              {/* File header with number and remove */}
              <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-2">
                  <span className="w-6 h-6 rounded-full bg-[#00ff00]/20 text-[#00ff00] text-xs font-mono font-bold flex items-center justify-center">
                    {index + 1}
                  </span>
                  <Small className="text-gray-500 font-mono">
                    {file.file.size >= 1024 * 1024
                      ? `${(file.file.size / (1024 * 1024)).toFixed(1)} MB`
                      : `${(file.file.size / 1024).toFixed(0)} KB`}
                  </Small>
                  {file.originalEpubName && (
                    <span className="px-1.5 py-0.5 bg-purple-500/20 text-purple-400 rounded text-[9px] font-mono flex items-center gap-0.5">
                      <LibraryIcon size={10} /> EPUB
                    </span>
                  )}
                  {file.fromDraft && (
                    <span className="px-1.5 py-0.5 bg-cyan-500/20 text-cyan-400 rounded text-[9px] font-mono flex items-center gap-1" title="Metadata restored from previous upload attempt">
                      <RefreshIcon size={10} /> Restored
                    </span>
                  )}
                </div>
                <button
                  onClick={() => removeFile(file.id)}
                  className="w-7 h-7 rounded-full bg-red-500/10 text-red-400/70 hover:bg-red-500/20 hover:text-red-400 flex items-center justify-center transition-all"
                >
                  ×
                </button>
              </div>

              <div className="flex gap-3">
                {/* Cover preview with URL input */}
                <div className="shrink-0 space-y-1">
                  <div className="w-16 h-20 rounded-lg bg-[#1a1a1a] overflow-hidden flex items-center justify-center border border-[#00ff00]/10">
                    {file.coverUrl ? (
                      <img src={file.coverUrl} alt="Cover" className="w-full h-full object-cover" />
                    ) : (
                      <span className="text-2xl text-[#00ff00]/50"><DocumentIcon size={28} /></span>
                    )}
                  </div>
                  {/* Cover URL input - compact */}
                  <input
                    type="text"
                    placeholder="Cover URL"
                    value={file.coverUrl?.startsWith('data:') ? '' : (file.coverUrl || '')}
                    onChange={(e) => {
                      const url = e.target.value.trim();
                      if (url && (url.startsWith('http://') || url.startsWith('https://'))) {
                        updateFileMetadata(file.id, { coverUrl: url });
                      } else if (!url) {
                        updateFileMetadata(file.id, { coverUrl: undefined });
                      }
                    }}
                    className="w-16 px-1 py-0.5 bg-black/50 text-white font-mono text-[8px] border border-[#00ff00]/20 rounded focus:border-[#00ff00]/50 focus:outline-none placeholder:text-gray-600"
                  />
                </div>

                {/* Editable fields */}
                <div className="flex-1 min-w-0 space-y-2">
                  {/* Title field */}
                  <div>
                    <Small className="text-[#00ff00]/60 font-mono text-[10px] block mb-0.5">Title</Small>
                    <input
                      type="text"
                      value={file.title}
                      onChange={(e) => updateFileMetadata(file.id, { title: e.target.value })}
                      className="w-full px-2 py-1.5 bg-black/50 text-white font-mono text-sm border border-[#00ff00]/20 rounded focus:border-[#00ff00]/50 focus:outline-none"
                      placeholder="Enter title..."
                    />
                  </div>

                  {/* Author field */}
                  <div>
                    <Small className="text-[#00ff00]/60 font-mono text-[10px] block mb-0.5">Author</Small>
                    <input
                      type="text"
                      value={file.author}
                      onChange={(e) => updateFileMetadata(file.id, { author: e.target.value })}
                      className="w-full px-2 py-1.5 bg-black/50 text-white font-mono text-sm border border-[#00ff00]/20 rounded focus:border-[#00ff00]/50 focus:outline-none"
                      placeholder="Enter author..."
                    />
                  </div>
                </div>
              </div>

              {/* Additional metadata fields row */}
              <div className="mt-3 grid grid-cols-3 gap-2">
                {/* Year field */}
                <div>
                  <Small className="text-[#00ff00]/60 font-mono text-[10px] block mb-0.5">Year</Small>
                  <input
                    type="number"
                    value={file.publicationYear || ""}
                    onChange={(e) => updateFileMetadata(file.id, { publicationYear: e.target.value })}
                    className="w-full px-2 py-1 bg-black/50 text-white font-mono text-xs border border-[#00ff00]/20 rounded focus:border-[#00ff00]/50 focus:outline-none"
                    placeholder="2024"
                    min="1000"
                    max={new Date().getFullYear()}
                  />
                </div>

                {/* Publisher field */}
                <div>
                  <Small className="text-[#00ff00]/60 font-mono text-[10px] block mb-0.5">Publisher</Small>
                  <input
                    type="text"
                    value={file.publisher || ""}
                    onChange={(e) => updateFileMetadata(file.id, { publisher: e.target.value })}
                    className="w-full px-2 py-1 bg-black/50 text-white font-mono text-xs border border-[#00ff00]/20 rounded focus:border-[#00ff00]/50 focus:outline-none"
                    placeholder="Optional"
                  />
                </div>

                {/* ISBN field */}
                <div>
                  <Small className="text-[#00ff00]/60 font-mono text-[10px] block mb-0.5">ISBN/DOI</Small>
                  <input
                    type="text"
                    value={file.isbn || ""}
                    onChange={(e) => updateFileMetadata(file.id, { isbn: e.target.value })}
                    className="w-full px-2 py-1 bg-black/50 text-white font-mono text-xs border border-[#00ff00]/20 rounded focus:border-[#00ff00]/50 focus:outline-none"
                    placeholder="Optional"
                  />
                </div>
              </div>

              {/* Category selection - dropdown */}
              <div className="mt-2">
                <Small className="text-[#00ff00]/60 font-mono text-[10px] block mb-1">
                  Categories (up to 3)
                </Small>
                <CompactCategoryDropdown
                  categories={categories}
                  selectedCategories={file.categories}
                  onToggle={(catId) => {
                    const isSelected = file.categories.includes(catId);
                    const newCategories = isSelected
                      ? file.categories.filter(c => c !== catId)
                      : file.categories.length < 3
                        ? [...file.categories, catId]
                        : file.categories;
                    updateFileMetadata(file.id, { categories: newCategories });
                  }}
                />
              </div>

              {/* Per-file stack selection */}
              {stacks.length > 0 && (
                <div className="mt-2">
                  <Small className="text-[#00ff00]/60 font-mono text-[10px] block mb-1">
                    Add to Stacks
                  </Small>
                  <CompactStackDropdown
                    stacks={stacks}
                    selectedStackIds={file.stackIds || []}
                    onToggle={(stackId) => {
                      const currentStackIds = file.stackIds || [];
                      const isSelected = currentStackIds.includes(stackId);
                      const newStackIds = isSelected
                        ? currentStackIds.filter(id => id !== stackId)
                        : [...currentStackIds, stackId];
                      updateFileMetadata(file.id, { stackIds: newStackIds });
                    }}
                    isLoading={isLoadingStacks}
                  />
                </div>
              )}
            </CardContent>
          </Card>
        ))}
      </div>

      {/* Batch "Apply to All" stack selection */}
      {queuedFiles.length > 1 && stacks.length > 0 && (
        <Card className="bg-[#00ff00]/5 border border-[#00ff00]/20">
          <CardContent className="p-3">
            <div className="flex items-center justify-between mb-2">
              <Small className="text-[#00ff00] font-mono font-bold flex items-center gap-1"><LibraryIcon size={12} /> Quick Add to All</Small>
              <Small className="text-[#00ff00]/50 font-mono text-[10px]">
                batch action
              </Small>
            </div>
            <CompactStackDropdown
              stacks={stacks}
              selectedStackIds={selectedStackIds}
              onToggle={(stackId) => {
                // Toggle in batch selection state
                const isAdding = !selectedStackIds.includes(stackId);
                setSelectedStackIds(prev =>
                  isAdding ? [...prev, stackId] : prev.filter(id => id !== stackId)
                );
                // Also apply to ALL files
                setQueuedFiles(prev => prev.map(file => {
                  const currentStackIds = file.stackIds || [];
                  if (isAdding) {
                    // Add to all files if not already present
                    return currentStackIds.includes(stackId)
                      ? file
                      : { ...file, stackIds: [...currentStackIds, stackId] };
                  } else {
                    // Remove from all files
                    return { ...file, stackIds: currentStackIds.filter(id => id !== stackId) };
                  }
                }));
              }}
              isLoading={isLoadingStacks}
            />
            <Small className="text-gray-500 font-mono text-[10px] mt-1 block">
              Adds/removes stack from all {queuedFiles.length} files at once
            </Small>
          </CardContent>
        </Card>
      )}

      {/* Actions */}
      {queuedFiles.length > 0 && (
        <div className="flex gap-2">
          <Button
            onClick={() => setQueuedFiles([])}
            variant="outline"
            className="flex-1 border-[#222] text-gray-400 hover:border-red-500/30 hover:text-red-400"
          >
            Clear All
          </Button>
          <Button
            onClick={handleProceedToConfirm}
            disabled={!batchStats.isValid || queuedFiles.length === 0}
            className="flex-1 bg-[#00ff00] text-black hover:bg-[#00dd00] font-mono disabled:opacity-50"
          >
            Review ({queuedFiles.length})
          </Button>
        </div>
      )}

      {/* Help text */}
      <div className="mt-3 text-center">
        <Small className="text-gray-400 font-mono text-[10px]">
          Files uploaded sequentially • Covers auto-extracted • 100MB max per batch
        </Small>
      </div>
    </div>
  );
}
src/features/app/components/multimedia-viewer.tsx
"use client";

import { useState, useRef, useEffect } from "react";
import { Button, P, Small } from "@neynar/ui";
import { WarningIcon } from "@/components/icons/net-library-icons";
import { useUpvote } from "@/hooks/use-upvotes";
import { UpvoteModal } from "./upvote-modal";
import { normalizeCoverUrl } from "@/lib/cover-url-utils";
import { safeOpenUrl } from "@/lib/app-mode";
import { decryptContent } from "@/lib/crypto";
import type { SocialPlatform } from "@/features/app/types";
import ReactMarkdown from "react-markdown";

type ContentType = "pdf" | "image" | "audio" | "video" | "text" | "unknown";

interface MultimediaViewerProps {
  contentUrl: string;
  contentType: ContentType;
  title: string;
  author: string;
  coverUrl?: string; // Cover/thumbnail image for audio/video
  contentKey?: string;
  operatorAddress?: string;
  upvoteCount?: number;
  socialPlatform?: SocialPlatform; // Source platform for social receipts
  /** When true, shows a password prompt before rendering content */
  isEncrypted?: boolean;
  onBack: () => void;
  onShare: () => void;
  onUpvoteSuccess?: () => void;
}

export function MultimediaViewer({
  contentUrl,
  contentType,
  title,
  author,
  coverUrl,
  contentKey,
  operatorAddress,
  upvoteCount = 0,
  socialPlatform,
  isEncrypted = false,
  onBack,
  onShare,
  onUpvoteSuccess,
}: MultimediaViewerProps) {
  const [localUpvotes, setLocalUpvotes] = useState(0);
  const [showUpvoteModal, setShowUpvoteModal] = useState(false);
  const [isFullscreen, setIsFullscreen] = useState(false);

  // Encryption gate state
  const [isLocked, setIsLocked] = useState(isEncrypted);
  const [passwordInput, setPasswordInput] = useState("");
  const [decryptError, setDecryptError] = useState<string | null>(null);
  const [isDecrypting, setIsDecrypting] = useState(false);
  // After successful decryption, replace contentUrl with a blob URL of the plaintext
  const [decryptedUrl, setDecryptedUrl] = useState<string | null>(null);
  // "Remember this password for this session" — stored in sessionStorage only, never persisted
  const [rememberPassword, setRememberPassword] = useState(true);
  const { upvote, isUpvoting, isConfirmed } = useUpvote();

  // Revoke the blob URL when the component unmounts or when decryptedUrl changes,
  // preventing memory accumulation from repeated opens of encrypted items.
  useEffect(() => {
    return () => {
      if (decryptedUrl) {
        URL.revokeObjectURL(decryptedUrl);
      }
    };
  }, [decryptedUrl]);

  // Derived: use the decrypted blob URL once unlocked; fall back to original URL for unencrypted items.
  // Declared early so all useEffect hooks below can reference it.
  const activeContentUrl = decryptedUrl || contentUrl;

  // Image state
  const [imageZoom, setImageZoom] = useState(1);
  const [imagePan, setImagePan] = useState({ x: 0, y: 0 });
  const [isDragging, setIsDragging] = useState(false);
  const lastTouchRef = useRef<{ x: number; y: number } | null>(null);

  // Audio/Video state
  const [isPlaying, setIsPlaying] = useState(false);
  const [currentTime, setCurrentTime] = useState(0);
  const [duration, setDuration] = useState(0);
  const [volume, setVolume] = useState(1);
  const [isMuted, setIsMuted] = useState(false);
  const [previousVolume, setPreviousVolume] = useState(1); // For unmute restore
  const [mediaError, setMediaError] = useState<string | null>(null);
  const [isMediaLoading, setIsMediaLoading] = useState(true);
  const mediaRef = useRef<HTMLAudioElement | HTMLVideoElement>(null);

  // Text state
  const [textContent, setTextContent] = useState<string>("");
  const [isLoadingText, setIsLoadingText] = useState(false);
  const [textFontSize, setTextFontSize] = useState(14); // Font size in px

  const displayUpvotes = upvoteCount + localUpvotes;

  // Debug logging
  useEffect(() => {
    const normalized = normalizeCoverUrl(coverUrl);
    console.log("[MultimediaViewer] Props:", { contentUrl, contentType, title, coverUrl, normalizedCoverUrl: normalized });
  }, [contentUrl, contentType, title, coverUrl]);

  // Reset loading state when content changes
  useEffect(() => {
    if (contentType === "audio" || contentType === "video") {
      setIsMediaLoading(true);
      setMediaError(null);
      setDuration(0);
      setCurrentTime(0);
      setIsPlaying(false);
    }
  }, [contentUrl, contentType]);

  const handleUpvote = async (count: number) => {
    if (!contentKey || !operatorAddress) return;
    const success = await upvote(contentKey, operatorAddress, count);
    if (success) {
      setLocalUpvotes((prev) => prev + count);
      setShowUpvoteModal(false);
    }
  };

  useEffect(() => {
    if (isConfirmed) {
      const timer = setTimeout(() => {
        onUpvoteSuccess?.();
      }, 2000);
      return () => clearTimeout(timer);
    }
  }, [isConfirmed, onUpvoteSuccess]);

  // Auto-unlock from sessionStorage if the user previously checked "Remember for session"
  useEffect(() => {
    if (!isEncrypted || !contentKey) return;
    try {
      const saved = sessionStorage.getItem(`net-pw-${contentKey}`);
      if (saved) {
        // Re-use the remembered password to decrypt silently on mount
        (async () => {
          try {
            const res = await fetch(contentUrl);
            if (!res.ok) return;
            const encryptedBase64 = await res.text();
            // decryptContent is already statically imported at the top of this file
            const plainBuffer = await decryptContent(encryptedBase64.trim(), saved);
            const mimeMap: Record<string, string> = {
              pdf: "application/pdf",
              image: "image/*",
              audio: "audio/*",
              video: "video/*",
              text: "text/plain",
              unknown: "application/octet-stream",
            };
            const blob = new Blob([plainBuffer], { type: mimeMap[contentType] ?? "application/octet-stream" });
            setDecryptedUrl(URL.createObjectURL(blob));
            setIsLocked(false);
          } catch (err) {
            // Only clear the saved password if it was actually wrong (DOMException from
            // SubtleCrypto auth-tag failure). For transient network/fetch errors, keep the
            // password so the user doesn't need to re-enter it on the next open.
            if (err instanceof DOMException) {
              sessionStorage.removeItem(`net-pw-${contentKey}`);
            }
            // Either way, fall back to the lock screen silently
          }
        })();
      }
    } catch {
      // sessionStorage not available (private mode / SSR) — ignore
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // Run once on mount only

  // Handle /storage/raw/ URLs: these endpoints return JSON { key, text, data }
  // instead of raw binary, so browsers can't render them directly.
  // The `data` field is base64-encoded on storedon.net (or legacy "0x…" hex on other
  // operators). Detect the encoding, decode to bytes, wrap in a blob URL, and let all
  // downstream rendering paths work normally.
  useEffect(() => {
    // Only run for un-encrypted items (encrypted items already go through the decrypt flow)
    // and only when the raw URL is not already a blob URL.
    if (isEncrypted || !contentUrl || !contentUrl.includes("/storage/raw/")) return;
    if (decryptedUrl) return; // Already resolved

    let cancelled = false;
    (async () => {
      try {
        const res = await fetch(contentUrl);
        if (!res.ok) return;
        const json = await res.json();
        if (!json.data || cancelled) return;

        // storedon.net returns base64-encoded data, but the field may also carry
        // a legacy "0x…" hex string from other operators.  Detect which encoding
        // is in use and decode accordingly.
        let bytes: Uint8Array;
        if (json.data.startsWith("0x") || /^[0-9a-fA-F]+$/.test(json.data)) {
          // Hex-encoded (legacy / other operators)
          const hex: string = json.data.startsWith("0x") ? json.data.slice(2) : json.data;
          bytes = new Uint8Array(hex.length / 2);
          for (let i = 0; i < bytes.length; i++) {
            bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
          }
        } else {
          // Base64-encoded (storedon.net standard)
          const binary = atob(json.data);
          bytes = new Uint8Array(binary.length);
          for (let i = 0; i < binary.length; i++) {
            bytes[i] = binary.charCodeAt(i);
          }
        }

        const mimeMap: Record<string, string> = {
          pdf: "application/pdf",
          image: "image/*",
          audio: "audio/*",
          video: "video/*",
          text: "text/plain",
          unknown: "application/octet-stream",
        };
        const blob = new Blob([bytes], { type: mimeMap[contentType] ?? "application/octet-stream" });
        if (!cancelled) {
          setDecryptedUrl(URL.createObjectURL(blob));
        }
      } catch (err) {
        // Non-JSON response or network error — leave the URL as-is and let the
        // browser's native rendering handle it (or show its own error state).
        console.warn("[MultimediaViewer] /storage/raw/ decode failed:", err);
      }
    })();

    return () => { cancelled = true; };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [contentUrl, contentType, isEncrypted]); // decryptedUrl intentionally omitted — this only runs when it's null

  // Load text content if applicable
  useEffect(() => {
    // For encrypted text, wait until decrypted — activeContentUrl will be a blob URL
    if (contentType === "text" && activeContentUrl && !isLocked) {
      setIsLoadingText(true);

      // Check if this is a storedon.net URL that needs proxying due to CORS
      // Use our /api/media-proxy endpoint to avoid CORS issues
      // (Blob URLs from decryption skip the proxy path — they're already local)
      let fetchUrl = activeContentUrl;
      if (activeContentUrl.includes("storedon.net") && contentKey && operatorAddress) {
        // Use the media proxy to avoid CORS
        fetchUrl = `/api/media-proxy?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&mediaType=text&storageType=regular`;
        console.log("[MultimediaViewer] Using media proxy for text:", fetchUrl);
      } else {
        // Normalize the URL in case it's a production URL in dev
        fetchUrl = normalizeCoverUrl(activeContentUrl) || activeContentUrl;
        console.log("[MultimediaViewer] Fetching text from:", fetchUrl);
      }

      fetch(fetchUrl)
        .then(res => {
          if (!res.ok) {
            console.error("[MultimediaViewer] Text fetch failed:", res.status, res.statusText);
            throw new Error(`HTTP ${res.status}`);
          }
          return res.text();
        })
        .then(text => {
          setTextContent(text);
          setIsLoadingText(false);
        })
        .catch((err) => {
          console.error("[MultimediaViewer] Text fetch error:", err, "URL:", fetchUrl);
          setTextContent("Failed to load content. The file may no longer be available.");
          setIsLoadingText(false);
        });
    }
  }, [contentType, activeContentUrl, contentKey, operatorAddress, isLocked]);

  // Media control handlers
  const togglePlay = async () => {
    if (mediaRef.current) {
      if (isPlaying) {
        mediaRef.current.pause();
        setIsPlaying(false);
      } else {
        try {
          await mediaRef.current.play();
          setIsPlaying(true);
        } catch (err) {
          console.error("[MultimediaViewer] Play failed:", err);
          // Try to recover - sometimes need user interaction first
          setIsPlaying(false);
        }
      }
    }
  };

  // Toggle mute
  const toggleMute = () => {
    if (mediaRef.current) {
      if (isMuted) {
        // Unmute - restore previous volume
        mediaRef.current.muted = false;
        mediaRef.current.volume = previousVolume;
        setVolume(previousVolume);
        setIsMuted(false);
      } else {
        // Mute - save current volume and mute
        setPreviousVolume(volume);
        mediaRef.current.muted = true;
        setIsMuted(true);
      }
    }
  };

  const handleTimeUpdate = () => {
    if (mediaRef.current) {
      setCurrentTime(mediaRef.current.currentTime);
    }
  };

  const handleLoadedMetadata = () => {
    if (mediaRef.current) {
      console.log("[MultimediaViewer] Metadata loaded, duration:", mediaRef.current.duration);
      setDuration(mediaRef.current.duration);
      setIsMediaLoading(false);
      setMediaError(null);
    }
  };

  const handleCanPlay = () => {
    console.log("[MultimediaViewer] Can play");
    setIsMediaLoading(false);
  };

  const handleMediaError = (e: React.SyntheticEvent<HTMLAudioElement | HTMLVideoElement>) => {
    const target = e.target as HTMLAudioElement | HTMLVideoElement;
    const error = target.error;
    console.error("[MultimediaViewer] Media error:", error?.message, "code:", error?.code, "url:", contentUrl);
    setMediaError(error?.message || "Failed to load media");
    setIsMediaLoading(false);
  };

  const handleSeek = (e: React.ChangeEvent<HTMLInputElement>) => {
    const time = parseFloat(e.target.value);
    if (mediaRef.current) {
      mediaRef.current.currentTime = time;
      setCurrentTime(time);
    }
  };

  const formatTime = (seconds: number, isTotal = false) => {
    // Show "--:--" for total duration while still loading (duration is 0 or NaN)
    if (isTotal && (seconds === 0 || isNaN(seconds) || !isFinite(seconds))) {
      return "--:--";
    }
    const mins = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${mins}:${secs.toString().padStart(2, "0")}`;
  };

  // Decrypt handler — fetches encrypted blob, decrypts with password, creates object URL
  const handleUnlock = async () => {
    if (!passwordInput.trim()) return;
    setIsDecrypting(true);
    setDecryptError(null);
    try {
      // Fetch the encrypted content
      const res = await fetch(contentUrl);
      if (!res.ok) throw new Error(`Failed to fetch content (HTTP ${res.status})`);
      const encryptedBase64 = await res.text();

      // Decrypt in the browser
      const plainBuffer = await decryptContent(encryptedBase64.trim(), passwordInput);

      // Create a blob URL so the existing renderers work unchanged
      const mimeMap: Record<ContentType, string> = {
        pdf: "application/pdf",
        image: "image/*",
        audio: "audio/*",
        video: "video/*",
        text: "text/plain",
        unknown: "application/octet-stream",
      };
      const blob = new Blob([plainBuffer], { type: mimeMap[contentType] || "application/octet-stream" });
      const blobUrl = URL.createObjectURL(blob);
      setDecryptedUrl(blobUrl);
      setIsLocked(false);
      // Persist password in sessionStorage if the user opted in (never survives tab close)
      if (rememberPassword && contentKey) {
        try {
          sessionStorage.setItem(`net-pw-${contentKey}`, passwordInput);
        } catch {
          // sessionStorage not available — ignore
        }
      }
      setPasswordInput("");
    } catch (err) {
      // DOMException from SubtleCrypto means wrong password; other errors are fetch/parse failures
      const isDomException = err instanceof DOMException;
      setDecryptError(
        isDomException
          ? "Incorrect password. Please try again."
          : "Failed to decrypt content. Check the password and try again."
      );
    } finally {
      setIsDecrypting(false);
    }
  };

  // Image zoom/pan handlers
  const handleImageWheel = (e: React.WheelEvent) => {
    e.preventDefault();
    const delta = e.deltaY > 0 ? 0.9 : 1.1;
    setImageZoom(prev => Math.min(Math.max(prev * delta, 0.5), 5));
  };

  const handleImageMouseDown = (e: React.MouseEvent) => {
    setIsDragging(true);
    lastTouchRef.current = { x: e.clientX, y: e.clientY };
  };

  const handleImageMouseMove = (e: React.MouseEvent) => {
    if (!isDragging || !lastTouchRef.current) return;
    const dx = e.clientX - lastTouchRef.current.x;
    const dy = e.clientY - lastTouchRef.current.y;
    setImagePan(prev => ({ x: prev.x + dx, y: prev.y + dy }));
    lastTouchRef.current = { x: e.clientX, y: e.clientY };
  };

  const handleImageMouseUp = () => {
    setIsDragging(false);
    lastTouchRef.current = null;
  };

  const resetImageView = () => {
    setImageZoom(1);
    setImagePan({ x: 0, y: 0 });
  };

  // Render content based on type
  const renderContent = () => {
    // Password gate — shown instead of content when item is encrypted and not yet unlocked
    if (isLocked) {
      return (
        <div className="flex-1 flex items-center justify-center bg-black p-6">
          <div className="w-full max-w-sm space-y-4">
            <div className="text-center space-y-2">
              <div className="text-4xl">🔒</div>
              <P className="text-[#00ff00] font-mono font-bold">Encrypted Content</P>
              <Small className="text-gray-400 font-mono block">
                This item is password-protected. Enter the password to view it.
              </Small>
            </div>

            <div className="space-y-3">
              <input
                type="password"
                value={passwordInput}
                onChange={(e) => {
                  setPasswordInput(e.target.value);
                  setDecryptError(null);
                }}
                onKeyDown={(e) => e.key === "Enter" && !isDecrypting && handleUnlock()}
                placeholder="Enter password…"
                className="w-full px-3 py-2.5 rounded-lg bg-[#1a1a1a] border border-[#00ff00]/30 text-white font-mono text-sm placeholder-gray-600 focus:outline-none focus:border-[#00ff00]/70"
                autoFocus
              />

              {decryptError && (
                <div className="p-2 rounded bg-red-500/10 border border-red-500/30">
                  <Small className="text-red-400 font-mono text-xs">{decryptError}</Small>
                </div>
              )}

              {/* Remember password for this session (sessionStorage — never persisted to disk) */}
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={rememberPassword}
                  onChange={(e) => setRememberPassword(e.target.checked)}
                  className="rounded border-[#00ff00]/30 bg-[#1a1a1a] text-[#00ff00] focus:ring-[#00ff00]"
                />
                <Small className="text-gray-400 font-mono text-xs">Remember for this session</Small>
              </label>

              <button
                onClick={handleUnlock}
                disabled={isDecrypting || !passwordInput.trim()}
                className="w-full py-2.5 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] font-mono font-bold hover:bg-[#00ff00]/20 transition-colors disabled:opacity-40"
              >
                {isDecrypting ? "Decrypting…" : "Unlock"}
              </button>
            </div>
          </div>
        </div>
      );
    }

    switch (contentType) {
      case "pdf":
        return (
          <div className="flex-1 overflow-hidden bg-white">
            <iframe
              src={activeContentUrl}
              title={title}
              className="w-full h-full border-none"
              style={{
                minHeight: "100%",
                background: "white"
              }}
            />
          </div>
        );

      case "image": {
        // Normalize content URL to work in both dev and production
        const normalizedContentUrl = normalizeCoverUrl(activeContentUrl) || activeContentUrl;
        return (
          <div
            className="flex-1 overflow-hidden bg-[#1a1a1a] flex items-center justify-center cursor-move relative"
            style={{
              // Subtle checkered pattern to show image boundaries (like Photoshop transparency grid)
              backgroundImage: `
                linear-gradient(45deg, #222 25%, transparent 25%),
                linear-gradient(-45deg, #222 25%, transparent 25%),
                linear-gradient(45deg, transparent 75%, #222 75%),
                linear-gradient(-45deg, transparent 75%, #222 75%)
              `,
              backgroundSize: "20px 20px",
              backgroundPosition: "0 0, 0 10px, 10px -10px, -10px 0px",
            }}
            onWheel={handleImageWheel}
            onMouseDown={handleImageMouseDown}
            onMouseMove={handleImageMouseMove}
            onMouseUp={handleImageMouseUp}
            onMouseLeave={handleImageMouseUp}
          >
            {/* Subtle drop shadow on image to separate from background */}
            <img
              src={normalizedContentUrl}
              alt={title}
              className="max-w-full max-h-full object-contain transition-transform duration-100 shadow-2xl"
              style={{
                transform: `scale(${imageZoom}) translate(${imagePan.x / imageZoom}px, ${imagePan.y / imageZoom}px)`,
                // Adds a glow effect to help dark images stand out
                boxShadow: "0 0 40px rgba(0, 255, 0, 0.15), 0 25px 50px -12px rgba(0, 0, 0, 0.5)",
              }}
              draggable={false}
            />

            {/* Branding overlay - Net Library logo (bottom-left, only for non-social receipts) */}
            {!socialPlatform && (
              <div className="absolute bottom-4 left-4 flex items-center gap-2 px-3 py-2 rounded-lg bg-black/70 backdrop-blur-sm border border-[#00ff00]/20">
                <img
                  src="/app-logo.png"
                  alt="Net Library"
                  className="w-6 h-6 rounded"
                />
                <span className="text-[#00ff00] font-mono text-xs font-medium tracking-wide">
                  NET LIBRARY
                </span>
              </div>
            )}

            {/* Zoom controls */}
            <div className="absolute bottom-4 right-4 flex items-center gap-2">
              <button
                onClick={() => setImageZoom(prev => Math.max(prev * 0.8, 0.5))}
                className="w-10 h-10 rounded-full bg-black/80 border border-[#00ff00]/30 text-[#00ff00] font-bold hover:bg-[#00ff00]/10"
              >
                −
              </button>
              <span className="px-3 py-1 rounded bg-black/80 text-[#00ff00] font-mono text-sm">
                {Math.round(imageZoom * 100)}%
              </span>
              <button
                onClick={() => setImageZoom(prev => Math.min(prev * 1.2, 5))}
                className="w-10 h-10 rounded-full bg-black/80 border border-[#00ff00]/30 text-[#00ff00] font-bold hover:bg-[#00ff00]/10"
              >
                +
              </button>
              <button
                onClick={resetImageView}
                className="px-3 py-2 rounded bg-black/80 border border-[#00ff00]/30 text-[#00ff00] font-mono text-xs hover:bg-[#00ff00]/10"
              >
                Reset
              </button>
            </div>
          </div>
        );
      }

      case "audio": {
        // Normalize cover URL to work in both local dev and production
        const normalizedCoverUrl = normalizeCoverUrl(coverUrl);
        return (
          <div className="flex-1 flex flex-col items-center justify-center bg-gradient-to-br from-[#0a0a0a] to-[#1a1a1a] p-8">
            {/* Album art - use coverUrl if available, otherwise show placeholder */}
            {normalizedCoverUrl ? (
              <div className="w-48 h-48 rounded-xl overflow-hidden mb-8 shadow-lg shadow-[#00ff00]/20 border border-[#00ff00]/30">
                <img
                  src={normalizedCoverUrl}
                  alt={title}
                  className="w-full h-full object-cover"
                  onError={(e) => {
                    // Fallback to placeholder if image fails to load
                    const target = e.target as HTMLImageElement;
                    target.style.display = "none";
                    const parent = target.parentElement;
                    if (parent) {
                      parent.innerHTML = '<span class="text-6xl flex items-center justify-center w-full h-full bg-gradient-to-br from-[#00ff00]/20 to-[#00ff00]/5">🎵</span>';
                    }
                  }}
                />
              </div>
            ) : (
              <div className="w-48 h-48 rounded-xl bg-gradient-to-br from-[#00ff00]/20 to-[#00ff00]/5 border border-[#00ff00]/30 flex items-center justify-center mb-8">
                <span className="text-6xl">🎵</span>
              </div>
            )}

            {/* Title & Author */}
            <P className="text-white font-mono text-lg font-bold text-center mb-1">{title}</P>
            <Small className="text-gray-400 font-mono mb-8">{author}</Small>

            {/* Audio element (hidden) */}
            <audio
              ref={mediaRef as React.RefObject<HTMLAudioElement>}
              src={activeContentUrl}
              onTimeUpdate={handleTimeUpdate}
              onLoadedMetadata={handleLoadedMetadata}
              onCanPlay={handleCanPlay}
              onError={handleMediaError}
              onEnded={() => setIsPlaying(false)}
              onPlay={() => setIsPlaying(true)}
              onPause={() => setIsPlaying(false)}
              preload="auto"
            />

            {/* Loading/Error state */}
            {isMediaLoading && !mediaError && (
              <div className="text-[#00ff00] font-mono text-sm mb-4 animate-pulse">
                Loading audio...
              </div>
            )}
            {mediaError && (
              <div className="text-red-400 font-mono text-sm mb-4 p-3 bg-red-500/10 border border-red-500/30 rounded-lg flex items-start gap-2">
                <WarningIcon size={16} className="shrink-0 mt-0.5" />
                <div>
                  {mediaError}
                  <div className="text-xs text-gray-500 mt-1 break-all">URL: {activeContentUrl}</div>
                </div>
              </div>
            )}

            {/* Progress bar */}
            <div className="w-full max-w-md mb-4">
              <input
                type="range"
                min={0}
                max={duration || 100}
                value={currentTime}
                onChange={handleSeek}
                className="w-full h-2 bg-gray-800 rounded-lg appearance-none cursor-pointer accent-[#00ff00]"
              />
              <div className="flex justify-between mt-1">
                <Small className="text-gray-500 font-mono">{formatTime(currentTime)}</Small>
                <Small className="text-gray-500 font-mono">{formatTime(duration, true)}</Small>
              </div>
            </div>

            {/* Controls */}
            <div className="flex items-center gap-4">
              <button
                onClick={() => {
                  if (mediaRef.current) mediaRef.current.currentTime -= 10;
                }}
                className="w-12 h-12 rounded-full bg-black border border-[#00ff00]/30 text-[#00ff00] font-mono text-sm hover:bg-[#00ff00]/10"
              >
                -10s
              </button>
              <button
                onClick={togglePlay}
                className={`w-16 h-16 rounded-full font-bold text-2xl transition-colors flex items-center justify-center ${
                  isPlaying
                    ? "bg-black border-2 border-[#00ff00] text-[#00ff00] hover:bg-[#00ff00]/10"
                    : "bg-[#00ff00] text-black hover:bg-[#00ff00]/90"
                }`}
              >
                {isPlaying ? (
                  <span className="flex items-center gap-1">
                    <span className="w-1.5 h-6 bg-[#00ff00] rounded-sm"></span>
                    <span className="w-1.5 h-6 bg-[#00ff00] rounded-sm"></span>
                  </span>
                ) : (
                  "▶"
                )}
              </button>
              <button
                onClick={() => {
                  if (mediaRef.current) mediaRef.current.currentTime += 10;
                }}
                className="w-12 h-12 rounded-full bg-black border border-[#00ff00]/30 text-[#00ff00] font-mono text-sm hover:bg-[#00ff00]/10"
              >
                +10s
              </button>
            </div>

            {/* Volume with mute button */}
            <div className="flex items-center gap-3 mt-6">
              <button
                onClick={toggleMute}
                className="w-10 h-10 rounded-full bg-black border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/10 flex items-center justify-center transition-colors"
                title={isMuted ? "Unmute" : "Mute"}
              >
                {isMuted ? "🔇" : volume > 0.5 ? "🔊" : volume > 0 ? "🔉" : "🔈"}
              </button>
              <input
                type="range"
                min={0}
                max={1}
                step={0.1}
                value={isMuted ? 0 : volume}
                onChange={(e) => {
                  const v = parseFloat(e.target.value);
                  setVolume(v);
                  setIsMuted(v === 0);
                  if (mediaRef.current) {
                    mediaRef.current.volume = v;
                    mediaRef.current.muted = v === 0;
                  }
                }}
                className="w-24 h-2 bg-gray-800 rounded-lg appearance-none cursor-pointer accent-[#00ff00]"
              />
            </div>
          </div>
        );
      }

      case "video": {
        // Normalize cover URL for video poster
        const normalizedVideoPoster = normalizeCoverUrl(coverUrl);
        return (
          <div className="flex-1 flex flex-col bg-black">
            {/* Video player */}
            <div className="flex-1 flex items-center justify-center relative">
              <video
                ref={mediaRef as React.RefObject<HTMLVideoElement>}
                src={activeContentUrl}
                className="max-w-full max-h-full"
                onTimeUpdate={handleTimeUpdate}
                onLoadedMetadata={handleLoadedMetadata}
                onCanPlay={handleCanPlay}
                onError={handleMediaError}
                onEnded={() => setIsPlaying(false)}
                onPlay={() => setIsPlaying(true)}
                onPause={() => setIsPlaying(false)}
                onClick={togglePlay}
                preload="auto"
                poster={normalizedVideoPoster} // Use cover image as video poster
              />

              {/* Loading overlay */}
              {isMediaLoading && !mediaError && (
                <div className="absolute inset-0 flex items-center justify-center bg-black/50">
                  <div className="text-[#00ff00] font-mono text-sm animate-pulse">Loading video...</div>
                </div>
              )}

              {/* Error overlay */}
              {mediaError && (
                <div className="absolute inset-0 flex items-center justify-center bg-black/80">
                  <div className="text-red-400 font-mono text-sm p-4 bg-red-500/10 border border-red-500/30 rounded-lg max-w-xs text-center">
                    <WarningIcon size={18} className="mx-auto mb-2" />
                    {mediaError}
                    <div className="text-xs text-gray-500 mt-2 break-all">URL: {activeContentUrl}</div>
                  </div>
                </div>
              )}

              {/* Play overlay */}
              {!isPlaying && !isMediaLoading && !mediaError && (
                <button
                  onClick={togglePlay}
                  className="absolute inset-0 flex items-center justify-center bg-black/30"
                >
                  <div className="w-20 h-20 rounded-full bg-[#00ff00]/90 text-black text-4xl flex items-center justify-center hover:bg-[#00ff00] transition-colors">
                    ▶
                  </div>
                </button>
              )}
            </div>

            {/* Controls */}
            <div className="p-4 bg-black/90 border-t border-[#00ff00]/20">
              {/* Progress */}
              <div className="mb-3">
                <input
                  type="range"
                  min={0}
                  max={duration || 100}
                  value={currentTime}
                  onChange={handleSeek}
                  className="w-full h-2 bg-gray-800 rounded-lg appearance-none cursor-pointer accent-[#00ff00]"
                />
                <div className="flex justify-between mt-1">
                  <Small className="text-gray-500 font-mono">{formatTime(currentTime)}</Small>
                  <Small className="text-gray-500 font-mono">{formatTime(duration, true)}</Small>
                </div>
              </div>

              {/* Buttons */}
              <div className="flex items-center justify-center gap-4">
                <button
                  onClick={() => {
                    if (mediaRef.current) mediaRef.current.currentTime -= 10;
                  }}
                  className="px-3 py-1 rounded bg-black border border-[#00ff00]/30 text-[#00ff00] font-mono text-sm hover:bg-[#00ff00]/10"
                >
                  -10s
                </button>
                <button
                  onClick={togglePlay}
                  className={`w-12 h-12 rounded-full font-bold text-xl transition-colors flex items-center justify-center ${
                    isPlaying
                      ? "bg-black border-2 border-[#00ff00] text-[#00ff00] hover:bg-[#00ff00]/10"
                      : "bg-[#00ff00] text-black hover:bg-[#00ff00]/90"
                  }`}
                >
                  {isPlaying ? (
                    <span className="flex items-center gap-0.5">
                      <span className="w-1 h-5 bg-[#00ff00] rounded-sm"></span>
                      <span className="w-1 h-5 bg-[#00ff00] rounded-sm"></span>
                    </span>
                  ) : (
                    "▶"
                  )}
                </button>
                <button
                  onClick={() => {
                    if (mediaRef.current) mediaRef.current.currentTime += 10;
                  }}
                  className="px-3 py-1 rounded bg-black border border-[#00ff00]/30 text-[#00ff00] font-mono text-sm hover:bg-[#00ff00]/10"
                >
                  +10s
                </button>

                {/* Volume with mute button */}
                <div className="flex items-center gap-2 ml-4">
                  <button
                    onClick={toggleMute}
                    className="w-8 h-8 rounded-full bg-black border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/10 flex items-center justify-center transition-colors text-sm"
                    title={isMuted ? "Unmute" : "Mute"}
                  >
                    {isMuted ? "🔇" : volume > 0.5 ? "🔊" : volume > 0 ? "🔉" : "🔈"}
                  </button>
                  <input
                    type="range"
                    min={0}
                    max={1}
                    step={0.1}
                    value={isMuted ? 0 : volume}
                    onChange={(e) => {
                      const v = parseFloat(e.target.value);
                      setVolume(v);
                      setIsMuted(v === 0);
                      if (mediaRef.current) {
                        mediaRef.current.volume = v;
                        mediaRef.current.muted = v === 0;
                      }
                    }}
                    className="w-20 h-2 bg-gray-800 rounded-lg appearance-none cursor-pointer accent-[#00ff00]"
                  />
                </div>
              </div>
            </div>
          </div>
        );
      }

      case "text":
        return (
          <div className="flex-1 overflow-y-auto p-4 bg-black relative">
            {isLoadingText ? (
              <div className="flex items-center justify-center h-full">
                <div className="text-[#00ff00] font-mono animate-pulse">Loading...</div>
              </div>
            ) : (
              <div
                className="prose prose-invert prose-green max-w-none font-mono leading-relaxed"
                style={{ fontSize: `${textFontSize}px` }}
              >
                <ReactMarkdown
                  components={{
                    // Style links to be clickable and green - use safeOpenUrl to break out of mini app
                    a: ({ href, children }) => (
                      <button
                        onClick={(e) => {
                          e.preventDefault();
                          if (href) safeOpenUrl(href);
                        }}
                        className="text-[#00ff00] underline hover:text-[#00ff00]/80 transition-colors cursor-pointer inline"
                      >
                        {children}
                      </button>
                    ),
                    // Style paragraphs
                    p: ({ children }) => (
                      <p className="text-white mb-4 whitespace-pre-wrap">{children}</p>
                    ),
                    // Style headers
                    h1: ({ children }) => (
                      <h1 className="text-[#00ff00] text-2xl font-bold mb-4 mt-6">{children}</h1>
                    ),
                    h2: ({ children }) => (
                      <h2 className="text-[#00ff00] text-xl font-bold mb-3 mt-5">{children}</h2>
                    ),
                    h3: ({ children }) => (
                      <h3 className="text-[#00ff00] text-lg font-bold mb-2 mt-4">{children}</h3>
                    ),
                    // Style lists
                    ul: ({ children }) => (
                      <ul className="list-disc list-inside text-white mb-4 space-y-1">{children}</ul>
                    ),
                    ol: ({ children }) => (
                      <ol className="list-decimal list-inside text-white mb-4 space-y-1">{children}</ol>
                    ),
                    li: ({ children }) => (
                      <li className="text-white">{children}</li>
                    ),
                    // Style bold and italic
                    strong: ({ children }) => (
                      <strong className="text-white font-bold">{children}</strong>
                    ),
                    em: ({ children }) => (
                      <em className="text-white italic">{children}</em>
                    ),
                    // Style code blocks
                    code: ({ children }) => (
                      <code className="bg-[#1a1a1a] text-[#00ff00] px-1.5 py-0.5 rounded text-sm">{children}</code>
                    ),
                    pre: ({ children }) => (
                      <pre className="bg-[#1a1a1a] border border-[#00ff00]/20 rounded-lg p-4 overflow-x-auto mb-4">{children}</pre>
                    ),
                    // Style blockquotes
                    blockquote: ({ children }) => (
                      <blockquote className="border-l-4 border-[#00ff00]/50 pl-4 italic text-gray-300 mb-4">{children}</blockquote>
                    ),
                  }}
                >
                  {textContent}
                </ReactMarkdown>
              </div>
            )}

            {/* Font size controls */}
            <div className="fixed bottom-24 right-4 flex flex-col gap-2 z-40">
              <button
                onClick={() => setTextFontSize(prev => Math.min(prev + 2, 28))}
                className="w-10 h-10 rounded-full bg-black/80 border border-[#00ff00]/30 text-[#00ff00] font-bold hover:bg-[#00ff00]/10 flex items-center justify-center"
                title="Increase font size"
              >
                A+
              </button>
              <span className="text-center text-[#00ff00] font-mono text-xs bg-black/80 rounded px-1">
                {textFontSize}px
              </span>
              <button
                onClick={() => setTextFontSize(prev => Math.max(prev - 2, 10))}
                className="w-10 h-10 rounded-full bg-black/80 border border-[#00ff00]/30 text-[#00ff00] font-bold hover:bg-[#00ff00]/10 flex items-center justify-center"
                title="Decrease font size"
              >
                A-
              </button>
            </div>
          </div>
        );

      default:
        return (
          <div className="flex-1 flex items-center justify-center bg-[#0a0a0a]">
            <div className="text-center">
              <span className="text-6xl block mb-4">📦</span>
              <P className="text-gray-400 font-mono mb-4">This content type is not supported for preview.</P>
              <a
                href={activeContentUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="inline-block px-4 py-2 rounded-lg bg-[#00ff00] text-black font-mono font-bold hover:bg-[#00ff00]/90"
              >
                Open in New Tab
              </a>
            </div>
          </div>
        );
    }
  };

  return (
    <div className="h-dvh flex flex-col overflow-hidden bg-black">
      {/* Header - hidden in fullscreen */}
      {!isFullscreen && (
        <header className="shrink-0 px-4 py-3 border-b border-[#00ff00]/30 flex items-center gap-3 bg-black">
          <button
            onClick={onBack}
            className="w-10 h-10 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222]"
          >
            ←
          </button>
          <div className="flex-1 min-w-0">
            <p className="text-[#00ff00] font-mono text-sm font-bold tracking-tight truncate">{title}</p>
            <p className="text-gray-500 font-mono text-xs truncate">{author}</p>
          </div>
          {/* Fullscreen button */}
          <button
            onClick={() => setIsFullscreen(true)}
            className="w-10 h-10 rounded-full bg-[#1a1a1a] flex items-center justify-center text-[#00ff00] hover:bg-[#222] border border-[#00ff00]/30"
            title="Enter fullscreen"
          >
            ⛶
          </button>
        </header>
      )}

      {/* Content */}
      {renderContent()}

      {/* Footer with actions - hidden in fullscreen */}
      {!isFullscreen && (
        <footer className="shrink-0 px-4 py-3 border-t border-[#00ff00]/30 bg-black">
          <div className="flex items-center justify-between">
            {/* Upvote */}
            <button
              onClick={() => setShowUpvoteModal(true)}
              disabled={isUpvoting}
              className="flex items-center gap-2 px-4 py-2 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] font-mono hover:bg-[#00ff00]/20 transition-colors disabled:opacity-50"
            >
              <span className="text-lg">▲</span>
              <span className="font-bold">{displayUpvotes}</span>
            </button>

            {/* Share */}
            <Button
              onClick={onShare}
              className="bg-[#00ff00] text-black font-mono font-bold px-6 hover:bg-[#00ff00]/90"
            >
              Share
            </Button>
          </div>
        </footer>
      )}

      {/* Exit fullscreen button - only visible in fullscreen mode */}
      {isFullscreen && (
        <button
          onClick={() => setIsFullscreen(false)}
          className="fixed top-4 right-4 z-50 w-12 h-12 rounded-full bg-black/80 backdrop-blur border border-[#00ff00]/50 flex items-center justify-center text-[#00ff00] hover:bg-black/90 transition-colors shadow-lg"
          title="Exit fullscreen"
        >
          ✕
        </button>
      )}

      {/* Upvote Modal */}
      <UpvoteModal
        isOpen={showUpvoteModal}
        onClose={() => setShowUpvoteModal(false)}
        onUpvote={handleUpvote}
        isUpvoting={isUpvoting}
        bookTitle={title}
        currentUpvotes={displayUpvotes}
      />
    </div>
  );
}
src/features/app/components/my-library-tab.tsx
"use client";

import React, { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { useAccount, useBalance } from "wagmi";
import { Card, CardContent, P, Small } from "@neynar/ui";
import { useSponsoredTransaction } from "@/hooks/use-sponsored-transaction";
import { useDiscoveryContext } from "@/contexts/discovery-context";
import { useLeaderboard } from "@/hooks/use-leaderboard";
import { useMembership } from "@/hooks/use-membership";
import { useUserStats } from "@/hooks/use-user-stats";
import { useActiveMembers } from "@/hooks/use-active-members";
import { useUserNetLink } from "@/hooks/use-user-net-link";
import { useUpvoteCounts } from "@/hooks/use-upvotes";
import { useMemberUpvote, useMemberUpvoteCounts } from "@/hooks/use-member-upvotes";
import { useMemberProfile } from "@/contexts/member-profile-context";
import { useUserProfile } from "@/hooks/use-user-profile";
import { AchievementsSection, MemberResourcesSection } from "./achievements";
import { TrendingShareButton } from "./trending-share";
import { LinkToNetModal } from "./link-to-net-modal";
import { LinkFarcasterModal } from "./link-farcaster-modal";
import { LinkBaseModal } from "./link-base-modal";
import { CreateStackModal } from "./create-stack-modal";
import { AddToStackModal } from "./add-to-stack-modal";
import { LibraryCardShareModal } from "./library-card-share-modal";
import { WebProfileEditor } from "./web-profile-editor";
import { EditItemModal } from "./edit-item-modal";
import { UserLibraryCardModal } from "./user-library-card-modal";
import { MemberUpvoteModal } from "./member-upvote-modal";
import { CoverImage } from "./cover-image";
import { AirdropModal } from "./airdrop-modal";
import { useStoragePassModal } from "./unlimited-storage-pass-modal";
import { safeOpenUrl, useAppMode } from "@/lib/app-mode";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { usePlatformStatus } from "@/hooks/use-platform-status";
import { useUserStacks } from "@/hooks/use-stacks";
import { useGrids } from "@/hooks/use-grids";
import { formatUnits, type Address } from "viem";
import { base } from "viem/chains";
import type { Category } from "@/features/app/types";
import type { DiscoveryEntry, GridCell, GridWithStats } from "@/lib/net-protocol";
import { getUserFriendlyCdnUrl, BASE_CHAIN_ID, decodeBytes32Key } from "@/lib/net-protocol";
import {
  UserIcon,
  LibraryIcon,
  UploadIcon,
  DownloadIcon,
  SearchIcon,
  CopyIcon,
  TrophyIcon,
  WarningIcon,
  CheckIcon,
  CloseIcon,
  LoadingIcon,
  BookmarkIcon,
  EditIcon,
  WalletIcon,
  PartyIcon,
  GridIcon,
  EyeIcon,
  EyeOffIcon,
  LinkIcon,
  LockIcon,
  FarcasterIcon,
  BaseIcon,
  WebIcon,
  DocumentIcon,
  ParachuteIcon,
  SaveIcon,
  ClipboardIcon,
  CheckCircleIcon,
} from "@/components/icons/net-library-icons";

// Get best cover URL - prefers coverUrl, falls back to cdnUrl for visual content
// Note: Don't convert here - CoverImage handles URL normalization internally
function getEffectiveCoverUrl(entry: { coverUrl?: string; cdnUrl?: string; mediaType?: string }): string {
  // If explicit cover art is set, use it
  if (entry.coverUrl) return entry.coverUrl;

  // For image/video content, cdnUrl IS the visual content - use it as thumbnail
  if (entry.cdnUrl && entry.mediaType && ["image", "video"].includes(entry.mediaType)) {
    return entry.cdnUrl;
  }

  return '';
}

// USDC Contract on Base
const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" as Address;
const USDC_ABI = [
  {
    name: "transfer",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "to", type: "address" },
      { name: "value", type: "uint256" },
    ],
    outputs: [{ type: "bool" }],
  },
] as const;

// Braille alphabet mapping (Grade 1)
const BRAILLE_MAP: Record<string, string> = {
  'a': '⠁', 'b': '⠃', 'c': '⠉', 'd': '⠙', 'e': '⠑',
  'f': '⠋', 'g': '⠛', 'h': '⠓', 'i': '⠊', 'j': '⠚',
  'k': '⠅', 'l': '⠇', 'm': '⠍', 'n': '⠝', 'o': '⠕',
  'p': '⠏', 'q': '⠟', 'r': '⠗', 's': '⠎', 't': '⠞',
  'u': '⠥', 'v': '⠧', 'w': '⠺', 'x': '⠭', 'y': '⠽',
  'z': '⠵', '0': '⠚', '1': '⠁', '2': '⠃', '3': '⠉',
  '4': '⠙', '5': '⠑', '6': '⠋', '7': '⠛', '8': '⠓',
  '9': '⠊', ' ': '⠀', '.': '⠲', ',': '⠂', '-': '⠤',
  '_': '⠸', '@': '⠈⠁'
};

function toBraille(text: string): string {
  return (text || '').toLowerCase().split('').map(char => BRAILLE_MAP[char] || char).join('');
}

// Treasury address for membership mints (netlibrary.eth)
const TREASURY_ADDRESS = "0xAcAD71e697Ef3bb148093b2DD2fCf0845e957627" as const;
const MEMBERSHIP_COST_USDC = 2;

// Info tooltip component - positioned to stay within bounds
// Position "left" means tooltip appears LEFT of the trigger (for right-side elements)
// Position "right" means tooltip appears RIGHT of the trigger (for left-side elements)
// Position "center" means centered below the trigger
function _InfoTooltip({ text, isOpen, onToggle, position = "center" }: { text: string; isOpen: boolean; onToggle: () => void; position?: "left" | "center" | "right" }) {
  const positionClasses = {
    left: "right-0 translate-x-0", // Anchor to right, so tooltip appears LEFT
    center: "left-1/2 -translate-x-1/2",
    right: "left-0 -translate-x-0" // Anchor to left, so tooltip appears RIGHT
  };

  return (
    <span className="relative inline-block ml-1">
      <button
        onClick={(e) => {
          e.stopPropagation();
          onToggle();
        }}
        className="text-[#00ff00]/50 hover:text-[#00ff00] text-[10px] align-super cursor-pointer"
      >
        ⓘ
      </button>
      {isOpen && (
        <div className={`absolute bottom-full ${positionClasses[position]} mb-2 w-40 p-2 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg shadow-lg z-50`}>
          <Small className="text-gray-300 font-mono text-[10px] block text-center">{text}</Small>
          <div className="absolute top-full left-1/2 -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent border-t-[#00ff00]/30" />
        </div>
      )}
    </span>
  );
}

// Upload engagement stats with tooltips
function UploadEngagementStats({ stats }: { stats: { opens: number; currentlyReading: number; addedToQueues: number; upvotes: number } }) {
  return (
    <div className="grid grid-cols-4 gap-2 mt-3 pt-3 border-t border-[#00ff00]/10">
      <div className="text-center">
        <P className="text-[#00ff00] font-mono font-bold text-sm">{stats.upvotes}</P>
        <Small className="text-gray-500 font-mono text-[9px]">▲ Upvotes</Small>
      </div>
      <div className="text-center">
        <P className="text-[#00ff00] font-mono font-bold text-sm">{stats.opens}</P>
        <Small className="text-gray-500 font-mono text-[9px]">Opens</Small>
      </div>
      <div className="text-center">
        <P className="text-[#00ff00] font-mono font-bold text-sm">{stats.currentlyReading}</P>
        <Small className="text-gray-500 font-mono text-[9px]">Reading</Small>
      </div>
      <div className="text-center">
        <P className="text-[#00ff00] font-mono font-bold text-sm">{stats.addedToQueues}</P>
        <Small className="text-gray-500 font-mono text-[9px]">Queued</Small>
      </div>
    </div>
  );
}

// Format bytes for display
function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

// Cover Art Edit Modal
// Recommended dimensions: 400x560px (5:7 aspect ratio, like a book cover)
// Minimum: 200x280px | Maximum file size: 500KB
// Supported formats: JPG, PNG, WebP
const COVER_SPECS = {
  recommendedWidth: 400,
  recommendedHeight: 560,
  minWidth: 200,
  minHeight: 280,
  maxFileSize: 500 * 1024, // 500KB
  aspectRatio: 5 / 7,
  aspectTolerance: 0.15, // Allow 15% deviation from ideal aspect ratio
};

function CoverArtModal({
  isOpen,
  onClose,
  contentKey,
  operator,
  currentCoverUrl,
  title,
  onUpdate,
}: {
  isOpen: boolean;
  onClose: () => void;
  contentKey: string;
  operator: string;
  currentCoverUrl?: string;
  title: string;
  onUpdate: () => void;
}) {
  const [coverUrl, setCoverUrl] = useState(currentCoverUrl || "");
  const [isUploading, setIsUploading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [warning, setWarning] = useState<string | null>(null);
  const [_imageDimensions, setImageDimensions] = useState<{ width: number; height: number } | null>(null);
  const [mounted, setMounted] = useState(false);
  const fileInputRef = React.useRef<HTMLInputElement>(null);

  // Track client-side mount for portal
  React.useEffect(() => {
    setMounted(true);
  }, []);

  // Validate image dimensions
  const validateImageDimensions = (width: number, height: number): { valid: boolean; warning?: string } => {
    const actualRatio = width / height;
    const ratioDiff = Math.abs(actualRatio - COVER_SPECS.aspectRatio) / COVER_SPECS.aspectRatio;

    if (width < COVER_SPECS.minWidth || height < COVER_SPECS.minHeight) {
      return {
        valid: false,
        warning: `Image too small. Minimum ${COVER_SPECS.minWidth}x${COVER_SPECS.minHeight}px required.`,
      };
    }

    if (ratioDiff > COVER_SPECS.aspectTolerance) {
      return {
        valid: true,
        warning: `Image may appear cropped. Ideal ratio is 5:7 (${COVER_SPECS.recommendedWidth}x${COVER_SPECS.recommendedHeight}px).`,
      };
    }

    return { valid: true };
  };

  // Handle file upload to get a URL
  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // Validate file type
    const validTypes = ["image/jpeg", "image/png", "image/webp"];
    if (!validTypes.includes(file.type)) {
      setError("Please use JPG, PNG, or WebP format");
      return;
    }

    // Validate file size (max 500KB)
    if (file.size > COVER_SPECS.maxFileSize) {
      setError(`Image must be under ${COVER_SPECS.maxFileSize / 1024}KB. Try compressing it.`);
      return;
    }

    setIsUploading(true);
    setError(null);
    setWarning(null);

    try {
      // Convert to base64 data URL
      const reader = new FileReader();
      reader.onload = () => {
        const dataUrl = reader.result as string;

        // Check image dimensions
        const img = new Image();
        img.onload = () => {
          const { valid, warning: dimWarning } = validateImageDimensions(img.width, img.height);
          setImageDimensions({ width: img.width, height: img.height });

          if (!valid) {
            setError(dimWarning || "Invalid image dimensions");
            setIsUploading(false);
            return;
          }

          if (dimWarning) {
            setWarning(dimWarning);
          }

          setCoverUrl(dataUrl);
          setIsUploading(false);
        };
        img.onerror = () => {
          setError("Failed to load image");
          setIsUploading(false);
        };
        img.src = dataUrl;
      };
      reader.onerror = () => {
        setError("Failed to read file");
        setIsUploading(false);
      };
      reader.readAsDataURL(file);
    } catch {
      setError("Failed to process image");
      setIsUploading(false);
    }
  };

  // Save cover URL to discovery index
  const handleSave = async () => {
    setIsSaving(true);
    setError(null);

    try {
      const response = await fetch("/api/discovery", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          contentKey,
          operator,
          coverUrl: coverUrl || null,
        }),
      });

      if (!response.ok) {
        const data = await response.json();
        throw new Error(data.error || "Failed to update");
      }

      onUpdate();
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to save");
    } finally {
      setIsSaving(false);
    }
  };

  // Remove cover art
  const handleRemove = async () => {
    setCoverUrl("");
  };

  if (!isOpen || !mounted) return null;

  const modalContent = (
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/90"
      onClick={onClose}
    >
      <div
        className="w-full max-w-sm bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="p-3 border-b border-[#00ff00]/20 flex items-center justify-between">
          <div>
            <P className="text-white font-mono font-medium text-sm">Edit Cover</P>
            <Small className="text-gray-500 font-mono text-[10px] truncate block max-w-[200px]">{title}</Small>
          </div>
          <button
            onClick={onClose}
            className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-white/10 text-gray-400 hover:text-white transition-colors"
          >
            <CloseIcon size={16} />
          </button>
        </div>

        {/* Content - compact layout */}
        <div className="p-4">
          {/* Preview + Upload side by side */}
          <div className="flex gap-4 items-center mb-4">
            {/* Preview */}
            <div className="w-20 h-28 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded-lg border-2 border-[#00ff00]/30 flex items-center justify-center overflow-hidden shrink-0">
              {coverUrl ? (
                <img src={coverUrl} alt="Cover preview" className="w-full h-full object-cover" />
              ) : (
                <BookmarkIcon size={24} className="text-[#00ff00]/50" />
              )}
            </div>

            {/* Upload area */}
            <div className="flex-1 space-y-2">
              <input
                ref={fileInputRef}
                type="file"
                accept="image/jpeg,image/png,image/webp"
                onChange={handleFileSelect}
                className="hidden"
              />
              <button
                onClick={() => fileInputRef.current?.click()}
                disabled={isUploading}
                className="w-full py-3 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg text-[#00ff00] font-mono text-sm hover:bg-[#00ff00]/20 transition-colors disabled:opacity-50"
              >
                {isUploading ? "Processing..." : <><UploadIcon size={14} className="inline mr-1" /> Upload Image</>}
              </button>
              <Small className="text-gray-500 font-mono text-[9px] text-center block">
                JPG, PNG, WebP • Max 500KB
              </Small>
            </div>
          </div>

          {/* URL Input - collapsed by default, just a subtle option */}
          <div className="border-t border-[#00ff00]/10 pt-3">
            <input
              type="text"
              value={coverUrl}
              onChange={(e) => {
                setCoverUrl(e.target.value);
                setImageDimensions(null);
                setWarning(null);
              }}
              placeholder="Or paste image URL..."
              className="w-full px-3 py-2 bg-black/50 border border-[#00ff00]/20 rounded-lg text-white font-mono text-xs focus:border-[#00ff00] focus:outline-none placeholder:text-gray-600"
            />
          </div>

          {/* Warning/Error - compact */}
          {(warning || error) && (
            <div className="mt-3">
              {warning && <Small className="text-yellow-400 font-mono text-[10px] block flex items-center gap-1"><WarningIcon size={12} /> {warning}</Small>}
              {error && <Small className="text-red-400 font-mono text-[10px] block">{error}</Small>}
            </div>
          )}
        </div>

        {/* Footer - compact */}
        <div className="p-3 border-t border-[#00ff00]/20 flex gap-2">
          {coverUrl && (
            <button
              onClick={handleRemove}
              className="px-4 py-2 text-red-400 font-mono text-sm hover:bg-red-500/10 rounded-lg transition-colors"
            >
              Remove
            </button>
          )}
          <button
            onClick={handleSave}
            disabled={isSaving}
            className="flex-1 py-2 bg-[#00ff00] text-black font-mono font-bold text-sm rounded-lg hover:bg-[#00ff00]/90 transition-colors disabled:opacity-50"
          >
            {isSaving ? "Saving..." : "Save"}
          </button>
        </div>
      </div>
    </div>
  );

  return createPortal(modalContent, document.body);
}

// Membership/Share Button Component - Full width button at bottom of card
// Handles: Non-members → $2 payment → Register + ENS → Share with embed button
// Members → Share library card with Warpcast embed that has "Mint Your Card" button
function MembershipButton({
  username,
  displayName,
  isMember,
  member,
  address,
  fid,
  stats,
  pfpUrl,
  onMembershipComplete,
  fcVerified = false,
  baseVerified = false,
  webVerified = false,
  hasNetLink = false,
  netLinkLabel = "",
}: {
  /** Farcaster handle (e.g. "cherylfromnet") — shown as @handle on card */
  username: string;
  /** Human-readable display name (e.g. "Cheryl") — shown as big name on card */
  displayName?: string;
  isMember: boolean;
  member?: { memberId: number; ensSubname: string } | null;
  address?: string;
  fid?: number;
  stats?: { uploads: number; dataMb: string; upvotes: number };
  pfpUrl?: string;
  onMembershipComplete?: () => void;
  fcVerified?: boolean;
  baseVerified?: boolean;
  webVerified?: boolean;
  hasNetLink?: boolean;
  netLinkLabel?: string;
}) {
  const [mintState, setMintState] = useState<"idle" | "paying" | "confirming" | "minting" | "complete" | "error">(
    isMember ? "complete" : "idle"
  );
  const [error, setError] = useState<string | null>(null);
  const [showShareModal, setShowShareModal] = useState(false);
  const [showWelcomeModal, setShowWelcomeModal] = useState(false);
  const [newMemberData, setNewMemberData] = useState<{ memberId: number; ensSubname: string } | null>(null);
  const appMode = useAppMode();
  const { openStoragePassModal } = useStoragePassModal();

  // Check USDC balance to show warning if insufficient
  const { data: usdcBalance } = useBalance({
    address: address as Address | undefined,
    token: USDC_ADDRESS,
    chainId: base.id,
  });

  // Calculate if user has enough USDC (need $2, USDC has 6 decimals)
  const usdcBalanceFormatted = usdcBalance ? parseFloat(formatUnits(usdcBalance.value, 6)) : 0;
  const hasEnoughUsdc = usdcBalanceFormatted >= MEMBERSHIP_COST_USDC;

  // Sponsored transaction hook for gas-free USDC transfer (uses CDP Paymaster)
  const {
    sendSponsoredTransaction,
    txHash,
    isPending,
    isConfirming,
    isConfirmed,
    error: writeError,
    reset,
    isSponsored,
  } = useSponsoredTransaction();

  // Handle write errors - only when in paying state
  useEffect(() => {
    if (writeError && mintState === "paying") {
      console.error("USDC write error:", writeError.message);

      const errMsg = writeError.message?.toLowerCase() || "";
      // User rejected - go back to idle
      if (errMsg.includes('user rejected') || errMsg.includes('denied') || errMsg.includes('cancelled')) {
        reset();
        setMintState("idle");
        return;
      }

      // Show actual error
      setError(writeError.message?.slice(0, 60) || "Payment failed");
      setMintState("error");
    }
  }, [writeError, mintState, reset]);

  // Handle transaction confirming
  useEffect(() => {
    if (txHash && isConfirming && mintState === "paying") {
      setMintState("confirming");
    }
  }, [txHash, isConfirming, mintState]);

  // Handle transaction confirmed - register membership
  useEffect(() => {
    if (isConfirmed && txHash && (mintState === "paying" || mintState === "confirming")) {
      registerMembership(txHash);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isConfirmed, txHash]);

  const registerMembership = async (hash: string) => {
    setMintState("minting");

    try {
      const response = await fetch("/api/membership", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          address,
          fid,
          username,
          txHash: hash,
          signupPlatform: appMode === "detecting" ? "farcaster" : appMode,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to register");
      }

      // Store new member data and show welcome modal with card image
      const memberNum = data.member?.memberId || 0;
      const ensSubname = data.member?.ensSubname || "";

      setNewMemberData({ memberId: memberNum, ensSubname });
      setMintState("complete");
      reset();

      // Show the welcome modal with the library card image
      setShowWelcomeModal(true);

      onMembershipComplete?.();
    } catch (err) {
      console.error("Registration error:", err);
      setMintState("complete"); // Payment went through, registration can retry
      reset();
      onMembershipComplete?.();
    }
  };

  // Initiate USDC payment - but first check if user is already a member
  const handlePayment = async () => {
    setError(null);

    // Pre-flight check 1: verify this wallet address isn't already registered
    // This prevents Base App users from accidentally paying twice
    if (address) {
      try {
        const fidParam = fid ? `&fid=${fid}` : '';
        const checkResponse = await fetch(`/api/membership?address=${address}${fidParam}`);
        const checkData = await checkResponse.json();

        if (checkData.isMember) {
          const matchDesc = checkData.matchType === 'linked'
            ? 'This wallet is linked to'
            : checkData.matchType === 'fid'
            ? 'Your Farcaster account is already'
            : 'This wallet is already';
          setError(`${matchDesc} member #${checkData.member?.memberId || 'unknown'}`);
          setMintState("error");
          return;
        }
      } catch (err) {
        console.error("Pre-flight address check failed:", err);
        // Continue anyway - the API will catch duplicates
      }
    }

    // Pre-flight check 2: verify this FID isn't already registered (for Farcaster users with different wallets)
    if (fid) {
      try {
        const checkResponse = await fetch(`/api/membership/check-fid?fid=${fid}`);
        const checkData = await checkResponse.json();

        if (checkData.isMember) {
          setError(`Your Farcaster account is already member #${checkData.member?.memberId || 'unknown'}`);
          setMintState("error");
          return;
        }
      } catch (err) {
        console.error("Pre-flight FID check failed:", err);
        // Continue anyway - the API will catch duplicates
      }
    }

    setMintState("paying");

    try {
      await sendSponsoredTransaction({
        address: USDC_ADDRESS,
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        abi: USDC_ABI as any,
        functionName: "transfer",
        args: [TREASURY_ADDRESS, BigInt(MEMBERSHIP_COST_USDC * 1_000_000)],
      });
    } catch (err) {
      console.error("Transaction failed:", err);
      // Error handling is done via the hook's error state
    }
  };

  const _isBaseApp = appMode === "base-app";

  // Member state - show Share button that opens visual modal
  if (mintState === "complete" || isMember) {
    return (
      <>
        <div className="flex flex-col gap-2 mt-3 relative">
          <button
            onClick={() => setShowShareModal(true)}
            className="w-full py-2 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] text-xs font-mono uppercase tracking-wider hover:bg-[#00ff00]/20 hover:shadow-[0_0_15px_rgba(0,255,0,0.3)] transition-all"
          >
            Share My Library Card
          </button>
        </div>

        {/* Share Modal - shows card image preview */}
        {member && (
          <LibraryCardShareModal
            isOpen={showShareModal}
            onClose={() => setShowShareModal(false)}
            memberId={member.memberId}
            ensSubname={member.ensSubname}
            username={username}
            displayName={displayName}
            uploads={stats?.uploads || 0}
            dataMb={stats?.dataMb || '0'}
            upvotes={stats?.upvotes || 0}
            pfpUrl={pfpUrl}
            mode="share"
            fcVerified={fcVerified}
            baseVerified={baseVerified}
            webVerified={webVerified}
            hasNetLink={hasNetLink}
            netLinkLabel={netLinkLabel}
          />
        )}

        {/* Welcome Modal - shows after new signup */}
        {newMemberData && (
          <LibraryCardShareModal
            isOpen={showWelcomeModal}
            onClose={() => setShowWelcomeModal(false)}
            memberId={newMemberData.memberId}
            ensSubname={newMemberData.ensSubname}
            username={username}
            displayName={displayName}
            uploads={0}
            dataMb="0"
            upvotes={0}
            pfpUrl={pfpUrl}
            mode="welcome"
            fcVerified={fcVerified}
            baseVerified={baseVerified}
            webVerified={webVerified}
            hasNetLink={hasNetLink}
            netLinkLabel={netLinkLabel}
          />
        )}
      </>
    );
  }

  // Error state
  if (mintState === "error") {
    return (
      <div className="flex flex-col gap-2 mt-3">
        <button
          onClick={() => {
            setError(null);
            setMintState("idle");
          }}
          className="w-full py-2 rounded-lg bg-red-500/20 border border-red-500/40 text-red-400 text-xs font-mono hover:bg-red-500/30 transition-all"
        >
          {error || "Payment failed"} - Tap to Retry
        </button>
      </div>
    );
  }

  // Minting state - show progress
  if (mintState === "minting") {
    return (
      <div className="w-full mt-3 py-2 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] text-xs font-mono uppercase tracking-wider text-center animate-pulse">
        Registering your membership...
      </div>
    );
  }

  // Confirming state - transaction submitted, waiting for confirmation
  if (mintState === "confirming") {
    return (
      <div className="w-full mt-3 py-2 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] text-xs font-mono uppercase tracking-wider text-center animate-pulse">
        Confirming transaction...
      </div>
    );
  }

  // Paying state - waiting for wallet confirmation
  if (mintState === "paying") {
    return (
      <div className="w-full mt-3 py-2 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] text-xs font-mono uppercase tracking-wider text-center animate-pulse">
        Confirm in wallet...
      </div>
    );
  }

  // Non-member state - show payment button with balance check
  return (
    <div className="flex flex-col gap-2 mt-3">
      {/* Insufficient balance warning */}
      {!hasEnoughUsdc && usdcBalance !== undefined && (
        <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30">
          <div className="flex items-start gap-2">
            <WalletIcon size={20} className="text-red-400" />
            <div className="flex-1 min-w-0">
              <P className="text-red-400 font-mono text-xs font-medium">
                Insufficient USDC Balance
              </P>
              <Small className="text-red-400/70 font-mono block mt-0.5">
                Membership costs ${MEMBERSHIP_COST_USDC} USDC on Base. You have ${usdcBalanceFormatted.toFixed(2)} USDC.
              </Small>
              <Small className="text-gray-500 font-mono block mt-1">
                Add USDC to your wallet to continue
              </Small>
            </div>
          </div>
        </div>
      )}
      {/* Unlimited Pass upsell */}
      <button
        onClick={openStoragePassModal}
        className="w-full mb-4 p-4 rounded-xl border border-purple-500/30 bg-gradient-to-r from-purple-500/10 via-[#00ff00]/5 to-purple-500/10 hover:from-purple-500/20 hover:to-purple-500/20 transition-colors text-left"
      >
        <div className="flex items-center gap-2 mb-1">
          <span className="text-sm">✦</span>
          <span className="text-xs font-mono font-bold bg-gradient-to-r from-purple-400 via-[#00ff00] to-purple-400 bg-clip-text text-transparent uppercase tracking-wider">
            Better Deal
          </span>
        </div>
        <p className="text-white font-mono text-sm font-bold">
          Get the Unlimited Pass for $10
        </p>
        <p className="text-gray-400 font-mono text-xs mt-1">
          Includes FREE membership + unlimited uploads + bypass warm-up + free hazza.name
        </p>
      </button>
      <button
        onClick={handlePayment}
        disabled={isPending || !hasEnoughUsdc}
        className={`w-full py-2 rounded-lg text-xs font-mono uppercase tracking-wider transition-all text-center ${
          hasEnoughUsdc
            ? "bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/20 hover:shadow-[0_0_15px_rgba(0,255,0,0.3)]"
            : "bg-[#1a1a1a] border border-gray-700 text-gray-500 cursor-not-allowed"
        } disabled:opacity-50`}
      >
        {hasEnoughUsdc ? (
          <>
            Become a Net Library Member!
            {isSponsored && <span className="ml-1 text-[10px] opacity-70">⛽ Gas Free</span>}
          </>
        ) : (
          `Need $${MEMBERSHIP_COST_USDC} USDC to Join`
        )}
      </button>
    </div>
  );
}

// Get the best CDN URL for a discovery entry
// Prefers: stored cdnUrl > /storage/load/ with filename > bytes32 decoded key > /storage/raw/
function getBestCdnUrl(entry: DiscoveryEntry): string {
  // 1. Use stored cdnUrl if available (for entries uploaded with new format)
  if (entry.cdnUrl) {
    return entry.cdnUrl;
  }

  // 2. Use /storage/load/ format if we have fileName and operator
  if (entry.fileName && entry.operator) {
    return getUserFriendlyCdnUrl(BASE_CHAIN_ID, entry.operator, entry.fileName);
  }

  // 3. Chunked storage uses a different path
  if (entry.storageType === "chunked") {
    return `https://storedon.net/net/${BASE_CHAIN_ID}/chunked-storage/file/${entry.operator}/${entry.contentKey}`;
  }

  // 4. Try to decode bytes32 contentKey → human-readable key → /storage/load/
  // Items registered via API with short keys (≤32 chars) are stored under the human-readable
  // key, not the bytes32 hex, so /storage/raw/ returns "Storage data not found".
  const decodedKey = decodeBytes32Key(entry.contentKey);
  if (decodedKey && entry.operator) {
    return `https://storedon.net/net/${BASE_CHAIN_ID}/storage/load/${entry.operator}/${encodeURIComponent(decodedKey)}`;
  }

  // 5. Final fallback to /storage/raw/ (multimedia viewer will decode the JSON response)
  return `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${entry.operator}/${entry.contentKey}`;
}

// CDN Links View - displays all uploads with copyable CDN links
function CdnLinksView({ uploads }: { uploads: DiscoveryEntry[] }) {
  const [copiedKey, setCopiedKey] = useState<string | null>(null);

  const handleCopy = async (url: string, contentKey: string) => {
    try {
      await navigator.clipboard.writeText(url);
      setCopiedKey(contentKey);
      setTimeout(() => setCopiedKey(null), 2000);
    } catch {
      // Fallback
      const textarea = document.createElement("textarea");
      textarea.value = url;
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand("copy");
      document.body.removeChild(textarea);
      setCopiedKey(contentKey);
      setTimeout(() => setCopiedKey(null), 2000);
    }
  };

  const handleDownloadAll = async () => {
    const links = uploads.map((u) => getBestCdnUrl(u)).join("\n");
    const blob = new Blob([links], { type: "text/plain" });
    const blobUrl = URL.createObjectURL(blob);
    // Use safeOpenUrl to break out of mini app and open in external browser
    await safeOpenUrl(blobUrl);
  };

  return (
    <div className="space-y-3">
      {/* Download all button */}
      <button
        onClick={handleDownloadAll}
        className="w-full py-3 px-4 bg-[#00ff00]/10 border-2 border-[#00ff00]/30 rounded-xl text-[#00ff00] font-mono hover:bg-[#00ff00]/20 hover:border-[#00ff00]/50 transition-all flex items-center justify-center gap-2"
      >
        <DownloadIcon size={16} />
        <span>Download All Links (.txt)</span>
      </button>

      {/* Links list */}
      <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/20">
        <CardContent className="p-3 space-y-3">
          {uploads.map((upload) => {
            const cdnUrl = getBestCdnUrl(upload);
            const isCopied = copiedKey === upload.contentKey;
            return (
              <div key={upload.contentKey} className="border-b border-[#00ff00]/10 pb-3 last:border-0 last:pb-0">
                <P className="text-white font-mono text-sm truncate mb-1">{upload.title}</P>
                <div className="flex items-center gap-2">
                  <code className="flex-1 text-[#00ff00] font-mono text-[10px] bg-black rounded px-2 py-1 truncate">
                    {cdnUrl}
                  </code>
                  <button
                    onClick={() => handleCopy(cdnUrl, upload.contentKey)}
                    className={`shrink-0 px-2 py-1 rounded text-[10px] font-mono transition-all ${
                      isCopied
                        ? "bg-green-500/20 text-green-400 border border-green-500/50"
                        : "bg-[#00ff00]/10 text-[#00ff00] border border-[#00ff00]/30 hover:bg-[#00ff00]/20"
                    }`}
                  >
                    {isCopied ? <CheckIcon size={12} /> : <CopyIcon size={12} />}
                  </button>
                </div>
              </div>
            );
          })}
        </CardContent>
      </Card>

      <Small className="text-gray-500 font-mono text-center block">
        {uploads.length} link{uploads.length !== 1 ? "s" : ""} total
      </Small>
    </div>
  );
}

// Member type for All Members feed
interface AllMemberData {
  memberId: number;
  address: string;
  ensSubname: string;
  fid?: number;
  username?: string;
  joinedAt: number;
  signupPlatform?: "farcaster" | "base-app" | "web" | "unknown";
  pfpUrl?: string;
  upvotesReceived?: number;
  linkedAddresses?: string[];
  // Agent identity
  isAgent?: boolean;
  agentId?: string;
  // Display name vs handle separation
  displayName?: string;
  farcasterUsername?: string;
  // Pass status
  hasStackPass?: boolean;
}

// Grouped member type for All Members feed (combines multiple memberships)
interface GroupedAllMember {
  fid?: number;
  username?: string;
  address: string;
  pfpUrl?: string;
  memberNumbers: number[]; // All member IDs for this user
  ensSubnames: string[]; // All ENS subnames
  primaryMemberId: number; // The lowest member ID (used for upvoting)
  signupPlatforms: ("farcaster" | "base-app" | "web" | "unknown" | undefined)[]; // Platform for each member ID
  canonicalPlatform: "farcaster" | "base-app" | "web" | "unknown" | undefined; // Platform of first membership
  linkedAddresses?: string[];
  // Agent identity
  isAgent?: boolean;
  agentId?: string;
  // Display name vs handle separation
  displayName?: string;
  farcasterUsername?: string;
  // Pass status — true if any membership in this group has the pass
  hasStackPass?: boolean;
}

// Group members by FID (or by address if no FID)
function groupAllMembersByFid(members: AllMemberData[]): GroupedAllMember[] {
  const grouped = new Map<string, GroupedAllMember>();

  // Sort by memberId first so lowest ID becomes primary
  const sortedMembers = [...members].sort((a, b) => a.memberId - b.memberId);

  for (const member of sortedMembers) {
    // Use FID as key if available, otherwise use lowercase address
    const key = member.fid ? `fid:${member.fid}` : `addr:${(member.address || '').toLowerCase()}`;

    if (grouped.has(key)) {
      // Add to existing group
      const existing = grouped.get(key)!;
      existing.memberNumbers.push(member.memberId);
      existing.ensSubnames.push(member.ensSubname);
      existing.signupPlatforms.push(member.signupPlatform);
      // Propagate pass status — any membership in the group having the pass is enough
      if (member.hasStackPass) {
        existing.hasStackPass = true;
      }
    } else {
      // Create new group - first membership determines canonical platform
      // Legacy members (no signupPlatform) default to Farcaster since Base App came later
      const inferredPlatform = member.signupPlatform || "farcaster";
      grouped.set(key, {
        fid: member.fid,
        username: member.username,
        address: member.address,
        pfpUrl: member.pfpUrl,
        memberNumbers: [member.memberId],
        ensSubnames: [member.ensSubname],
        primaryMemberId: member.memberId,
        signupPlatforms: [member.signupPlatform],
        canonicalPlatform: inferredPlatform,
        linkedAddresses: member.linkedAddresses,
        // Agent identity
        isAgent: member.isAgent,
        agentId: member.agentId,
        // Display name vs handle
        displayName: member.displayName,
        farcasterUsername: member.farcasterUsername,
        // Pass status
        hasStackPass: !!member.hasStackPass,
      });
    }
  }

  // Convert to array and sort by primary member ID
  return Array.from(grouped.values()).sort((a, b) => a.primaryMemberId - b.primaryMemberId);
}

// Member Profile View Component - Full screen view when tapping on a member
// Uses context for member data and can be rendered globally
export function MemberProfileView() {
  const { selectedMember, closeMemberProfile } = useMemberProfile();
  const [uploads, setUploads] = useState<DiscoveryEntry[]>([]);
  const [isLoadingUploads, setIsLoadingUploads] = useState(true);
  const [showMemberUpvoteModal, setShowMemberUpvoteModal] = useState(false);
  const { entries } = useDiscoveryContext();
  const { address } = useAccount();

  const member = selectedMember;
  const onClose = closeMemberProfile;

  // Member upvote hook
  const { upvoteMember, isUpvoting, isConfirmed, reset: resetUpvote } = useMemberUpvote();

  // Fetch upvote count for this member
  const memberUpvoteData = React.useMemo(() =>
    member?.address ? [{ memberId: member.memberId, address: member.address }] : [],
    [member?.memberId, member?.address]
  );
  const { getCount: getMemberUpvotes, refresh: refreshUpvotes } = useMemberUpvoteCounts(memberUpvoteData);

  // Refresh when transaction confirms, then close modal
  useEffect(() => {
    if (isConfirmed) {
      refreshUpvotes();
      setTimeout(() => {
        setShowMemberUpvoteModal(false);
        resetUpvote();
      }, 2000); // stay open 2s on confirmed state so user sees it
    }
  }, [isConfirmed, refreshUpvotes, resetUpvote]);

  // Get user's uploads
  useEffect(() => {
    if (!member?.address) {
      setIsLoadingUploads(false);
      return;
    }

    // Filter entries to find this member's uploads (exclude hidden items).
    // Check uploaderAddress first — relay uploads store the backend wallet as `operator`
    // and the actual user's wallet as `uploaderAddress`. Fall back to operator for legacy entries.
    const addr = member.address.toLowerCase();
    const memberUploads = entries.filter(e =>
      !e.hidden && (
        (e.uploaderAddress && e.uploaderAddress.toLowerCase() === addr) ||
        (e.operator && e.operator.toLowerCase() === addr)
      )
    );
    setUploads(memberUploads);
    setIsLoadingUploads(false);
  }, [member?.address, entries]);

  // Helper for platform color
  const getPlatformColor = (platform?: string) => {
    if (platform === "farcaster") return "text-purple-400";
    if (platform === "base-app") return "text-blue-400";
    if (platform === "web") return "text-yellow-400";
    return "text-gray-400";
  };

  // Helper for platform icon
  const getPlatformIcon = (platform?: string) => {
    if (platform === "farcaster") return <FarcasterIcon size={16} className="text-purple-400" />;
    if (platform === "base-app") return <BaseIcon size={16} className="text-blue-400" />;
    if (platform === "web") return <WebIcon size={16} className="text-yellow-400" />;
    return null;
  };

  // Format join date
  const formatDate = (timestamp: number) => {
    return new Date(timestamp).toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    });
  };

  // Handle upvoting this member (on-chain) - opens count-selection modal
  const handleUpvote = () => {
    if (!member?.address || isUpvoting) return;
    setShowMemberUpvoteModal(true);
  };

  const handleSubmitMemberUpvote = async (count: number) => {
    if (!member?.address) return;
    // Don't close modal here — let isConfirmed drive the close so user sees confirmation
    await upvoteMember(member.address, member.memberId, count);
  };

  // Don't render if no member selected
  if (!member) return null;

  return (
    <div className="fixed inset-0 bg-black z-[9999] overflow-y-auto">
      {/* Header with Back Button */}
      <div className="sticky top-0 z-10 bg-black/95 backdrop-blur-sm border-b border-[#00ff00]/20 px-4 py-3">
        <div className="flex items-center gap-3">
          <button
            onClick={onClose}
            className="w-10 h-10 rounded-full bg-[#00ff00]/10 border border-[#00ff00]/30 flex items-center justify-center text-[#00ff00] hover:bg-[#00ff00]/20 transition-colors"
          >
            ←
          </button>
          <div className="flex-1">
            <P className="text-white font-mono font-medium">
              {member.username || `Member ${member.memberId}`}
            </P>
            <Small className="text-[#00ff00]/60 font-mono">Member Profile</Small>
          </div>
        </div>
      </div>

      {/* Profile Content */}
      <div className="p-4 space-y-6">
        {/* Profile Card */}
        <Card className="bg-gradient-to-br from-[#0a0a0a] via-[#0d1a0d] to-[#0a0a0a] border-2 border-[#00ff00]/50 shadow-[0_0_30px_rgba(0,255,0,0.15)]">
          <CardContent className="p-6">
            <div className="flex flex-col items-center text-center">
              {/* PFP */}
              <div className="relative mb-4">
                <img
                  src={member.pfpUrl}
                  alt={member.username || `Member ${member.memberId}`}
                  className="w-24 h-24 rounded-full border-4 border-[#00ff00]/50 object-cover shadow-[0_0_20px_rgba(0,255,0,0.3)]"
                />
                <div className="absolute -bottom-2 -right-2 w-8 h-8 rounded-full bg-black border-2 border-[#00ff00]/50 flex items-center justify-center">
                  {getPlatformIcon(member.signupPlatform)}
                </div>
              </div>

              {/* Username & Member # */}
              <P className="text-white font-mono text-xl font-bold">
                {member.username || `Member ${member.memberId}`}
              </P>
              <div className="flex items-center gap-2 mt-1">
                <span className={`font-mono text-sm ${getPlatformColor(member.signupPlatform)}`}>
                  Member #{member.memberId}
                </span>
              </div>

              {/* ENS Subdomain */}
              <Small className="text-[#00ff00] font-mono mt-2 block">
                {member.ensSubname}
              </Small>

              {/* FID */}
              {member.fid && (
                <Small className="text-purple-400/70 font-mono mt-1">
                  FID: {member.fid}
                </Small>
              )}

              {/* Join Date */}
              <Small className="text-gray-500 font-mono mt-2">
                Joined {formatDate(member.joinedAt)}
              </Small>

              {/* Stats */}
              <div className="grid grid-cols-2 gap-6 mt-6 w-full max-w-xs">
                <div className="text-center">
                  <P className="text-[#00ff00] font-mono text-2xl font-bold">
                    {uploads.length}
                  </P>
                  <Small className="text-gray-500 font-mono">Uploads</Small>
                </div>
                {/* Upvote Button */}
                <button
                  onClick={handleUpvote}
                  disabled={isUpvoting || !address || !member.address || address.toLowerCase() === member.address.toLowerCase()}
                  className={`text-center px-4 py-3 rounded-xl border-2 transition-all ${
                    isUpvoting
                      ? "bg-[#00ff00]/30 border-[#00ff00] animate-pulse"
                      : address && member.address && address.toLowerCase() !== member.address.toLowerCase()
                      ? "bg-[#00ff00]/10 border-[#00ff00]/50 hover:bg-[#00ff00]/20 hover:border-[#00ff00] hover:shadow-[0_0_15px_rgba(0,255,0,0.3)] active:scale-95"
                      : "bg-gray-800/50 border-gray-700 cursor-not-allowed opacity-50"
                  }`}
                >
                  <P className="text-[#00ff00] font-mono text-2xl font-bold">
                    {isUpvoting ? "..." : `▲ ${member.address ? getMemberUpvotes(member.address) : 0}`}
                  </P>
                  <Small className="text-gray-500 font-mono">
                    {address && member.address && address.toLowerCase() === member.address.toLowerCase() ? "your profile" : "tap to upvote"}
                  </Small>
                </button>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Uploads Section */}
        <div>
          <P className="text-[#00ff00] font-mono font-bold mb-3">UPLOADS</P>

          {isLoadingUploads ? (
            <div className="text-center py-8">
              <P className="text-gray-500 font-mono">Loading uploads...</P>
            </div>
          ) : uploads.length === 0 ? (
            <Card className="bg-[#0a0a0a] border border-[#00ff00]/20">
              <CardContent className="p-6 text-center">
                <div className="w-12 h-12 mx-auto mb-3 rounded-full bg-[#00ff00]/10 flex items-center justify-center">
                  <DocumentIcon size={24} className="text-[#00ff00]/50" />
                </div>
                <P className="text-gray-400 font-mono">No uploads yet</P>
              </CardContent>
            </Card>
          ) : (
            <div className="space-y-2">
              {uploads.slice(0, 10).map((upload) => (
                <Card
                  key={upload.contentKey}
                  className="bg-[#0a0a0a] border border-[#00ff00]/20 hover:border-[#00ff00]/50 transition-all"
                >
                  <CardContent className="p-3">
                    <div className="flex items-center gap-3">
                      {/* Cover */}
                      {(upload.coverUrl || upload.cdnUrl) ? (
                        <img
                          src={getEffectiveCoverUrl(upload)}
                          alt={upload.title}
                          className="w-12 h-12 rounded object-cover border border-[#00ff00]/20"
                        />
                      ) : (
                        <div className="w-12 h-12 rounded bg-[#00ff00]/10 flex items-center justify-center border border-[#00ff00]/20">
                          <DocumentIcon size={20} className="text-[#00ff00]/50" />
                        </div>
                      )}
                      {/* Info */}
                      <div className="flex-1 min-w-0">
                        <P className="text-white font-mono text-sm truncate">
                          {upload.title}
                        </P>
                        <Small className="text-gray-500 font-mono truncate block">
                          {upload.author}
                        </Small>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))}
              {uploads.length > 10 && (
                <Small className="text-gray-500 font-mono text-center block">
                  +{uploads.length - 10} more uploads
                </Small>
              )}
            </div>
          )}
        </div>
      </div>
      {/* Member Upvote Modal — portaled to body so fixed positioning is always viewport-relative */}
      {typeof document !== "undefined" && createPortal(
        <MemberUpvoteModal
          isOpen={showMemberUpvoteModal}
          onClose={() => setShowMemberUpvoteModal(false)}
          onUpvote={handleSubmitMemberUpvote}
          isUpvoting={isUpvoting}
          isConfirmed={isConfirmed}
          memberName={member.displayName || member.username || `Member ${member.memberId}`}
          currentUpvotes={member.address ? getMemberUpvotes(member.address) : 0}
        />,
        document.body
      )}
    </div>
  );
}

// All Members Feed Component
// Shows paginated list of all library members with search and sorting
// Groups members by FID to combine multiple memberships into single cards
const MEMBERS_PER_PAGE = 12;

function AllMembersFeed() {
  const [members, setMembers] = useState<AllMemberData[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [sortBy, setSortBy] = useState<"member-number" | "upvotes">("member-number");
  const [currentPage, setCurrentPage] = useState(1);
  const [upvotingMemberId, setUpvotingMemberId] = useState<number | null>(null);
  const [selectedMember, setSelectedMember] = useState<AllMemberData | null>(null);
  const [selectedGroupedMember, setSelectedGroupedMember] = useState<GroupedAllMember | null>(null);
  const [showMemberUpvoteModal, setShowMemberUpvoteModal] = useState(false);
  const [pendingUpvoteMember, setPendingUpvoteMember] = useState<GroupedAllMember | null>(null);
  const [showAirdropModal, setShowAirdropModal] = useState(false);
  const [showCsvModal, setShowCsvModal] = useState(false);
  const [isDownloadingCsv, setIsDownloadingCsv] = useState(false);
  const [csvCopied, setCsvCopied] = useState(false);
  const { address } = useAccount();

  // Check if current user is a member
  const { isMember } = useMembershipStatus();

  // Member upvote hook
  const { upvoteMember, isUpvoting, isConfirmed, reset: resetUpvote } = useMemberUpvote();

  // Group members by FID
  const groupedMembers = React.useMemo(() => groupAllMembersByFid(members), [members]);

  // Get upvote counts for all members (use primary member IDs)
  const memberUpvoteData = React.useMemo(() =>
    groupedMembers.filter(m => m.address).map(m => ({ memberId: m.primaryMemberId, address: m.address })),
    [groupedMembers]
  );
  const { getCount: getMemberUpvotes, refresh: refreshUpvotes } = useMemberUpvoteCounts(memberUpvoteData);

  const handleSubmitMemberUpvote = async (count: number) => {
    if (!pendingUpvoteMember?.address) return;
    const lowestMemberId = Math.min(...pendingUpvoteMember.memberNumbers);
    setUpvotingMemberId(lowestMemberId);
    // Don't close modal here — let isConfirmed drive the close so user sees confirmation
    await upvoteMember(pendingUpvoteMember.address, lowestMemberId, count);
  };

  // Refresh upvote counts when a transaction confirms, then close modal
  useEffect(() => {
    if (isConfirmed) {
      // Refresh counts first, then reset — give chain a moment to index
      refreshUpvotes();
      setTimeout(() => {
        setUpvotingMemberId(null);
        setShowMemberUpvoteModal(false);
        setPendingUpvoteMember(null);
        resetUpvote();
      }, 2000); // modal stays open 2s showing confirmed state so user sees it
    }
  }, [isConfirmed, refreshUpvotes, resetUpvote]);

  // Count members by signup platform (canonical platform for each user)
  const platformCounts = React.useMemo(() => {
    return groupedMembers.reduce(
      (acc, member) => {
        if (member.canonicalPlatform === "farcaster") {
          acc.farcaster += 1;
        } else if (member.canonicalPlatform === "web") {
          acc.web += 1;
        } else {
          acc.baseApp += 1;
        }
        return acc;
      },
      { farcaster: 0, baseApp: 0, web: 0 }
    );
  }, [groupedMembers]);

  // Generate CSV content string
  const generateCsvContent = () => {
    const headers = ["member_id", "address", "username", "fid", "signup_platform", "ens_subname"];
    const rows = members.map((m) => [
      m.memberId,
      m.address,
      m.username || "",
      m.fid || "",
      m.signupPlatform || "farcaster",
      m.ensSubname || "",
    ]);

    return [
      headers.join(","),
      ...rows.map((row) => row.map((cell) => `"${cell}"`).join(",")),
    ].join("\n");
  };

  // Download CSV file (member-gated)
  const downloadMembersCsv = async () => {
    if (!isMember) return;
    setIsDownloadingCsv(true);
    try {
      const csvUrl = `${window.location.origin}/api/member-registry/csv`;
      await safeOpenUrl(csvUrl);
      setShowCsvModal(false);
    } catch (err) {
      console.error("Failed to download CSV:", err);
    } finally {
      setIsDownloadingCsv(false);
    }
  };

  // Copy CSV to clipboard (member-gated)
  const copyMembersCsv = async () => {
    if (!isMember) return;
    try {
      const csvContent = generateCsvContent();
      await navigator.clipboard.writeText(csvContent);
      setCsvCopied(true);
      setTimeout(() => setCsvCopied(false), 2000);
    } catch (err) {
      console.error("Failed to copy CSV:", err);
    }
  };

  // Fetch all members on mount
  useEffect(() => {
    async function fetchMembers() {
      setIsLoading(true);
      try {
        const response = await fetch("/api/member-registry");
        if (response.ok) {
          const data = await response.json();
          const memberList = data.members || [];

          // Collect FIDs for batch display name resolution
          const fidsToResolve: number[] = [];
          for (const m of memberList) {
            if (m.fid) fidsToResolve.push(m.fid);
          }

          // Resolve display names by FID (batch call)
          const fidToDisplayName = new Map<number, string>();
          const fidToUsername = new Map<number, string>();
          const fidToPfpUrl = new Map<number, string>();

          if (fidsToResolve.length > 0) {
            try {
              const fidResponse = await fetch("/api/resolve-user", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ fids: fidsToResolve }),
              });
              if (fidResponse.ok) {
                const fidData = await fidResponse.json();
                if (fidData.users) {
                  for (const user of fidData.users) {
                    if (user.display_name) {
                      fidToDisplayName.set(user.fid, user.display_name);
                    }
                    if (user.username) {
                      fidToUsername.set(user.fid, user.username);
                    }
                    if (user.pfp_url) {
                      fidToPfpUrl.set(user.fid, user.pfp_url);
                    }
                  }
                }
              }
            } catch {
              // Ignore resolve errors
            }
          }

          // Resolve by address for members without FID
          const membersWithoutFid = memberList.filter((m: { fid?: number }) => !m.fid);
          const addresses = membersWithoutFid.filter((m: { address: string }) => m.address).map((m: { address: string }) => m.address);
          const resolvedUsers = new Map<string, { username: string; pfpUrl: string; fid?: number; displayName?: string }>();

          if (addresses.length > 0) {
            try {
              const resolveResponse = await fetch("/api/resolve-user", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ addresses }),
              });
              if (resolveResponse.ok) {
                const resolveData = await resolveResponse.json();
                for (const [addr, user] of Object.entries(resolveData.users || {})) {
                  const userData = user as { username: string; pfpUrl: string; fid?: number; displayName?: string };
                  resolvedUsers.set(addr.toLowerCase(), userData);
                }
              }
            } catch {
              // Ignore resolve errors
            }
          }

          // Enhance members with resolved data (upvotes fetched via hook)
          const enhancedMembers = memberList.map((member: {
            memberId: number;
            address: string;
            ensSubname: string;
            fid?: number;
            username?: string;
            joinedAt: number;
            signupPlatform?: "farcaster" | "base-app" | "web" | "unknown";
            isAgent?: boolean;
            agentId?: string;
            farcasterUsername?: string;
            pfpUrl?: string;
          }) => {
            const resolved = member.address ? resolvedUsers.get(member.address.toLowerCase()) : undefined;
            const resolvedFid = member.fid || resolved?.fid;

            // Display name resolution:
            // 1. For agents: use registry username as display name (e.g., "Cheryl")
            // 2. For users with FID: use Neynar display_name
            // 3. Fallback to resolved or registry username
            let displayName: string | undefined;
            let farcasterUsername: string | undefined;

            if (member.isAgent) {
              // Agent: username IS the display name, farcasterUsername is the handle
              displayName = member.username;
              farcasterUsername = member.farcasterUsername;
            } else if (resolvedFid) {
              // Regular user: get display_name and handle from Neynar
              // displayName = Neynar display_name (e.g. "Cheryl") > member.username (may be display name)
              displayName = fidToDisplayName.get(resolvedFid) || member.username || resolved?.username;
              // farcasterUsername = Neynar username/handle (e.g. "cherylfromnet") > stored farcasterUsername > member.username fallback
              farcasterUsername = fidToUsername.get(resolvedFid) || member.farcasterUsername || resolved?.username;
            } else {
              // Address-only fallback
              displayName = resolved?.displayName || member.username || resolved?.username;
              farcasterUsername = member.farcasterUsername || resolved?.username || member.username;
            }

            // PFP priority: registry pfpUrl > FID-resolved > address-resolved > dicebear
            let pfpUrl = member.pfpUrl;
            if (!pfpUrl && resolvedFid) {
              pfpUrl = fidToPfpUrl.get(resolvedFid);
            }
            if (!pfpUrl && resolved?.pfpUrl) {
              pfpUrl = resolved.pfpUrl;
            }
            if (!pfpUrl) {
              pfpUrl = `https://api.dicebear.com/7.x/identicon/svg?seed=${member.address || member.memberId}`;
            }

            return {
              ...member,
              // Use resolved FID if member doesn't have one (enables grouping by FID)
              fid: resolvedFid,
              username: member.username || resolved?.username,
              pfpUrl,
              upvotesReceived: 0, // Will be fetched via useMemberUpvoteCounts hook
              // Display name (e.g., "GEAUX", "Cheryl")
              displayName,
              // Farcaster handle (e.g., "geaux", "cherylfromnet")
              farcasterUsername,
              // Pass through agent fields from registry
              isAgent: member.isAgent,
              agentId: member.agentId,
            };
          });

          setMembers(enhancedMembers);
        }
      } catch (error) {
        console.error("Failed to fetch members:", error);
      } finally {
        setIsLoading(false);
      }
    }
    fetchMembers();
  }, []);

  // Filter and sort GROUPED members
  const filteredGroupedMembers = React.useMemo(() => {
    let result = [...groupedMembers];

    // Apply search filter (search across all ENS subnames and usernames)
    if (searchQuery.trim()) {
      const query = searchQuery.toLowerCase().trim();
      result = result.filter(m =>
        (m.username && m.username.toLowerCase().includes(query)) ||
        m.ensSubnames.some(ens => ens && ens.toLowerCase().includes(query)) ||
        m.memberNumbers.some(num => num.toString().includes(query))
      );
    }

    // Apply sorting
    if (sortBy === "member-number") {
      result.sort((a, b) => a.primaryMemberId - b.primaryMemberId);
    } else if (sortBy === "upvotes") {
      // Use getMemberUpvotes to get on-chain upvote counts
      result.sort((a, b) => {
        const aUpvotes = a.address ? getMemberUpvotes(a.address) : 0;
        const bUpvotes = b.address ? getMemberUpvotes(b.address) : 0;
        return bUpvotes - aUpvotes;
      });
    }

    return result;
  }, [groupedMembers, searchQuery, sortBy, getMemberUpvotes]);

  // Paginate
  const totalPages = Math.ceil(filteredGroupedMembers.length / MEMBERS_PER_PAGE);
  const startIndex = (currentPage - 1) * MEMBERS_PER_PAGE;
  const endIndex = startIndex + MEMBERS_PER_PAGE;
  const paginatedGroupedMembers = filteredGroupedMembers.slice(startIndex, endIndex);

  // Reset to page 1 when search or sort changes
  useEffect(() => {
    setCurrentPage(1);
  }, [searchQuery, sortBy]);

  if (isLoading) {
    return (
      <div className="py-8 text-center">
        <div className="w-16 h-16 mx-auto mb-4 rounded-full bg-[#00ff00]/10 flex items-center justify-center border-2 border-[#00ff00]/30 animate-pulse">
          <UserIcon size={28} className="text-[#00ff00]/50" />
        </div>
        <P className="text-[#00ff00] font-mono">Loading members...</P>
        <Small className="text-gray-500 font-mono">Fetching member data</Small>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Header with platform stats, CSV, and Airdrop buttons */}
      <div className="flex items-center justify-between gap-2 p-3 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl">
        <div>
          <P className="text-[#00ff00] font-mono font-bold text-sm">
            {filteredGroupedMembers.length} member{filteredGroupedMembers.length !== 1 ? "s" : ""}
          </P>
          {/* Platform breakdown */}
          <div className="flex items-center gap-2 mt-0.5">
            <span className="text-purple-400 font-mono text-[10px]">
              ● {platformCounts.farcaster} FC
            </span>
            <span className="text-gray-600 text-[9px]">/</span>
            <span className="text-blue-400 font-mono text-[10px]">
              ● {platformCounts.baseApp} Base
            </span>
            <span className="text-gray-600 text-[9px]">/</span>
            <span className="text-yellow-400 font-mono text-[10px]">
              ● {platformCounts.web} Web
            </span>
          </div>
        </div>
        <div className="flex items-center gap-2">
          {/* CSV Export - Member Only */}
          {isMember ? (
            <button
              onClick={() => setShowCsvModal(true)}
              disabled={isLoading}
              className="px-2 py-1.5 rounded-lg bg-[#0a0a0a] border border-[#00ff00]/20 text-[#00ff00] font-mono text-[10px] hover:bg-[#00ff00]/10 transition-colors disabled:opacity-50"
              title="Export member addresses"
            >
              <DownloadIcon size={12} className="inline mr-1" /> CSV
            </button>
          ) : (
            <button
              disabled
              className="px-2 py-1.5 rounded-lg bg-[#0a0a0a] border border-gray-700 text-gray-500 font-mono text-[10px] cursor-not-allowed"
              title="Members only: Export member addresses"
            >
              <DownloadIcon size={12} className="inline mr-1 opacity-50" /> CSV
            </button>
          )}
          <button
            onClick={() => setShowAirdropModal(true)}
            className="px-2.5 py-1.5 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] font-mono text-[10px] font-bold hover:bg-[#00ff00]/20 transition-colors flex items-center gap-1"
          >
            <ParachuteIcon size={12} /> AIRDROP
          </button>
        </div>
      </div>

      {/* Search Bar */}
      <div className="relative">
        <SearchIcon size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-500" />
        <input
          type="text"
          placeholder="Search by username or member #..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
          className="w-full pl-10 pr-4 py-3 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl text-white font-mono text-sm placeholder:text-gray-600 focus:border-[#00ff00] focus:outline-none transition-colors"
        />
        {searchQuery && (
          <button
            onClick={() => setSearchQuery("")}
            className="absolute right-3 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full bg-gray-700 flex items-center justify-center text-gray-400 hover:text-white transition-colors"
          >
            ×
          </button>
        )}
      </div>

      {/* Sort Toggle */}
      <div className="flex items-center gap-2">
        <Small className="text-gray-500 font-mono text-[10px]">Sort:</Small>
        <div className="flex gap-1 flex-1">
          <button
            onClick={() => setSortBy("member-number")}
            className={`flex-1 px-3 py-1.5 rounded-lg text-[10px] font-mono transition-all ${
              sortBy === "member-number"
                ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/50"
                : "bg-[#1a1a1a] text-gray-400 border border-transparent hover:border-[#00ff00]/30"
            }`}
          >
            Member #
          </button>
          <button
            onClick={() => setSortBy("upvotes")}
            className={`flex-1 px-3 py-1.5 rounded-lg text-[10px] font-mono transition-all ${
              sortBy === "upvotes"
                ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/50"
                : "bg-[#1a1a1a] text-gray-400 border border-transparent hover:border-[#00ff00]/30"
            }`}
          >
            ▲ Upvotes
          </button>
        </div>
      </div>

      {/* Stats Summary */}
      <div className="flex items-center justify-between px-2">
        <Small className="text-gray-500 font-mono">
          {filteredGroupedMembers.length} user{filteredGroupedMembers.length !== 1 ? "s" : ""} ({members.length} membership{members.length !== 1 ? "s" : ""})
          {searchQuery && ` matching "${searchQuery}"`}
        </Small>
      </div>

      {/* Empty State */}
      {filteredGroupedMembers.length === 0 && (
        <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
          <CardContent className="p-8 text-center">
            <div className="w-16 h-16 mx-auto mb-3 rounded-full bg-[#00ff00]/10 flex items-center justify-center border-2 border-dashed border-[#00ff00]/30">
              <SearchIcon size={28} className="text-[#00ff00]/50" />
            </div>
            <P className="text-[#00ff00] font-mono">No members found</P>
            <Small className="text-gray-500 font-mono">
              {searchQuery ? "Try a different search term" : "Be the first to join!"}
            </Small>
          </CardContent>
        </Card>
      )}

      {/* Member Cards - Grouped by FID */}
      <div className="space-y-2">
        {paginatedGroupedMembers.map((grouped) => {
          // Find the primary member entry for the library card modal
          const primaryMember = members.find(m => m.memberId === grouped.primaryMemberId);

          // Determine ring color based on canonical platform (purple = FC, blue = Base, yellow = Web)
          const platform = grouped.canonicalPlatform;
          const ringColor = platform === "farcaster"
            ? "border-purple-500"
            : platform === "web"
            ? "border-yellow-500"
            : "border-blue-500";

          return (
            <div
              key={grouped.fid ? `fid-${grouped.fid}` : `addr-${grouped.address}`}
              onClick={() => {
                if (primaryMember) {
                  setSelectedMember(primaryMember);
                  setSelectedGroupedMember(grouped);
                }
              }}
              className="flex items-center gap-3 p-3 bg-[#0a0a0a] border border-[#00ff00]/20 rounded-xl hover:border-[#00ff00]/50 transition-all cursor-pointer"
            >
              {/* PFP */}
              <div className={`shrink-0 w-12 h-12 rounded-full border-2 ${ringColor} overflow-hidden`}>
                {grouped.pfpUrl ? (
                  <img
                    src={grouped.pfpUrl}
                    alt={grouped.username || `Member ${grouped.primaryMemberId}`}
                    className="w-full h-full object-cover"
                  />
                ) : (
                  <div className="w-full h-full bg-[#1a1a1a] flex items-center justify-center">
                    <span className="text-[#00ff00] font-mono text-xs font-bold">
                      #{grouped.primaryMemberId}
                    </span>
                  </div>
                )}
              </div>

              {/* Info */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <P className={`font-mono font-medium truncate text-sm ${grouped.isAgent ? "text-[#B794F4]" : "text-white"}`}>
                    {grouped.displayName || grouped.username || `Member ${grouped.primaryMemberId}`}
                  </P>
                  {grouped.isAgent && (
                    <span className="text-[8px] font-mono font-bold text-[#B794F4] bg-[#B794F4]/10 px-1 py-0.5 rounded border border-[#B794F4]/30">
                      AGENT
                    </span>
                  )}
                </div>
                {/* Show ENS subnames joined by " and " */}
                <Small className={`font-mono text-[10px] truncate ${grouped.isAgent ? "text-[#B794F4]/60" : "text-[#00ff00]/60"}`}>
                  {grouped.ensSubnames.join(" and ")}
                </Small>
              </div>

              {/* Upvote Button - Uses LOWEST member ID */}
              <button
                onClick={(e) => {
                  e.stopPropagation();
                  if (!grouped.address || !address || address.toLowerCase() === grouped.address.toLowerCase()) return;
                  setPendingUpvoteMember(grouped);
                  setShowMemberUpvoteModal(true);
                }}
                disabled={!address || !grouped.address || address.toLowerCase() === grouped.address.toLowerCase()}
                className={`text-center shrink-0 px-3 py-2 rounded-lg border transition-all ${
                  upvotingMemberId === grouped.primaryMemberId
                    ? "bg-[#00ff00]/30 border-[#00ff00] animate-pulse"
                    : address && grouped.address && address.toLowerCase() !== grouped.address.toLowerCase()
                    ? "bg-[#00ff00]/10 border-[#00ff00]/30 hover:bg-[#00ff00]/20 hover:border-[#00ff00] active:scale-95"
                    : "bg-gray-800/50 border-gray-700 cursor-not-allowed opacity-50"
                }`}
              >
                <P className="text-[#00ff00] font-mono text-lg">
                  {upvotingMemberId === grouped.primaryMemberId ? "..." : `▲ ${grouped.address ? getMemberUpvotes(grouped.address) : 0}`}
                </P>
              </button>
            </div>
          );
        })}
      </div>

      {/* Pagination Footer - Prominent and easy to tap */}
      {totalPages > 1 && (
        <div className="mt-4 pt-4 border-t border-[#00ff00]/30 space-y-3">
          <div className="flex items-center justify-center gap-3">
            <button
              onClick={() => setCurrentPage(p => Math.max(1, p - 1))}
              disabled={currentPage === 1}
              className="px-4 py-2 rounded-lg bg-[#0a0a0a] border border-[#00ff00]/30 text-[#00ff00] font-mono text-sm disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#00ff00]/10 transition-colors min-w-[80px]"
            >
              ← Prev
            </button>
            <div className="flex flex-col items-center">
              <span className="text-[#00ff00] font-mono text-sm font-bold">
                {currentPage} / {totalPages}
              </span>
              <span className="text-gray-500 font-mono text-[9px]">
                {startIndex + 1}-{Math.min(endIndex, filteredGroupedMembers.length)} of {filteredGroupedMembers.length}
              </span>
            </div>
            <button
              onClick={() => setCurrentPage(p => Math.min(totalPages, p + 1))}
              disabled={currentPage === totalPages}
              className="px-4 py-2 rounded-lg bg-[#0a0a0a] border border-[#00ff00]/30 text-[#00ff00] font-mono text-sm disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#00ff00]/10 transition-colors min-w-[80px]"
            >
              Next →
            </button>
          </div>
          <div className="flex items-center justify-center">
            <span className="text-[9px] text-gray-500 font-mono">
              Tap PFP to view library card
            </span>
          </div>
        </div>
      )}

      {/* User Library Card Modal */}
      {selectedMember && (
        <UserLibraryCardModal
          isOpen={!!selectedMember}
          onClose={() => {
            setSelectedMember(null);
            setSelectedGroupedMember(null);
          }}
          member={{
            memberId: selectedMember.memberId,
            address: selectedMember.address,
            ensSubname: selectedMember.ensSubname,
            fid: selectedMember.fid,
            username: selectedMember.username,
            signupPlatform: selectedMember.signupPlatform === "unknown" ? undefined : selectedMember.signupPlatform,
            pfpUrl: selectedMember.pfpUrl,
            linkedAddresses: selectedMember.linkedAddresses,
            joinedAt: selectedMember.joinedAt,
            // Agent identity
            isAgent: selectedMember.isAgent,
            agentId: selectedMember.agentId,
          }}
          allMemberships={selectedGroupedMember ? selectedGroupedMember.memberNumbers.map((memberId, idx) => ({
            memberId,
            address: selectedGroupedMember.address,
            ensSubname: selectedGroupedMember.ensSubnames[idx],
            signupPlatform: selectedGroupedMember.signupPlatforms[idx] as "farcaster" | "base-app" | "web" | "unknown" | undefined,
          })) : undefined}
        />
      )}

      {/* Airdrop Modal */}
      <AirdropModal
        isOpen={showAirdropModal}
        onClose={() => setShowAirdropModal(false)}
        isMember={isMember}
        members={members.map(m => ({
          memberId: m.memberId,
          address: m.address,
          ensSubname: m.ensSubname,
          fid: m.fid,
          username: m.username,
          joinedAt: m.joinedAt,
          signupPlatform: m.signupPlatform === "unknown" ? undefined : m.signupPlatform,
        }))}
      />

      {/* Member Upvote Modal — portaled to body so fixed positioning is always viewport-relative */}
      {typeof document !== "undefined" && createPortal(
        <MemberUpvoteModal
          isOpen={showMemberUpvoteModal}
          onClose={() => { setShowMemberUpvoteModal(false); setPendingUpvoteMember(null); }}
          onUpvote={handleSubmitMemberUpvote}
          isUpvoting={isUpvoting}
          isConfirmed={isConfirmed}
          memberName={pendingUpvoteMember?.displayName || pendingUpvoteMember?.username || (pendingUpvoteMember ? `Member #${pendingUpvoteMember.primaryMemberId}` : "")}
          currentUpvotes={pendingUpvoteMember?.address ? getMemberUpvotes(pendingUpvoteMember.address) : 0}
        />,
        document.body
      )}

      {/* CSV Export Modal */}
      {showCsvModal && (
        <div
          className="fixed inset-0 bg-black/80 z-[70] flex items-center justify-center p-4"
          onClick={() => setShowCsvModal(false)}
        >
          <div
            className="bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl p-5 max-w-sm w-full"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-4">
              <span className="text-[#00ff00] font-mono font-bold text-sm flex items-center gap-1"><DownloadIcon size={14} /> Export Members</span>
              <button
                onClick={() => setShowCsvModal(false)}
                className="w-6 h-6 rounded-full bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white text-xs"
              >
                ✕
              </button>
            </div>
            <P className="text-gray-400 font-mono text-xs mb-4">
              Export {members.length} member addresses as CSV
            </P>
            <div className="space-y-3">
              {/* Save File Option */}
              <button
                onClick={downloadMembersCsv}
                disabled={isDownloadingCsv}
                className="w-full p-3 rounded-lg border border-[#00ff00]/30 bg-[#00ff00]/10 hover:bg-[#00ff00]/20 transition-colors disabled:opacity-50"
              >
                <div className="flex items-center gap-3">
                  <SaveIcon size={20} className="text-[#00ff00]" />
                  <div className="text-left">
                    <P className="text-[#00ff00] font-mono text-sm font-bold">
                      {isDownloadingCsv ? "Opening..." : "Save File"}
                    </P>
                    <Small className="text-gray-500 font-mono">
                      Download CSV to your device
                    </Small>
                  </div>
                </div>
              </button>

              {/* Copy to Clipboard Option */}
              <button
                onClick={copyMembersCsv}
                className="w-full p-3 rounded-lg border border-gray-600/30 bg-[#1a1a1a] hover:bg-[#222] transition-colors"
              >
                <div className="flex items-center gap-3">
                  <span className="text-xl">{csvCopied ? <CheckCircleIcon size={20} className="text-green-400" /> : <ClipboardIcon size={20} className="text-[#00ff00]" />}</span>
                  <div className="text-left">
                    <P className="text-white font-mono text-sm font-bold">
                      {csvCopied ? "Copied!" : "Copy to Clipboard"}
                    </P>
                    <Small className="text-gray-500 font-mono">
                      Paste into email, notes, etc.
                    </Small>
                  </div>
                </div>
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

interface MyLibraryTabProps {
  categories: Category[];
}

export function MyLibraryTab({
  categories,
}: MyLibraryTabProps) {
  // Main subtab: "my-profile" (default) or "all-members"
  const [membersSubTab, setMembersSubTab] = useState<"my-profile" | "all-members">("my-profile");
  const [profileSubTab, setProfileSubTab] = useState<"uploads" | "stacks" | "grids" | "hidden" | "verify">("uploads");
  const [uploadsSortBy, setUploadsSortBy] = useState<"recent" | "upvotes" | "cdn-links">("recent");
  const [showCreateStackModal, setShowCreateStackModal] = useState(false);
  const [showAddToStackModal, setShowAddToStackModal] = useState(false);
  const [uploadToAddToStack, setUploadToAddToStack] = useState<DiscoveryEntry | null>(null);
  const [_showReadsInfo, _setShowReadsInfo] = useState(false);
  const [_showBytesInfo, _setShowBytesInfo] = useState(false);
  const [showLinkToNetModal, setShowLinkToNetModal] = useState(false);
  const [showLinkFarcasterModal, setShowLinkFarcasterModal] = useState(false);
  const [showLinkBaseModal, setShowLinkBaseModal] = useState(false);
  const [showClaimMembershipModal, setShowClaimMembershipModal] = useState(false);
  const [editingCover, setEditingCover] = useState<{ contentKey: string; operator: string; coverUrl?: string; title: string } | null>(null);
  const [editingItem, setEditingItem] = useState<DiscoveryEntry | null>(null);
  const [showCpis, setShowCpis] = useState(false);
  const [isUnlinkingFid, setIsUnlinkingFid] = useState(false);
  const [showUnlinkConfirm, setShowUnlinkConfirm] = useState(false);
  const [hiddenEntries, setHiddenEntries] = useState<DiscoveryEntry[]>([]);
  const [isLoadingHidden, setIsLoadingHidden] = useState(false);
  const [isUnhiding, setIsUnhiding] = useState<string | null>(null);
  const [showWebProfileEditor, setShowWebProfileEditor] = useState(false);

  // Stack delete confirmation state (window.confirm is blocked in Farcaster miniapp)
  const [stackToDelete, setStackToDelete] = useState<string | null>(null);
  const [isDeleting, setIsDeleting] = useState(false);
  const [hideItemsOnDelete, setHideItemsOnDelete] = useState(false);

  // Verify & cleanup state
  const [verifyResults, setVerifyResults] = useState<Array<{
    contentKey: string;
    operator: string;
    title?: string;
    status: "verified" | "broken" | "external" | "invalid";
    error?: string;
    message?: string;
  }> | null>(null);
  const [isVerifying, setIsVerifying] = useState(false);
  const [isRemovingBroken, setIsRemovingBroken] = useState<string | null>(null);

  // Get current app mode to show Link Farcaster button for Base App users
  const appMode = useAppMode();

  // Get cross-platform identity status
  const { isFarcasterVerified, isBaseAppVerified, isWebVerified } = usePlatformStatus();

  // Get user profile (works across Farcaster and Base App)
  const { profile: userProfile, isLoading: isLoadingUser } = useUserProfile();

  // Get connected wallet (auto-connected via Farcaster)
  const { address, isConnected: _isConnected } = useAccount();

  // Get discovery data from shared context (single source of truth)
  const { entries, isLoading: isLoadingDiscovery, refresh: refreshDiscovery } = useDiscoveryContext();
  const { getUserRank, getPopularBooks, isLoading: isLoadingLeaderboard } = useLeaderboard();

  // Fetch membership status - pass both address and FID for cross-platform identity lookup
  // This allows finding membership even when using a different wallet (e.g., Coinbase Smart Wallet)
  const { isMember, member, allMemberships, refresh: refreshMembership, isLoading: isLoadingMembership } = useMembership(address, userProfile?.fid);

  // Fetch user stats (achievements) from Net Protocol
  // Use member's registered address if available (for cross-platform identity)
  // This ensures achievements are fetched correctly on Base App even when wallet differs
  const achievementLookupAddress = member?.address || address;
  const { earnedIds, isLoading: isLoadingStats } = useUserStats(achievementLookupAddress);

  // Fetch user's Net link (pass FID for cross-platform sync)
  const { link: netLink, updateLink: updateNetLink } = useUserNetLink(address, userProfile?.fid);

  // Active members tracking
  const { reportActive } = useActiveMembers();

  // User's stacks
  const { stacks: userStacks, isLoading: isLoadingStacks, deleteStack, createStack, refresh: refreshStacks } = useUserStacks();

  // User's grids
  const { grids: userGrids } = useGrids({ creator: address, autoFetch: !!address });

  // Open Net link in browser
  const openNetLink = async (url: string) => {
    await safeOpenUrl(url);
  };

  // Unlink Farcaster account from membership
  const handleUnlinkFarcaster = async () => {
    if (!member || !address) return;

    setIsUnlinkingFid(true);
    try {
      const response = await fetch("/api/link-farcaster", {
        method: "DELETE",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          address,
          memberId: member.memberId,
          fid: member.fid,
        }),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to unlink");
      }

      // Refresh membership data
      refreshMembership();
      setShowUnlinkConfirm(false);
    } catch (err) {
      console.error("Unlink error:", err);
      alert(err instanceof Error ? err.message : "Failed to unlink Farcaster account");
    } finally {
      setIsUnlinkingFid(false);
    }
  };

  // Report member as active when they view their profile
  useEffect(() => {
    if (isMember && member && address) {
      reportActive(address, member.memberId);
    }
  }, [isMember, member, address, reportActive]);

  // Filter entries for current user's uploads (memoized to prevent dependency issues)
  // Include uploads from: current connected address, registered member address, linked addresses, AND memberId
  const myUploads = React.useMemo(() => {
    if (!address) return [];

    // Build a set of all addresses that belong to this user
    const userAddresses = new Set<string>();
    userAddresses.add(address.toLowerCase());

    // If member, add their registered address and any linked addresses
    if (member?.address) {
      userAddresses.add(member.address.toLowerCase());
    }
    if (member?.linkedAddresses) {
      member.linkedAddresses.forEach(addr => addr && userAddresses.add(addr.toLowerCase()));
    }

    // Also add addresses from all memberships (for multi-membership users)
    if (allMemberships) {
      allMemberships.forEach(m => {
        if (m.address) userAddresses.add(m.address.toLowerCase());
      });
    }

    // Build set of memberIds for this user (for unified identity matching)
    const userMemberIds = new Set<number>();
    if (member?.memberId) {
      userMemberIds.add(member.memberId);
    }
    if (allMemberships) {
      allMemberships.forEach(m => {
        if (m.memberId) userMemberIds.add(m.memberId);
      });
    }

    // Filter entries where:
    // 1. User is the uploaderAddress (set for relay uploads — the actual user, not the backend wallet)
    // 2. User is operator (by address — for direct/non-relay uploads where operator === user wallet)
    // 3. User is importer (for CDN imports)
    // 4. Entry has matching memberId (unified identity across platforms)
    // Hidden items are invisible everywhere except the owner's hidden feed — not counted here.
    return entries.filter((e) =>
      !e.hidden && (
        (e.uploaderAddress && userAddresses.has(e.uploaderAddress.toLowerCase())) ||
        (e.operator && userAddresses.has(e.operator.toLowerCase())) ||
        (e.importerAddress && userAddresses.has(e.importerAddress.toLowerCase())) ||
        (e.uploaderMemberId && userMemberIds.has(e.uploaderMemberId))
      )
    );
  }, [address, member, allMemberships, entries]);

  // Fetch hidden entries when the hidden tab is selected
  const fetchHiddenEntries = React.useCallback(async () => {
    if (!address) return;

    setIsLoadingHidden(true);
    try {
      // Build set of user addresses for filtering
      const userAddresses = new Set<string>();
      userAddresses.add(address.toLowerCase());
      if (member?.address) {
        userAddresses.add(member.address.toLowerCase());
      }
      if (member?.linkedAddresses) {
        member.linkedAddresses.forEach(addr => addr && userAddresses.add(addr.toLowerCase()));
      }
      if (allMemberships) {
        allMemberships.forEach(m => m.address && userAddresses.add(m.address.toLowerCase()));
      }

      // Build set of memberIds for this user (for unified identity matching)
      const userMemberIds = new Set<number>();
      if (member?.memberId) {
        userMemberIds.add(member.memberId);
      }
      if (allMemberships) {
        allMemberships.forEach(m => {
          if (m.memberId) userMemberIds.add(m.memberId);
        });
      }

      // Fetch hidden entries from API
      const response = await fetch("/api/discovery?includeHidden=true");
      if (response.ok) {
        const data = await response.json();
        // Filter to only show hidden entries that belong to this user
        // Include entries where user is operator OR importer (for CDN imports) OR memberId matches
        const userHiddenEntries = (data.entries || []).filter(
          (e: DiscoveryEntry) => e.hidden && (
            (e.operator && userAddresses.has(e.operator.toLowerCase())) ||
            (e.importerAddress && userAddresses.has(e.importerAddress.toLowerCase())) ||
            (e.uploaderMemberId && userMemberIds.has(e.uploaderMemberId))
          )
        );
        setHiddenEntries(userHiddenEntries);
      }
    } catch (err) {
      console.error("Error fetching hidden entries:", err);
    } finally {
      setIsLoadingHidden(false);
    }
  }, [address, member, allMemberships]);

  // Load hidden entries when switching to hidden tab
  useEffect(() => {
    if (profileSubTab === "hidden") {
      fetchHiddenEntries();
    }
  }, [profileSubTab, fetchHiddenEntries]);

  // Unhide an entry
  const handleUnhide = async (contentKey: string) => {
    if (!address) return;

    setIsUnhiding(contentKey);
    try {
      const response = await fetch("/api/discovery", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          contentKey,
          operator: address,
          hidden: false,
        }),
      });

      if (response.ok) {
        // Remove from hidden entries list
        setHiddenEntries(prev => prev.filter(e => e.contentKey !== contentKey));
        // Refresh discovery to show it back in the main feed
        refreshDiscovery();
      }
    } catch (err) {
      console.error("Error unhiding entry:", err);
    } finally {
      setIsUnhiding(null);
    }
  };

  // Verify uploads against Net Protocol
  const handleVerifyUploads = async () => {
    if (myUploads.length === 0) return;

    setIsVerifying(true);
    setVerifyResults(null);

    try {
      const items = myUploads.map((u) => ({
        contentKey: u.contentKey,
        operator: u.operator,
        title: u.title,
      }));

      const response = await fetch("/api/verify-content", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ items }),
      });

      if (response.ok) {
        const data = await response.json();
        setVerifyResults(data.results || []);
      } else {
        console.error("Verify failed:", await response.text());
      }
    } catch (err) {
      console.error("Error verifying uploads:", err);
    } finally {
      setIsVerifying(false);
    }
  };

  // Hide a broken entry from the discovery index (recoverable via Hidden tab)
  const handleHideBroken = async (contentKey: string, operator: string) => {
    if (!address) return;

    setIsRemovingBroken(contentKey);
    try {
      // Use the PATCH endpoint with "hidden: true" to hide from feed
      const response = await fetch("/api/discovery", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          contentKey,
          operator,
          hidden: true,
        }),
      });

      if (response.ok) {
        // Remove from verify results (it's now hidden)
        setVerifyResults((prev) => prev?.filter((r) => r.contentKey !== contentKey) || null);
        // Refresh discovery
        refreshDiscovery();
      } else {
        console.error("Failed to hide entry:", await response.text());
      }
    } catch (err) {
      console.error("Error hiding broken entry:", err);
    } finally {
      setIsRemovingBroken(null);
    }
  };

  // Prepare items for upvote count fetching
  // Use uploaderAddress (user's actual wallet) if present, falling back to operator
  // (backend relay wallet) — must match the address used when casting upvotes
  const upvoteItems = React.useMemo(() =>
    myUploads.map(upload => ({
      contentKey: upload.contentKey,
      operator: upload.uploaderAddress || upload.operator,
    })),
    [myUploads]
  );

  // Fetch upvote counts for user's uploads
  const { getCount: getUpvoteCount } = useUpvoteCounts(upvoteItems);

  // Calculate total upvotes received
  const totalUpvotesReceived = React.useMemo(() =>
    myUploads.reduce((total, upload) => total + getUpvoteCount(upload.contentKey), 0),
    [myUploads, getUpvoteCount]
  );

  // Sort uploads based on selected sort option
  const sortedUploads = React.useMemo(() => {
    const uploads = [...myUploads];
    switch (uploadsSortBy) {
      case "upvotes":
        // Most upvotes first
        return uploads.sort((a, b) => getUpvoteCount(b.contentKey) - getUpvoteCount(a.contentKey));
      case "cdn-links":
        // Same as recent for the list view (CDN links view handles its own display)
        return uploads.sort((a, b) => b.uploadedAt - a.uploadedAt);
      case "recent":
      default:
        // Most recently uploaded first (default)
        return uploads.sort((a, b) => b.uploadedAt - a.uploadedAt);
    }
  }, [myUploads, uploadsSortBy, getUpvoteCount]);

  // Get user stats from leaderboard - try current address first, then member's registered address
  const { rank, stats: userStats } = React.useMemo(() => {
    if (!address) return { rank: 0, stats: null };

    // Try current connected address first
    const result = getUserRank(address);
    if (result.stats) return result;

    // If member has a different registered address, try that
    if (member?.address && member.address.toLowerCase() !== address.toLowerCase()) {
      const memberResult = getUserRank(member.address);
      if (memberResult.stats) return memberResult;
    }

    // Try addresses from all memberships
    if (allMemberships) {
      for (const m of allMemberships) {
        if (m.address && m.address.toLowerCase() !== address.toLowerCase()) {
          const result = getUserRank(m.address);
          if (result.stats) return result;
        }
      }
    }

    return { rank: 0, stats: null };
  }, [address, member, allMemberships, getUserRank]);

  // Get popular books for stats
  const popularBooks = getPopularBooks(100);

  // Helper to get all stats for a specific upload
  const getBookStats = (contentKey: string) => {
    const bookStats = popularBooks.find(b => b.contentKey === contentKey);
    return {
      opens: bookStats?.opens || 0,
      currentlyReading: bookStats?.currentlyReading || 0,
      addedToQueues: bookStats?.addedToQueues || 0,
      upvotes: getUpvoteCount(contentKey),
    };
  };

  const isLoading = isLoadingUser || isLoadingDiscovery || isLoadingLeaderboard || isLoadingMembership || isLoadingStats || isLoadingStacks;

  // Loading state
  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center py-20">
        <div className="text-4xl mb-4 animate-pulse text-[#00ff00]"><UserIcon size={48} /></div>
        <P className="text-[#00ff00] font-mono">Loading your profile...</P>
        <Small className="text-gray-500 font-mono mt-2">Fetching onchain data</Small>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      {/* Main Subtab Toggle: My Profile | All Members */}
      <div className="flex gap-1 p-1 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl">
        <button
          onClick={() => setMembersSubTab("my-profile")}
          className={`flex-1 py-2.5 px-4 rounded-lg font-mono text-sm transition-all ${
            membersSubTab === "my-profile"
              ? "bg-[#00ff00] text-black font-bold"
              : "text-[#00ff00]/70 hover:bg-[#00ff00]/10"
          }`}
        >
          My Profile
        </button>
        <button
          onClick={() => setMembersSubTab("all-members")}
          className={`flex-1 py-2.5 px-4 rounded-lg font-mono text-sm transition-all ${
            membersSubTab === "all-members"
              ? "bg-[#00ff00] text-black font-bold"
              : "text-[#00ff00]/70 hover:bg-[#00ff00]/10"
          }`}
        >
          All Members
        </button>
      </div>

      {/* All Members Feed */}
      {membersSubTab === "all-members" && (
        <AllMembersFeed />
      )}

      {/* My Profile Content */}
      {membersSubTab === "my-profile" && (
        <>
      {/* NET LIBRARY CARD - Matrix-style library card */}
      <div className="relative overflow-hidden rounded-xl border-2 border-[#00ff00]/50 bg-gradient-to-br from-[#0a0a0a] via-[#0d1a0d] to-[#0a0a0a] shadow-[0_0_30px_rgba(0,255,0,0.15)]">
            {/* Scanline effect overlay */}
            <div className="absolute inset-0 bg-[linear-gradient(transparent_50%,rgba(0,0,0,0.1)_50%)] bg-[length:100%_4px] pointer-events-none opacity-30" />

            {/* Glowing corner accents */}
            <div className="absolute top-0 left-0 w-16 h-16 bg-gradient-to-br from-[#00ff00]/20 to-transparent" />
            <div className="absolute bottom-0 right-0 w-16 h-16 bg-gradient-to-tl from-[#00ff00]/20 to-transparent" />

            {/* Card Header */}
            <div className="relative px-4 py-2 border-b border-[#00ff00]/30 bg-[#00ff00]/5">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-[#00ff00] animate-pulse shadow-[0_0_8px_#00ff00]" />
                  <span className="text-[10px] font-mono text-[#00ff00]/70 tracking-[0.2em] uppercase">Net Protocol</span>
                </div>
                <span className="text-[10px] font-mono text-[#00ff00]/50">Onchain Library Card</span>
              </div>
            </div>

            {/* Main Card Content */}
            <div className="relative p-4">
              {/* Top Section - Photo & Identity */}
              <div className="flex gap-4 mb-4">
                {/* Photo with frame + Link to Net */}
                <div className="flex flex-col items-start w-20">
                  <div className="relative">
                    <div className="w-20 h-24 rounded-lg border-2 border-[#00ff00]/50 overflow-hidden bg-black shadow-[inset_0_0_20px_rgba(0,255,0,0.1)]">
                      <img
                        src={userProfile?.pfpUrl || `https://api.dicebear.com/7.x/identicon/svg?seed=${address}`}
                        alt="avatar"
                        className="w-full h-full object-cover"
                      />
                    </div>
                    {/* Holographic shine effect */}
                    <div className="absolute inset-0 rounded-lg bg-gradient-to-br from-white/10 via-transparent to-transparent pointer-events-none" />
                  </div>
                  {/* Net Link or Link to Net button */}
                  {netLink ? (
                    <div className="mt-4 flex items-center gap-2">
                      <button
                        onClick={() => openNetLink(netLink.url)}
                        className={`text-[9px] font-mono underline transition-colors text-left whitespace-nowrap ${
                          member?.isAgent
                            ? "text-[#B794F4] hover:text-[#B794F4]/80"
                            : "text-[#00ff00] hover:text-[#00ff00]/80"
                        } ${netLink.label.length > 30 ? 'truncate max-w-[80px]' : ''}`}
                        title={netLink.label}
                      >
                        {netLink.label}
                      </button>
                      <button
                        onClick={() => setShowLinkToNetModal(true)}
                        className={`text-[7px] font-mono text-gray-500 transition-colors ${
                          member?.isAgent ? "hover:text-[#B794F4]/70" : "hover:text-[#00ff00]/70"
                        }`}
                      >
                        edit
                      </button>
                    </div>
                  ) : (
                    <button
                      onClick={() => setShowLinkToNetModal(true)}
                      className={`mt-2 px-2 py-1 text-[8px] font-mono rounded transition-colors ${
                        member?.isAgent
                          ? "text-[#B794F4]/70 border border-[#B794F4]/30 hover:bg-[#B794F4]/10 hover:text-[#B794F4]"
                          : "text-[#00ff00]/70 border border-[#00ff00]/30 hover:bg-[#00ff00]/10 hover:text-[#00ff00]"
                      }`}
                    >
                      Link to Net
                    </button>
                  )}
                </div>

                {/* Identity Info */}
                <div className="min-w-0 flex flex-col justify-between h-24">
                  <div className="min-w-0">
                    <P className={`font-mono font-bold text-lg leading-none truncate -mt-0.5 ${member?.isAgent ? "text-[#B794F4]" : "text-[#00ff00]"}`}>
                      {userProfile?.displayName || userProfile?.username || "Anonymous"}
                    </P>
                    {(userProfile?.storedFarcasterUsername || userProfile?.username) && (
                      <button
                        onClick={async () => {
                          const handle = userProfile.storedFarcasterUsername || userProfile.username;
                          const profileUrl = `https://warpcast.com/${handle}`;
                          await safeOpenUrl(profileUrl);
                        }}
                        className={`font-mono truncate block text-sm transition-colors text-left ${
                          member?.isAgent
                            ? "text-[#B794F4]/60 hover:text-[#B794F4]"
                            : "text-[#00ff00]/60 hover:text-[#00ff00]"
                        }`}
                      >
                        @{userProfile?.storedFarcasterUsername || userProfile?.username}
                      </button>
                    )}
                    {/* Member badge and ENS subname(s) with platform indicators */}
                    {isMember && member && (
                      <div className="mt-2 flex flex-col gap-0.5">
                        <span className="text-[10px] font-mono font-bold tracking-wider">
                          <span className={member.isAgent ? "text-[#B794F4]" : "text-[#00ff00]"}>MEMBER</span>
                          {member.isAgent && <span className="text-[#B794F4]"> · AGENT</span>}
                        </span>
                        {/* Show all memberships with platform indicator */}
                        {allMemberships && allMemberships.length > 0 ? (
                          <div className="flex flex-col gap-0.5 -mt-0.5">
                            {allMemberships.map((m) => (
                              <span key={m.memberId} className={`text-[9px] font-mono flex items-center gap-1 ${member.isAgent ? "text-[#B794F4]/70" : "text-[#00ff00]/70"}`}>
                                <span>{m.ensSubname}</span>
                                {m.signupPlatform === "farcaster" ? (
                                  <FarcasterIcon size={10} className="text-purple-400" />
                                ) : m.signupPlatform === "web" ? (
                                  <WebIcon size={10} className="text-yellow-400" />
                                ) : (
                                  <BaseIcon size={10} className="text-blue-400" />
                                )}
                              </span>
                            ))}
                          </div>
                        ) : (
                          <span className={`text-[9px] font-mono -mt-0.5 ${member.isAgent ? "text-[#B794F4]/70" : "text-[#00ff00]/70"}`}>
                            {member.ensSubname}
                          </span>
                        )}
                        {/* Link Farcaster button for Base App users without FID */}
                        {appMode === "base-app" && !userProfile?.fid && (
                          <button
                            onClick={() => setShowLinkFarcasterModal(true)}
                            className="mt-1 px-1.5 py-0.5 text-[8px] font-mono text-purple-400 border border-purple-500/30 rounded hover:bg-purple-500/10 transition-colors flex items-center gap-1 w-fit"
                          >
                            <FarcasterIcon size={10} className="text-purple-400" />
                            <span>Link Farcaster</span>
                          </button>
                        )}
                        {/* Edit Profile button for Web platform users */}
                        {appMode === "web" && member?.signupPlatform === "web" && (
                          <button
                            onClick={() => setShowWebProfileEditor(true)}
                            className="mt-1 px-1.5 py-0.5 text-[8px] font-mono text-yellow-400 border border-yellow-500/30 rounded hover:bg-yellow-500/10 transition-colors flex items-center gap-1 w-fit"
                          >
                            <EditIcon size={12} />
                            <span>Edit Profile</span>
                          </button>
                        )}
                      </div>
                    )}
                  </div>
                  {/* Rank Badge - at bottom aligned with PFP, only show for rank 1-100 */}
                  {rank > 0 && rank <= 100 && (
                    <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-[#00ff00]/20 border border-[#00ff00]/30 w-fit">
                      <TrophyIcon size={10} className="text-[#00ff00]" />
                      <span className="text-[8px] font-mono text-[#00ff00] font-bold">RANK #{rank}</span>
                    </span>
                  )}
                </div>

                {/* Spacer to push shield right */}
                <div className="flex-1" />

                {/* Net Library Crest - Watermark style with upvotes below */}
                <div className="flex flex-col items-center flex-shrink-0 self-start" style={{ width: 'calc((100% - 2rem) / 3)' }}>
                  <div className="relative opacity-30 w-full" style={{ mixBlendMode: 'screen' }}>
                    <img src="/app-logo.png" alt="Net Library" className="w-full h-auto" />
                  </div>
                  {/* Upvotes - centered below shield */}
                  <div className="flex items-center gap-1 mt-2">
                    <span className="text-[#00ff00] font-mono text-lg">▲</span>
                    <span className="text-[#00ff00] font-mono text-lg font-bold">{totalUpvotesReceived}</span>
                  </div>
                </div>
              </div>

              {/* Membership Address - show the registered wallet */}
              {isMember && member?.address && (
                <div className="mt-2">
                  <Small className="text-[8px] font-mono text-gray-600 tracking-wider truncate block">
                    {member.address}
                  </Small>
                </div>
              )}

              {/* Cross-Platform Identity System (CPIS) - Simplified */}
              {isMember && (
                <div className="mt-3">
                  <button
                    onClick={() => setShowCpis(!showCpis)}
                    className="w-full flex items-center justify-between p-2 rounded-lg bg-black/30 border border-[#00ff00]/20 hover:border-[#00ff00]/40 transition-colors"
                  >
                    <div className="flex items-center gap-2">
                      <span className="text-[10px] font-mono text-gray-400">Cross-Platform Identity</span>
                      {/* Quick status badges */}
                      <div className="flex items-center gap-1.5">
                        <span className={`flex items-center gap-0.5 text-[9px] font-mono ${isFarcasterVerified ? "text-purple-400" : "text-purple-400/30"}`}>
                          <FarcasterIcon size={10} className={isFarcasterVerified ? "text-purple-400" : "text-purple-400/30"} />
                          {isFarcasterVerified ? "✓" : "○"}
                        </span>
                        <span className={`flex items-center gap-0.5 text-[9px] font-mono ${isBaseAppVerified ? "text-blue-400" : "text-blue-400/30"}`}>
                          <BaseIcon size={10} className={isBaseAppVerified ? "text-blue-400" : "text-blue-400/30"} />
                          {isBaseAppVerified ? "✓" : "○"}
                        </span>
                        <span className={`flex items-center gap-0.5 text-[9px] font-mono ${isWebVerified ? "text-yellow-400" : "text-yellow-400/30"}`}>
                          <WebIcon size={10} className={isWebVerified ? "text-yellow-400" : "text-yellow-400/30"} />
                          {isWebVerified ? "✓" : "○"}
                        </span>
                      </div>
                    </div>
                    <span className="text-gray-500 text-xs">{showCpis ? "▲" : "▼"}</span>
                  </button>

                  {showCpis && (
                    <div className="mt-2 p-3 rounded-lg bg-black/50 border border-[#00ff00]/10 space-y-3">
                      {/* Farcaster Status */}
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <FarcasterIcon size={16} className="text-purple-400" />
                          <div>
                            <Small className="text-white font-mono block">Farcaster</Small>
                            <span className="text-[9px] font-mono text-gray-500">
                              {member?.fid ? `@${member.farcasterUsername || member.username || `FID ${member.fid}`}` : userProfile?.fid ? `@${userProfile.storedFarcasterUsername || userProfile.username}` : "Not connected"}
                            </span>
                          </div>
                        </div>
                        {isFarcasterVerified ? (
                          <div className="flex items-center gap-1">
                            <span className="px-2 py-0.5 rounded text-[9px] font-mono bg-purple-500/20 text-purple-400 border border-purple-500/30">
                              Verified ✓
                            </span>
                            {member?.fid && (
                              <button
                                onClick={() => setShowUnlinkConfirm(true)}
                                className="px-1 py-0.5 rounded text-[8px] font-mono text-gray-500 hover:text-red-400 transition-colors"
                                title="Unlink Farcaster (for FID transfers)"
                              >
                                ×
                              </button>
                            )}
                          </div>
                        ) : (
                          <span className="px-2 py-0.5 rounded text-[9px] font-mono bg-gray-800 text-gray-500 border border-gray-700">
                            Not Linked
                          </span>
                        )}
                      </div>

                      {/* Base App Status */}
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <BaseIcon size={16} className="text-blue-400" />
                          <div>
                            <Small className="text-white font-mono block">Base App</Small>
                            <span className="text-[9px] font-mono text-gray-500">
                              {isBaseAppVerified ? "Wallet linked" : "Not linked"}
                            </span>
                          </div>
                        </div>
                        {isBaseAppVerified ? (
                          <span className="px-2 py-0.5 rounded text-[9px] font-mono bg-blue-500/20 text-blue-400 border border-blue-500/30">
                            Verified ✓
                          </span>
                        ) : (
                          <span className="px-2 py-0.5 rounded text-[9px] font-mono bg-gray-800 text-gray-500 border border-gray-700">
                            Not Linked
                          </span>
                        )}
                      </div>

                      {/* Web Status */}
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <WebIcon size={16} className="text-yellow-400" />
                          <div>
                            <Small className="text-white font-mono block">Web Browser</Small>
                            <span className="text-[9px] font-mono text-gray-500">
                              {isWebVerified ? "Wallet linked" : "Not linked"}
                            </span>
                          </div>
                        </div>
                        {isWebVerified ? (
                          <span className="px-2 py-0.5 rounded text-[9px] font-mono bg-yellow-500/20 text-yellow-400 border border-yellow-500/30">
                            Verified ✓
                          </span>
                        ) : (
                          <span className="px-2 py-0.5 rounded text-[9px] font-mono bg-gray-800 text-gray-500 border border-gray-700">
                            Not Linked
                          </span>
                        )}
                      </div>

                      {/* Cross-platform status message */}
                      <div className="pt-2 border-t border-[#00ff00]/10">
                        {isFarcasterVerified && isBaseAppVerified && isWebVerified ? (
                          <Small className="text-[#00ff00] font-mono text-[10px] block text-center">
                            <LinkIcon size={12} className="inline mr-1" /> Identity verified on all platforms!
                          </Small>
                        ) : (isFarcasterVerified && isBaseAppVerified) || (isFarcasterVerified && isWebVerified) || (isBaseAppVerified && isWebVerified) ? (
                          <Small className="text-[#00ff00]/70 font-mono text-[10px] block text-center">
                            <LinkIcon size={12} className="inline mr-1" /> Identity verified on {[isFarcasterVerified && "Farcaster", isBaseAppVerified && "Base App", isWebVerified && "Web"].filter(Boolean).join(" & ")}
                          </Small>
                        ) : isFarcasterVerified || isBaseAppVerified || isWebVerified ? (
                          <Small className="text-gray-500 font-mono text-[10px] block text-center">
                            Verified on {isFarcasterVerified ? "Farcaster" : isBaseAppVerified ? "Base App" : "Web"}. Use all apps to verify everywhere.
                          </Small>
                        ) : (
                          <Small className="text-gray-500 font-mono text-[10px] block text-center">
                            Connect on all platforms to use your membership anywhere.
                          </Small>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* Divider with circuit pattern */}
              <div className="relative h-px bg-[#00ff00]/20 my-3">
                <div className="absolute left-0 top-1/2 -translate-y-1/2 w-2 h-2 rounded-full bg-[#00ff00]/40" />
                <div className="absolute right-0 top-1/2 -translate-y-1/2 w-2 h-2 rounded-full bg-[#00ff00]/40" />
                <div className="absolute left-1/4 top-1/2 -translate-y-1/2 w-1 h-1 rounded-full bg-[#00ff00]/30" />
                <div className="absolute left-1/2 top-1/2 -translate-y-1/2 w-1 h-1 rounded-full bg-[#00ff00]/30" />
                <div className="absolute left-3/4 top-1/2 -translate-y-1/2 w-1 h-1 rounded-full bg-[#00ff00]/30" />
              </div>

              {/* Stats Grid - Order: Stacks, Grids, Uploads, Data */}
              <div className="grid grid-cols-4 gap-2">
                <div className="flex flex-col items-center justify-center p-2 rounded-lg bg-black/50 border border-[#00ff00]/20">
                  <P className="text-xl font-bold text-[#00ff00] font-mono leading-none text-center">
                    {userStacks.length}
                  </P>
                  <Small className="text-[9px] text-gray-500 font-mono uppercase tracking-wider text-center">Stacks</Small>
                </div>
                <div className="flex flex-col items-center justify-center p-2 rounded-lg bg-black/50 border border-[#00ff00]/20">
                  <P className="text-xl font-bold text-[#00ff00] font-mono leading-none text-center">
                    {userGrids.length}
                  </P>
                  <Small className="text-[9px] text-gray-500 font-mono uppercase tracking-wider text-center">Grids</Small>
                </div>
                <div className="flex flex-col items-center justify-center p-2 rounded-lg bg-black/50 border border-[#00ff00]/20">
                  <P className="text-xl font-bold text-[#00ff00] font-mono leading-none text-center">
                    {userStats?.totalUploads || myUploads.length}
                  </P>
                  <Small className="text-[9px] text-gray-500 font-mono uppercase tracking-wider text-center">Uploads</Small>
                </div>
                <div className="flex flex-col items-center justify-center p-2 rounded-lg bg-black/50 border border-[#00ff00]/20">
                  {(() => {
                    const bytes = userStats?.totalBytesUploaded || myUploads.reduce((acc, u) => acc + u.fileSize, 0);
                    const formatted = formatBytes(bytes);
                    const [num, unit] = formatted.split(' ');
                    return (
                      <>
                        <P className="text-xl font-bold text-[#00ff00] font-mono leading-none text-center">
                          {num}
                        </P>
                        <Small className="text-[9px] text-gray-500 font-mono uppercase tracking-wider text-center">
                          {unit || 'B'}
                        </Small>
                      </>
                    );
                  })()}
                </div>
              </div>

              {/* Membership / Share Button */}
              <MembershipButton
                username={userProfile?.storedFarcasterUsername || userProfile?.username || "user"}
                displayName={userProfile?.displayName || userProfile?.username}
                isMember={isMember}
                member={member}
                address={address}
                fid={userProfile?.fid}
                stats={{
                  uploads: userStats?.totalUploads || myUploads.length,
                  dataMb: ((userStats?.totalBytesUploaded || myUploads.reduce((acc, u) => acc + u.fileSize, 0)) / (1024 * 1024)).toFixed(1),
                  upvotes: totalUpvotesReceived,
                }}
                pfpUrl={userProfile?.pfpUrl}
                onMembershipComplete={refreshMembership}
                fcVerified={isFarcasterVerified}
                baseVerified={isBaseAppVerified}
                webVerified={isWebVerified}
                hasNetLink={!!netLink}
                netLinkLabel={netLink?.label || ""}
              />
              {/* "Already a member?" link for Base App non-members */}
              {!isMember && appMode === "base-app" && (
                <div className="mt-2 text-center">
                  <button
                    onClick={() => setShowClaimMembershipModal(true)}
                    className="text-[11px] font-mono text-purple-400 hover:text-purple-300 underline underline-offset-2 transition-colors flex items-center gap-1 justify-center"
                  >
                    <FarcasterIcon size={12} className="text-purple-400" />
                    Already a member on Farcaster? Link your account
                  </button>
                </div>
              )}
            </div>

            {/* Card Footer - Braille username + Stack Pass + identifier */}
            <div className="relative px-4 py-2 border-t border-[#00ff00]/20 bg-black/30">
              <div className="flex items-center justify-between gap-2">
                {/* Username in Braille */}
                <span className="text-sm font-mono text-[#00ff00]/50 tracking-wide shrink-0" title={userProfile?.username || "guest"}>
                  {toBraille(userProfile?.username || "guest")}
                </span>

                {/* Unlimited Pass Badge - Premium holographic style with occasional glimmer */}
                {member?.hasStackPass && (
                  <div className="relative flex items-center gap-1.5 px-2 py-0.5 rounded-full bg-gradient-to-r from-purple-500/20 via-[#00ff00]/20 to-purple-500/20 border border-purple-500/40 shrink-0 overflow-hidden">
                    {/* Glimmer effect - sweeps on load, then occasionally */}
                    <div
                      className="absolute inset-0 bg-gradient-to-r from-transparent via-white/30 to-transparent"
                      style={{
                        animation: 'glimmer-initial 0.6s ease-out forwards, glimmer-repeat 5s ease-in-out 1s infinite',
                      }}
                    />
                    <span className="text-[10px] relative z-10">∞</span>
                    <span className="text-[8px] font-mono font-bold bg-gradient-to-r from-purple-400 via-[#00ff00] to-purple-400 bg-clip-text text-transparent tracking-wider uppercase relative z-10">
                      UNLIMITED
                    </span>
                    <style jsx>{`
                      @keyframes glimmer-initial {
                        0% {
                          transform: translateX(-100%);
                        }
                        100% {
                          transform: translateX(100%);
                        }
                      }
                      @keyframes glimmer-repeat {
                        0%, 85%, 100% {
                          transform: translateX(-100%);
                        }
                        92% {
                          transform: translateX(100%);
                        }
                      }
                    `}</style>
                  </div>
                )}

                {/* FID for Farcaster users, Member # for Base App users, Guest for non-members */}
                <span className="text-[8px] font-mono text-[#00ff00]/40 tracking-widest shrink-0">
                  {isMember && member
                    ? (member.fid ? `FID-${member.fid}` : `MEMBER-${member.memberId}`)
                    : (userProfile?.fid ? `FID-${userProfile.fid}` : 'GUEST-ACCESS')
                  }
                </span>
              </div>
            </div>
          </div>

          {/* Achievements Section - Member-gated */}
          <AchievementsSection
            earnedIds={earnedIds}
            isMember={isMember}
          />

          {/* Member Resources Section - Member-gated */}
          <MemberResourcesSection
            isMember={isMember}
            userAddress={address}
            userFid={userProfile?.fid}
            userUploads={myUploads.map(u => ({ contentKey: u.contentKey, title: u.title, author: u.author }))}
            userStacks={userStacks.map(s => ({ id: s.id, name: s.name, itemCount: s.itemCount }))}
            userGrids={userGrids.map(g => ({ id: g.id, name: g.name, size: g.size }))}
          />

          {/* Sub-tabs for My Uploads, My Stacks, and Hidden */}
          <div className="flex gap-1 bg-[#0a0a0a] p-1 rounded-xl border border-[#00ff00]/20">
            <button
              onClick={() => setProfileSubTab("uploads")}
              className={`flex-1 py-2 px-2 rounded-lg text-xs font-mono transition-all ${
                profileSubTab === "uploads"
                  ? "bg-[#00ff00] text-black"
                  : "text-gray-400 hover:text-[#00ff00]"
              }`}
            >
              <UploadIcon size={12} className="inline mr-1" /> Uploads ({myUploads.length})
            </button>
            <button
              onClick={() => setProfileSubTab("stacks")}
              className={`flex-1 py-2 px-2 rounded-lg text-xs font-mono transition-all flex items-center justify-center gap-1 ${
                profileSubTab === "stacks"
                  ? "bg-[#00ff00] text-black"
                  : "text-gray-400 hover:text-[#00ff00]"
              }`}
            >
              <LibraryIcon size={12} /> Stacks ({userStacks.length})
            </button>
            <button
              onClick={() => setProfileSubTab("grids")}
              className={`flex-1 py-2 px-2 rounded-lg text-xs font-mono transition-all ${
                profileSubTab === "grids"
                  ? "bg-[#00ff00] text-black"
                  : "text-gray-400 hover:text-[#00ff00]"
              }`}
            >
              <GridIcon size={12} className="inline mr-1" /> Grids ({userGrids.length})
            </button>
            <button
              onClick={() => setProfileSubTab("hidden")}
              className={`flex-1 py-2 px-2 rounded-lg text-xs font-mono transition-all ${
                profileSubTab === "hidden"
                  ? "bg-gray-600 text-white"
                  : "text-gray-400 hover:text-gray-300"
              }`}
            >
              <EyeOffIcon size={12} className="inline mr-1" /> Hidden
            </button>
            <button
              onClick={() => setProfileSubTab("verify")}
              className={`flex-1 py-2 px-2 rounded-lg text-xs font-mono transition-all ${
                profileSubTab === "verify"
                  ? "bg-orange-500 text-white"
                  : "text-gray-400 hover:text-orange-400"
              }`}
            >
              <SearchIcon size={12} className="inline mr-1" /> Verify
            </button>
          </div>

          {/* My Uploads content */}
          {profileSubTab === "uploads" && (
            <>
              {/* Sort Filter - only show if there are uploads */}
              {myUploads.length > 0 && (
                <div className="flex items-center gap-2">
                  <Small className="text-gray-500 font-mono text-[10px]">Sort:</Small>
                  <div className="flex gap-1 flex-1">
                    <button
                      onClick={() => setUploadsSortBy("recent")}
                      className={`flex-1 px-2 py-1.5 rounded text-[10px] font-mono transition-all ${
                        uploadsSortBy === "recent"
                          ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/50"
                          : "bg-[#1a1a1a] text-gray-400 border border-transparent hover:border-[#00ff00]/30"
                      }`}
                    >
                      Recent
                    </button>
                    <button
                      onClick={() => setUploadsSortBy("upvotes")}
                      className={`flex-1 px-2 py-1.5 rounded text-[10px] font-mono transition-all ${
                        uploadsSortBy === "upvotes"
                          ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/50"
                          : "bg-[#1a1a1a] text-gray-400 border border-transparent hover:border-[#00ff00]/30"
                      }`}
                    >
                      Most Upvoted
                    </button>
                    <button
                      onClick={() => setUploadsSortBy("cdn-links")}
                      className={`flex-1 px-2 py-1.5 rounded text-[10px] font-mono transition-all ${
                        uploadsSortBy === "cdn-links"
                          ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/50"
                          : "bg-[#1a1a1a] text-gray-400 border border-transparent hover:border-[#00ff00]/30"
                      }`}
                    >
                      CDN Links
                    </button>
                  </div>
                </div>
              )}

              {/* Empty state */}
              {myUploads.length === 0 && (
                <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
                  <CardContent className="p-8 text-center">
                    <div className="w-16 h-16 mx-auto mb-3 rounded-full bg-[#00ff00]/10 flex items-center justify-center border-2 border-dashed border-[#00ff00]/30">
                      <UploadIcon size={28} className="text-[#00ff00]/60" />
                    </div>
                    <P className="text-[#00ff00] font-mono">No uploads yet</P>
                    <Small className="text-gray-500 font-mono">
                      Go to the Upload tab to share knowledge on Net Protocol
                    </Small>
                  </CardContent>
                </Card>
              )}

              {/* CDN Links View */}
              {uploadsSortBy === "cdn-links" && myUploads.length > 0 && (
                <CdnLinksView uploads={sortedUploads} />
              )}

              {/* Upload list (hidden when CDN Links view is active) */}
              {uploadsSortBy !== "cdn-links" && sortedUploads.map((upload) => {
            const uploadCategories = (Array.isArray(upload.categories) ? upload.categories : [])
              .map((catId) => categories.find((c) => c.id === catId))
              .filter(Boolean);
            const stats = getBookStats(upload.contentKey);
            return (
              <Card
                key={upload.contentKey}
                className="bg-[#0a0a0a] border-2 border-[#00ff00]/30 hover:border-[#00ff00] hover:shadow-[0_0_15px_rgba(0,255,0,0.3)] transition-all cursor-pointer"
                onClick={() => {
                  // Navigate to book detail by constructing the book object
                  const book = {
                    id: upload.contentKey,
                    title: upload.title,
                    author: upload.author,
                    categories: upload.categories,
                    uploader: {
                      username: userProfile?.username || (address ? address.slice(0, 6) + "..." + address.slice(-4) : "unknown"),
                      pfpUrl: userProfile?.pfpUrl || `https://api.dicebear.com/7.x/identicon/svg?seed=${address || 'unknown'}`,
                      address: upload.operator || "",
                    },
                    uploadDate: new Date(upload.uploadedAt).toLocaleDateString("en-US", {
                      month: "short",
                      day: "numeric",
                      year: "numeric",
                    }),
                    size: formatBytes(upload.fileSize),
                    contentKey: upload.contentKey,
                    storageType: upload.storageType,
                    coverUrl: upload.coverUrl,
                  };
                  // Dispatch custom event to select this book in the parent
                  window.dispatchEvent(new CustomEvent("select-book", { detail: book }));
                }}
              >
                <CardContent className="p-4">
                  <div className="flex gap-3">
                    {/* Cover art with edit button */}
                    <div className="relative shrink-0 group">
                      <div className="w-16 h-22 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded flex items-center justify-center border border-[#00ff00]/20 overflow-hidden">
                        {(upload.coverUrl || upload.cdnUrl) ? (
                          <img src={getEffectiveCoverUrl(upload)} alt={upload.title} className="w-full h-full object-cover" />
                        ) : (
                          <BookmarkIcon size={24} className="text-[#00ff00]/50" />
                        )}
                      </div>
                      {/* Edit button */}
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          setEditingItem(upload);
                        }}
                        className="absolute -bottom-1 -right-1 w-6 h-6 bg-[#00ff00] text-black rounded-full flex items-center justify-center text-xs shadow-lg hover:bg-[#00ff00]/80 transition-colors"
                        title="Edit item details"
                      >
                        <EditIcon size={12} />
                      </button>
                    </div>
                    <div className="flex-1 min-w-0">
                      <P className="font-medium truncate text-white font-mono">{upload.title}</P>
                      <Small className="text-gray-400 font-mono">{upload.author}</Small>
                      <Small className="text-[#00ff00]/70 block font-mono">
                        {formatBytes(upload.fileSize)} • {upload.storageType} storage
                      </Small>
                      <Small className="text-gray-500 block font-mono">
                        Uploaded {new Date(upload.uploadedAt).toLocaleDateString()}
                      </Small>
                      {/* Category tags */}
                      <div className="flex flex-wrap gap-1 mt-2">
                        {uploadCategories.map((cat) => (
                          <span
                            key={cat?.id}
                            className="px-1.5 py-0.5 rounded text-[10px] bg-[#00ff00]/10 text-[#00ff00]/70 font-mono"
                          >
                            {cat?.emoji} {cat?.label}
                          </span>
                        ))}
                      </div>
                    </div>
                  </div>

                  {/* Upload engagement stats */}
                  <UploadEngagementStats stats={stats} />

                  {/* Trending share button - shows when 100+ upvotes in last hour */}
                  <TrendingShareButton
                    title={upload.title}
                    upvotes={stats.upvotes}
                    contentKey={upload.contentKey}
                  />
                </CardContent>
              </Card>
            );
          })}
            </>
          )}

          {/* My Stacks sub-tab content */}
          {profileSubTab === "stacks" && (
            <div className="space-y-4">
              {/* Create New Stack Button */}
              <button
                onClick={() => setShowCreateStackModal(true)}
                className="w-full py-3 px-4 bg-[#00ff00]/10 border-2 border-dashed border-[#00ff00]/40 rounded-xl text-[#00ff00] font-mono hover:bg-[#00ff00]/20 hover:border-[#00ff00]/60 transition-all flex items-center justify-center gap-2"
              >
                <LibraryIcon size={18} />
                <span>Create New Stack</span>
              </button>

              {/* Stack List */}
              {userStacks.length === 0 ? (
                <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
                  <CardContent className="p-6 text-center">
                    <div className="w-14 h-14 mx-auto mb-3 rounded-full bg-[#00ff00]/10 flex items-center justify-center border-2 border-dashed border-[#00ff00]/30">
                      <span className="text-xl text-[#00ff00]"><LibraryIcon size={24} /></span>
                    </div>
                    <P className="text-[#00ff00] font-mono">No stacks yet</P>
                    <Small className="text-gray-500 font-mono">
                      Create your first stack to curate your favorite items!
                    </Small>
                  </CardContent>
                </Card>
              ) : (
                userStacks.map((stack) => {
                  const itemCount = stack.itemCount || 0;
                  const maxItems = 20;
                  const isUnlocked = stack.unlocked;
                  const isFull = !isUnlocked && itemCount >= maxItems;
                  const isNearLimit = !isUnlocked && itemCount >= 15 && itemCount < maxItems;
                  const progressPercent = isUnlocked ? 100 : Math.min((itemCount / maxItems) * 100, 100);

                  // Color logic: gray normal (1-14), yellow (15-19), green (full at 20)
                  const progressColor = isFull
                    ? "bg-[#00ff00]"
                    : isNearLimit
                    ? "bg-yellow-500"
                    : "bg-gray-500";
                  const progressTextColor = isFull
                    ? "text-[#00ff00]"
                    : isNearLimit
                    ? "text-yellow-400"
                    : "text-gray-500";

                  return (
                    <div key={stack.id}>
                      {/* Delete confirmation UI - shown when this stack is selected for deletion */}
                      {stackToDelete === stack.id ? (
                        <div className="flex flex-col gap-2 p-3 bg-red-500/10 border border-red-500/30 rounded-lg">
                          <span className="text-sm text-red-400 font-mono truncate">Delete &ldquo;{stack.name}&rdquo;?</span>
                          <label className="flex items-center gap-2 cursor-pointer">
                            <input
                              type="checkbox"
                              checked={hideItemsOnDelete}
                              onChange={(e) => setHideItemsOnDelete(e.target.checked)}
                              className="accent-red-500"
                              disabled={isDeleting}
                            />
                            <span className="text-xs text-gray-400 font-mono">Also hide items from library</span>
                          </label>
                          <div className="flex gap-2 justify-end">
                            <button
                              onClick={(e) => { e.stopPropagation(); setStackToDelete(null); setHideItemsOnDelete(false); }}
                              className="px-3 py-1 text-xs font-mono text-gray-400 bg-[#1a1a1a] rounded hover:bg-[#222]"
                              disabled={isDeleting}
                            >
                              Cancel
                            </button>
                            <button
                              onClick={async (e) => {
                                e.stopPropagation();
                                setIsDeleting(true);
                                try {
                                  // Step A: Fetch stack items BEFORE deletion if we need to hide them
                                  let itemsToHide: Array<{ contentKey: string }> = [];
                                  if (hideItemsOnDelete) {
                                    try {
                                      const stackData = await fetch(`/api/stacks?stackId=${stack.id}`).then(r => r.json());
                                      itemsToHide = stackData?.stack?.items || [];
                                      console.log("[My Stacks] Items to hide after deletion:", itemsToHide.length);
                                    } catch (fetchErr) {
                                      console.error("[My Stacks] Failed to fetch stack items:", fetchErr);
                                    }
                                  }

                                  // Step B: Delete the stack
                                  const success = await deleteStack(stack.id, stack.owner);

                                  if (success) {
                                    // Step C: Hide items if option was checked
                                    if (hideItemsOnDelete && itemsToHide.length > 0 && address) {
                                      console.log("[My Stacks] Hiding", itemsToHide.length, "items from library");
                                      for (const item of itemsToHide) {
                                        if (item.contentKey) {
                                          try {
                                            await fetch("/api/discovery", {
                                              method: "PATCH",
                                              headers: { "Content-Type": "application/json" },
                                              body: JSON.stringify({
                                                contentKey: item.contentKey,
                                                operator: address,
                                                hidden: true,
                                              }),
                                            });
                                          } catch (hideErr) {
                                            console.error("[My Stacks] Failed to hide item:", item.contentKey, hideErr);
                                          }
                                        }
                                      }
                                    }

                                    // Step D: Refresh
                                    refreshStacks();
                                  } else {
                                    console.error("[My Stacks] Delete failed for stack:", stack.id);
                                  }
                                } catch (err) {
                                  console.error("[My Stacks] Delete error:", err);
                                } finally {
                                  setIsDeleting(false);
                                  setStackToDelete(null);
                                  setHideItemsOnDelete(false);
                                }
                              }}
                              className="px-3 py-1 text-xs font-mono text-white bg-red-600 rounded hover:bg-red-500"
                              disabled={isDeleting}
                            >
                              {isDeleting ? "Deleting..." : "Delete"}
                            </button>
                          </div>
                        </div>
                      ) : (
                        <Card
                          className="bg-[#0a0a0a] border-2 border-[#00ff00]/30 hover:border-[#00ff00] hover:shadow-[0_0_15px_rgba(0,255,0,0.3)] transition-all cursor-pointer"
                          onClick={() => {
                            // Navigate to stack in Browse tab
                            window.dispatchEvent(new CustomEvent("navigate-to-stack", { detail: stack }));
                          }}
                        >
                          <CardContent className="p-4">
                            <div className="flex gap-3">
                              <div className="flex-1 min-w-0">
                                {/* Title with privacy badge */}
                                <div className="flex items-center gap-2">
                                  <P className="font-medium truncate text-white font-mono">{stack.name}</P>
                                  {stack.isPrivate && (
                                    <span className="px-1.5 py-0.5 text-[9px] bg-[#00ff00]/20 text-[#00ff00] rounded font-mono shrink-0 flex items-center">
                                      <LockIcon size={10} />
                                    </span>
                                  )}
                                </div>
                                {/* Description - under title */}
                                {stack.description && (
                                  <Small className="text-gray-400 font-mono line-clamp-2 mt-0.5">{stack.description}</Small>
                                )}
                                {/* Preview covers row - between description and stats */}
                                {stack.previewCovers && stack.previewCovers.length > 0 && (
                                  <div className="flex items-center gap-1 mt-2">
                                    {stack.previewCovers.slice(0, 5).map((coverUrl, index) => (
                                      <div
                                        key={index}
                                        className="w-7 h-10 rounded bg-gray-800 flex-shrink-0 overflow-hidden"
                                      >
                                        <CoverImage
                                          src={coverUrl}
                                          alt=""
                                          className="w-full h-full object-cover"
                                          fallbackLogoSize="w-4 h-4"
                                        />
                                      </div>
                                    ))}
                                    {itemCount > (stack.previewCovers?.length || 0) && (
                                      <div className="w-7 h-10 rounded bg-[#00ff00]/10 flex items-center justify-center flex-shrink-0">
                                        <span className="text-[8px] font-mono text-[#00ff00]">+{itemCount - (stack.previewCovers?.length || 0)}</span>
                                      </div>
                                    )}
                                  </div>
                                )}
                                {/* Stats row */}
                                <div className="flex items-center gap-2 mt-1.5 flex-wrap">
                                  <Small className="text-[#00ff00] font-mono text-[10px]">
                                    {isUnlocked ? `${itemCount} items ∞` : `${itemCount}/${maxItems}`}
                                  </Small>
                                  <Small className="text-gray-500 font-mono text-[10px]">
                                    ▲ {stack.upvotes || 0}
                                  </Small>
                                </div>

                                {/* Progress bar - only for non-unlocked stacks */}
                                {!isUnlocked && (
                                  <div className="mt-2">
                                    <div className="h-1.5 bg-[#1a1a1a] rounded-full overflow-hidden">
                                      <div
                                        className={`h-full ${progressColor} transition-all duration-300`}
                                        style={{ width: `${progressPercent}%` }}
                                      />
                                    </div>
                                    <div className="flex justify-between mt-1">
                                      <Small className={`font-mono text-[9px] ${progressTextColor}`}>
                                        {isFull ? "Full" : isNearLimit ? `${maxItems - itemCount} slots left` : ""}
                                      </Small>
                                      {isFull && (
                                        <Small className="font-mono text-[9px] text-[#00ff00]">
                                          Unlock for $5
                                        </Small>
                                      )}
                                    </div>
                                  </div>
                                )}
                              </div>
                              {/* Delete button */}
                              <button
                                type="button"
                                onClick={(e) => {
                                  e.stopPropagation();
                                  e.preventDefault();
                                  setStackToDelete(stack.id);
                                }}
                                className="relative z-10 w-8 h-8 rounded-lg bg-red-500/10 text-red-400 hover:bg-red-500/20 flex items-center justify-center text-sm shrink-0 self-start"
                                title="Delete stack"
                              >
                                <CloseIcon size={14} />
                              </button>
                            </div>
                          </CardContent>
                        </Card>
                      )}
                    </div>
                  );
                })
              )}

            </div>
          )}

          {/* My Grids sub-tab content */}
          {profileSubTab === "grids" && (
            <div className="space-y-4">
              {/* Navigate to Grids Tab Button */}
              <button
                onClick={() => {
                  window.dispatchEvent(new CustomEvent("navigate-to-tab", { detail: "grids" }));
                }}
                className="w-full py-3 px-4 bg-[#00ff00]/10 border-2 border-dashed border-[#00ff00]/40 rounded-xl text-[#00ff00] font-mono hover:bg-[#00ff00]/20 hover:border-[#00ff00]/60 transition-all flex items-center justify-center gap-2"
              >
                <GridIcon size={18} />
                <span>Create New Grid</span>
              </button>

              {/* Grid List */}
              {userGrids.length === 0 ? (
                <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
                  <CardContent className="p-6 text-center">
                    <div className="w-14 h-14 mx-auto mb-3 rounded-full bg-[#00ff00]/10 flex items-center justify-center border-2 border-dashed border-[#00ff00]/30">
                      <GridIcon size={24} className="text-[#00ff00]/60" />
                    </div>
                    <P className="text-[#00ff00] font-mono">No grids yet</P>
                    <Small className="text-gray-500 font-mono">
                      Create your first grid to curate visual media!
                    </Small>
                  </CardContent>
                </Card>
              ) : (
                userGrids.map((grid) => {
                  const cellCount = grid.cellCount || 0;
                  const gridSize = grid.size || 3;
                  const totalCells = gridSize * gridSize;
                  const progressPercent = totalCells > 0 ? (cellCount / totalCells) * 100 : 0;

                  return (
                    <Card
                      key={grid.id}
                      className="bg-[#0a0a0a] border-2 border-[#00ff00]/30 hover:border-[#00ff00] hover:shadow-[0_0_15px_rgba(0,255,0,0.3)] transition-all cursor-pointer"
                      onClick={() => {
                        // Navigate to grid in Grids tab
                        window.dispatchEvent(new CustomEvent("navigate-to-grid", { detail: grid }));
                      }}
                    >
                      <CardContent className="p-4">
                        <div className="flex gap-3">
                          {/* Grid preview */}
                          <GridPreviewThumb grid={grid} />
                          <div className="flex-1 min-w-0">
                            {/* Title with visibility badge */}
                            <div className="flex items-center gap-2">
                              <P className="font-medium truncate text-white font-mono">{grid.name}</P>
                              {grid.visibility === "hidden" && (
                                <span className="px-1.5 py-0.5 text-[9px] bg-gray-500/20 text-gray-400 rounded font-mono shrink-0">
                                  Hidden
                                </span>
                              )}
                            </div>
                            {/* Stats row */}
                            <div className="flex items-center gap-2 mt-1.5 flex-wrap">
                              <Small className="text-[#00ff00] font-mono text-[10px]">
                                {gridSize}×{gridSize} • {cellCount}/{totalCells} filled
                              </Small>
                              {grid.upvoteCount > 0 && (
                                <Small className="text-gray-400 font-mono text-[10px]">
                                  ▲{grid.upvoteCount}
                                </Small>
                              )}
                            </div>
                            {/* Progress bar */}
                            <div className="mt-2 h-1 bg-[#1a1a1a] rounded-full overflow-hidden">
                              <div
                                className="h-full bg-[#00ff00] transition-all"
                                style={{ width: `${progressPercent}%` }}
                              />
                            </div>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  );
                })
              )}
            </div>
          )}

          {/* Hidden Items Tab */}
          {profileSubTab === "hidden" && (
            <div className="space-y-4">
              {/* Info card */}
              <Card className="bg-gray-800/30 border border-gray-600/30">
                <CardContent className="p-3">
                  <Small className="text-gray-400 font-mono text-[11px] flex items-start gap-2">
                    <EyeOffIcon size={14} className="shrink-0 mt-0.5" />
                    <span>Hidden items are removed from the public feed but still exist on Net Protocol. You can unhide them anytime to restore them to the feed.</span>
                  </Small>
                </CardContent>
              </Card>

              {/* Loading state */}
              {isLoadingHidden && (
                <div className="flex items-center justify-center py-8">
                  <div className="text-center">
                    <SearchIcon size={28} className="text-gray-500 animate-pulse mb-2" />
                    <Small className="text-gray-500 font-mono">Loading hidden items...</Small>
                  </div>
                </div>
              )}

              {/* Empty state */}
              {!isLoadingHidden && hiddenEntries.length === 0 && (
                <Card className="bg-[#0a0a0a] border-2 border-gray-600/30">
                  <CardContent className="p-8 text-center">
                    <div className="w-16 h-16 mx-auto mb-3 rounded-full bg-gray-600/10 flex items-center justify-center border-2 border-dashed border-gray-600/30">
                      <EyeIcon size={28} className="text-gray-500" />
                    </div>
                    <P className="text-gray-400 font-mono">No hidden items</P>
                    <Small className="text-gray-500 font-mono">
                      Items you hide from the feed will appear here
                    </Small>
                  </CardContent>
                </Card>
              )}

              {/* Hidden items list */}
              {!isLoadingHidden && hiddenEntries.map((entry) => {
                const entryCategories = (Array.isArray(entry.categories) ? entry.categories : [])
                  .map((catId) => categories.find((c) => c.id === catId))
                  .filter(Boolean);
                return (
                  <Card
                    key={entry.contentKey}
                    className="bg-[#0a0a0a] border-2 border-gray-600/30 hover:border-gray-500/50 transition-all"
                  >
                    <CardContent className="p-4">
                      <div className="flex gap-3">
                        {/* Cover art */}
                        <div className="w-16 h-22 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded flex items-center justify-center border border-gray-600/20 overflow-hidden shrink-0 opacity-60">
                          {(entry.coverUrl || entry.cdnUrl) ? (
                            <img src={getEffectiveCoverUrl(entry)} alt={entry.title || 'Book cover'} className="w-full h-full object-cover" />
                          ) : (
                            <BookmarkIcon size={24} className="text-[#00ff00]/50" />
                          )}
                        </div>
                        <div className="flex-1 min-w-0">
                          <P className="font-medium truncate text-gray-300 font-mono">{entry.title || 'Untitled'}</P>
                          <Small className="text-gray-500 font-mono">{entry.author || 'Unknown Author'}</Small>
                          <Small className="text-gray-600 block font-mono">
                            {formatBytes(entry.fileSize || 0)} • {entry.storageType || 'unknown'} storage
                          </Small>
                          {/* Hidden date */}
                          {entry.hiddenAt && (
                            <Small className="text-gray-600 block font-mono">
                              Hidden {new Date(entry.hiddenAt).toLocaleDateString()}
                            </Small>
                          )}
                          {/* Category tags */}
                          <div className="flex flex-wrap gap-1 mt-2">
                            {entryCategories.map((cat) => (
                              <span
                                key={cat?.id}
                                className="px-1.5 py-0.5 rounded text-[10px] bg-gray-700/30 text-gray-500 font-mono"
                              >
                                {cat?.emoji} {cat?.label}
                              </span>
                            ))}
                          </div>
                        </div>
                      </div>

                      {/* Unhide button */}
                      <div className="mt-3 pt-3 border-t border-gray-700/30">
                        <button
                          onClick={() => handleUnhide(entry.contentKey)}
                          disabled={isUnhiding === entry.contentKey}
                          className="w-full py-2 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] text-xs font-mono hover:bg-[#00ff00]/20 disabled:opacity-50 disabled:cursor-not-allowed transition-all flex items-center justify-center gap-2"
                        >
                          {isUnhiding === entry.contentKey ? (
                            <>
                              <LoadingIcon size={14} className="animate-spin" />
                              <span>Unhiding...</span>
                            </>
                          ) : (
                            <>
                              <EyeIcon size={14} />
                              <span>Restore to Feed</span>
                            </>
                          )}
                        </button>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          )}

          {/* Verify & Cleanup Tab */}
          {profileSubTab === "verify" && (
            <div className="space-y-4">
              {/* Info card */}
              <Card className="bg-orange-500/10 border border-orange-500/30">
                <CardContent className="p-3">
                  <Small className="text-orange-300 font-mono text-[11px] flex items-start gap-2">
                    <SearchIcon size={14} className="shrink-0 mt-0.5" />
                    <span>Verify your uploads exist on Net Protocol. Hide broken entries that failed to upload properly (you can restore them later from the Hidden tab).</span>
                  </Small>
                </CardContent>
              </Card>

              {/* Scan button */}
              <button
                onClick={handleVerifyUploads}
                disabled={isVerifying || myUploads.length === 0}
                className={`w-full py-3 px-4 rounded-xl font-mono transition-all flex items-center justify-center gap-2 ${
                  isVerifying
                    ? "bg-orange-500/20 border border-orange-500/40 text-orange-400 animate-pulse"
                    : myUploads.length === 0
                    ? "bg-gray-800 border border-gray-700 text-gray-500 cursor-not-allowed"
                    : "bg-orange-500/10 border-2 border-dashed border-orange-500/40 text-orange-400 hover:bg-orange-500/20 hover:border-orange-500/60"
                }`}
              >
                {isVerifying ? (
                  <>
                    <LoadingIcon size={16} className="animate-spin" />
                    <span>Scanning {myUploads.length} uploads...</span>
                  </>
                ) : (
                  <>
                    <SearchIcon size={16} />
                    <span>Scan My Uploads ({myUploads.length})</span>
                  </>
                )}
              </button>

              {/* Results */}
              {verifyResults && (
                <div className="space-y-3">
                  {/* Summary */}
                  <Card className="bg-[#0a0a0a] border border-[#00ff00]/30">
                    <CardContent className="p-3">
                      <div className="grid grid-cols-4 gap-2 text-center">
                        <div>
                          <P className="text-[#00ff00] font-mono font-bold">{verifyResults.filter(r => r.status === "verified").length}</P>
                          <Small className="text-gray-500 font-mono text-[9px]">Verified</Small>
                        </div>
                        <div>
                          <P className="text-red-400 font-mono font-bold">{verifyResults.filter(r => r.status === "broken").length}</P>
                          <Small className="text-gray-500 font-mono text-[9px]">Broken</Small>
                        </div>
                        <div>
                          <P className="text-blue-400 font-mono font-bold">{verifyResults.filter(r => r.status === "external").length}</P>
                          <Small className="text-gray-500 font-mono text-[9px]">External</Small>
                        </div>
                        <div>
                          <P className="text-gray-400 font-mono font-bold">{verifyResults.filter(r => r.status === "invalid").length}</P>
                          <Small className="text-gray-500 font-mono text-[9px]">Invalid</Small>
                        </div>
                      </div>
                    </CardContent>
                  </Card>

                  {/* Broken entries list */}
                  {verifyResults.filter(r => r.status === "broken").length > 0 && (
                    <>
                      <P className="text-red-400 font-mono text-sm flex items-center gap-1"><WarningIcon size={14} /> Broken Entries</P>
                      <Small className="text-gray-500 font-mono text-[10px] block -mt-2">
                        These items are in the library but the content is not on Net Protocol. You can hide them to clean up your library.
                      </Small>
                      {verifyResults.filter(r => r.status === "broken").map((result) => (
                        <Card key={result.contentKey} className="bg-[#0a0a0a] border border-red-500/30">
                          <CardContent className="p-3">
                            <div className="flex items-start gap-3">
                              <div className="w-10 h-10 rounded-lg bg-red-500/20 flex items-center justify-center shrink-0">
                                <CloseIcon size={18} className="text-red-400" />
                              </div>
                              <div className="flex-1 min-w-0">
                                <P className="text-white font-mono text-sm truncate">{result.title || "Untitled"}</P>
                                <Small className="text-red-400/70 font-mono text-[10px] block">{result.error || "Content not on chain"}</Small>
                                <code className="text-gray-600 font-mono text-[8px] block truncate mt-1">{result.contentKey.slice(0, 20)}...</code>
                              </div>
                              <button
                                onClick={() => handleHideBroken(result.contentKey, result.operator)}
                                disabled={isRemovingBroken === result.contentKey}
                                className="shrink-0 px-3 py-1.5 rounded-lg bg-gray-600/30 text-gray-300 text-[10px] font-mono hover:bg-gray-600/50 disabled:opacity-50 transition-colors"
                              >
                                {isRemovingBroken === result.contentKey ? "..." : <><EyeOffIcon size={12} className="inline mr-1" />Hide</>}
                              </button>
                            </div>
                          </CardContent>
                        </Card>
                      ))}
                    </>
                  )}

                  {/* Verified entries list (collapsed by default) */}
                  {verifyResults.filter(r => r.status === "verified").length > 0 && (
                    <>
                      <details className="group">
                        <summary className="cursor-pointer flex items-center gap-2 text-[#00ff00] font-mono text-sm">
                          <span className="flex items-center gap-1"><CheckIcon size={14} /> Verified ({verifyResults.filter(r => r.status === "verified").length})</span>
                          <span className="text-gray-500 text-[10px] group-open:hidden">Click to expand</span>
                        </summary>
                        <div className="mt-2 space-y-2">
                          {verifyResults.filter(r => r.status === "verified").map((result) => (
                            <div key={result.contentKey} className="flex items-center gap-2 py-1 px-2 rounded bg-[#00ff00]/5 border border-[#00ff00]/20">
                              <CheckIcon size={12} className="text-[#00ff00]" />
                              <Small className="text-gray-300 font-mono truncate">{result.title || "Untitled"}</Small>
                            </div>
                          ))}
                        </div>
                      </details>
                    </>
                  )}

                  {/* External entries (CDN imports) */}
                  {verifyResults.filter(r => r.status === "external").length > 0 && (
                    <details className="group">
                      <summary className="cursor-pointer flex items-center gap-2 text-blue-400 font-mono text-sm">
                        <span className="flex items-center gap-1"><LinkIcon size={14} /> External Links ({verifyResults.filter(r => r.status === "external").length})</span>
                        <span className="text-gray-500 text-[10px] group-open:hidden">Click to expand</span>
                      </summary>
                      <div className="mt-2 space-y-2">
                        <Small className="text-gray-500 font-mono text-[10px] block">
                          CDN imports point to external URLs, not Net Protocol storage.
                        </Small>
                        {verifyResults.filter(r => r.status === "external").map((result) => (
                          <div key={result.contentKey} className="flex items-center gap-2 py-1 px-2 rounded bg-blue-500/5 border border-blue-500/20">
                            <LinkIcon size={12} className="text-blue-400" />
                            <Small className="text-gray-300 font-mono truncate">{result.title || "Untitled"}</Small>
                          </div>
                        ))}
                      </div>
                    </details>
                  )}

                  {/* All good message */}
                  {verifyResults.filter(r => r.status === "broken").length === 0 && (
                    <Card className="bg-[#00ff00]/5 border border-[#00ff00]/30">
                      <CardContent className="p-4 text-center">
                        <PartyIcon size={32} className="text-[#00ff00] mx-auto mb-2" />
                        <P className="text-[#00ff00] font-mono">All uploads verified!</P>
                        <Small className="text-gray-500 font-mono">No broken entries found.</Small>
                      </CardContent>
                    </Card>
                  )}
                </div>
              )}

              {/* Empty state */}
              {!verifyResults && myUploads.length === 0 && (
                <Card className="bg-[#0a0a0a] border-2 border-orange-500/30">
                  <CardContent className="p-8 text-center">
                    <div className="w-16 h-16 mx-auto mb-3 rounded-full bg-orange-500/10 flex items-center justify-center border-2 border-dashed border-orange-500/30">
                      <SearchIcon size={28} className="text-orange-400/60" />
                    </div>
                    <P className="text-orange-400 font-mono">No uploads to verify</P>
                    <Small className="text-gray-500 font-mono">
                      Upload some content first, then scan here to verify it exists on Net Protocol.
                    </Small>
                  </CardContent>
                </Card>
              )}
            </div>
          )}
        </>
      )}

      {/* Link to Net Modal */}
      {address && (
        <LinkToNetModal
          isOpen={showLinkToNetModal}
          onClose={() => setShowLinkToNetModal(false)}
          address={address}
          fid={userProfile?.fid} // Pass FID for cross-platform sync
          existingLink={netLink}
          onSave={(url, label) => {
            updateNetLink(url, label);
          }}
        />
      )}

      {/* Link Farcaster Modal (for Base App members to link their FC account) */}
      <LinkFarcasterModal
        isOpen={showLinkFarcasterModal}
        onClose={() => setShowLinkFarcasterModal(false)}
        onSuccess={() => {
          refreshMembership();
          setShowLinkFarcasterModal(false);
        }}
      />

      {/* Link Base Modal (for Farcaster members to link their Base wallet via SIWE) */}
      <LinkBaseModal
        isOpen={showLinkBaseModal}
        onClose={() => setShowLinkBaseModal(false)}
        onSuccess={() => {
          refreshMembership();
          setShowLinkBaseModal(false);
        }}
      />

      {/* Claim Membership Modal (for existing FC members to claim on Base App) */}
      <LinkFarcasterModal
        isOpen={showClaimMembershipModal}
        onClose={() => setShowClaimMembershipModal(false)}
        claimExistingMembership={true}
        onSuccess={() => {
          refreshMembership();
          setShowClaimMembershipModal(false);
        }}
      />

      {/* Cover Art Edit Modal */}
      {editingCover && (
        <CoverArtModal
          isOpen={!!editingCover}
          onClose={() => setEditingCover(null)}
          contentKey={editingCover.contentKey}
          operator={editingCover.operator}
          currentCoverUrl={editingCover.coverUrl}
          title={editingCover.title}
          onUpdate={() => {
            refreshDiscovery(); // Refreshes shared context - all components see update
            setEditingCover(null);
          }}
        />
      )}

      {/* Edit Item Details Modal */}
      {editingItem && (
        <EditItemModal
          isOpen={!!editingItem}
          onClose={() => setEditingItem(null)}
          entry={editingItem}
          categories={categories}
          onUpdate={() => {
            refreshDiscovery(); // Refreshes shared context - all components see update
            setEditingItem(null);
          }}
        />
      )}

      {/* Unlink Farcaster Confirmation Modal */}
      {showUnlinkConfirm && (
        <div
          className="fixed inset-0 bg-black/95 z-[9999] flex items-center justify-center p-4"
          onClick={() => setShowUnlinkConfirm(false)}
        >
          <div
            className="bg-[#0a0a0a] border border-red-500/30 rounded-xl max-w-sm w-full overflow-hidden"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="px-4 py-3 border-b border-red-500/20 bg-red-500/5">
              <div className="flex items-center gap-2">
                <WarningIcon size={20} className="text-red-400" />
                <P className="text-red-400 font-mono font-medium">Unlink Farcaster</P>
              </div>
            </div>
            <div className="p-4 space-y-3">
              <P className="text-gray-300 font-mono text-sm">
                Are you sure you want to unlink your Farcaster account from this membership?
              </P>
              <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/20">
                <Small className="text-red-400/80 font-mono block">
                  Use this if you&apos;ve sold or transferred your FID to someone else.
                  You can always link a new Farcaster account later.
                </Small>
              </div>
              {member?.fid && (
                <div className="p-2 rounded bg-purple-500/10 border border-purple-500/20">
                  <Small className="text-purple-400 font-mono">
                    Currently linked: @{member.farcasterUsername || member.username || `FID ${member.fid}`}
                  </Small>
                </div>
              )}
              <div className="flex gap-2 pt-2">
                <button
                  onClick={() => setShowUnlinkConfirm(false)}
                  className="flex-1 py-2 rounded-lg bg-[#1a1a1a] text-gray-400 font-mono hover:bg-[#222] transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handleUnlinkFarcaster}
                  disabled={isUnlinkingFid}
                  className="flex-1 py-2 rounded-lg bg-red-500/20 text-red-400 font-mono font-bold hover:bg-red-500/30 disabled:opacity-50 transition-colors"
                >
                  {isUnlinkingFid ? "Unlinking..." : "Unlink"}
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Create Stack Modal */}
      <CreateStackModal
        isOpen={showCreateStackModal}
        onClose={() => setShowCreateStackModal(false)}
        onSuccess={(_stack) => {
          refreshStacks();
          setShowCreateStackModal(false);
        }}
        createStack={createStack}
      />

      {/* Add to Stack Modal for uploads */}
      {uploadToAddToStack && (
        <AddToStackModal
          isOpen={showAddToStackModal}
          onClose={() => {
            setShowAddToStackModal(false);
            setUploadToAddToStack(null);
          }}
          book={{
            id: uploadToAddToStack.contentKey,
            title: uploadToAddToStack.title,
            author: uploadToAddToStack.author,
            categories: uploadToAddToStack.categories,
            contentKey: uploadToAddToStack.contentKey,
            coverUrl: uploadToAddToStack.coverUrl,
            uploader: {
              username: userProfile?.username || "unknown",
              pfpUrl: userProfile?.pfpUrl || "",
              address: uploadToAddToStack.operator || "",
            },
            uploadDate: new Date(uploadToAddToStack.uploadedAt).toLocaleDateString(),
            size: formatBytes(uploadToAddToStack.fileSize),
          }}
          onSuccess={() => {
            refreshStacks();
            setShowAddToStackModal(false);
            setUploadToAddToStack(null);
          }}
          onCreateStack={() => {
            setShowAddToStackModal(false);
            setShowCreateStackModal(true);
          }}
        />
      )}

      {/* Web Profile Editor Modal */}
      {appMode === "web" && isMember && member && member.wid && (
        <WebProfileEditor
          isOpen={showWebProfileEditor}
          onClose={() => setShowWebProfileEditor(false)}
          address={address || ""}
          memberId={member.memberId}
          wid={member.wid}
          currentUsername={userProfile?.customUsername}
          currentPfpUrl={userProfile?.customPfpUrl}
          onSuccess={() => {
            refreshMembership();
            setShowWebProfileEditor(false);
          }}
        />
      )}
    </div>
  );
}

// Grid Preview Thumbnail - shows tiled images from previewCells
function GridPreviewThumb({ grid }: { grid: GridWithStats }) {
  const previewSize = Math.min(grid.size || 3, 3);
  const cells = grid.previewCells || [];

  // Create a map of filled cells with their data
  const filledCells = new Map<string, GridCell>();
  cells.forEach((cell) => {
    if (cell && cell.row < previewSize && cell.col < previewSize) {
      filledCells.set(`${cell.row}-${cell.col}`, cell);
    }
  });

  return (
    <div
      className="w-12 h-12 rounded-lg bg-black border border-[#00ff00]/20 p-0.5 grid gap-0.5 shrink-0 overflow-hidden"
      style={{
        gridTemplateColumns: `repeat(${previewSize}, 1fr)`,
        gridTemplateRows: `repeat(${previewSize}, 1fr)`,
      }}
    >
      {Array.from({ length: previewSize * previewSize }).map((_, i) => {
        const row = Math.floor(i / previewSize);
        const col = i % previewSize;
        const cell = filledCells.get(`${row}-${col}`);

        if (cell) {
          const imageUrl = getEffectiveCoverUrl(cell);
          return (
            <div key={i} className="rounded-sm overflow-hidden bg-[#1a1a1a]">
              {imageUrl ? (
                <img
                  src={imageUrl}
                  alt=""
                  className="w-full h-full object-cover"
                  loading="lazy"
                  onError={(e) => {
                    e.currentTarget.style.display = 'none';
                    if (e.currentTarget.parentElement) {
                      e.currentTarget.parentElement.classList.add('bg-[#00ff00]/30');
                    }
                  }}
                />
              ) : (
                <div className="w-full h-full bg-[#00ff00]/30" />
              )}
            </div>
          );
        }

        return (
          <div
            key={i}
            className="rounded-sm bg-[#1a1a1a]"
          />
        );
      })}
    </div>
  );
}
src/features/app/components/pdf-reader.tsx
"use client";

import { useState, useEffect, useRef, useCallback } from "react";
import { useUpvote } from "@/hooks/use-upvotes";
import { UpvoteModal } from "./upvote-modal";
import { XCircleIcon, ShareIcon } from "@/components/icons/net-library-icons";

// Voice options for TTS
const VOICE_OPTIONS = [
  { id: "female" as const, label: "Female", emoji: "👩" },
  { id: "male" as const, label: "Male", emoji: "👨" },
];
type VoiceGender = "female" | "male";

// Bookmark and reading progress types
interface Bookmark {
  page: number;
  label?: string;
  createdAt: number;
}

interface ReadingProgress {
  currentPage: number;
  lastRead: number;
  bookmarks: Bookmark[];
}

// LocalStorage helpers for reading progress
const getStorageKey = (pdfUrl: string) => `netlib_reading_${btoa(pdfUrl).slice(0, 32)}`;

const loadReadingProgress = (pdfUrl: string): ReadingProgress | null => {
  if (typeof window === "undefined") return null;
  try {
    const data = localStorage.getItem(getStorageKey(pdfUrl));
    return data ? JSON.parse(data) : null;
  } catch {
    return null;
  }
};

const saveReadingProgress = (pdfUrl: string, progress: ReadingProgress) => {
  if (typeof window === "undefined") return;
  try {
    localStorage.setItem(getStorageKey(pdfUrl), JSON.stringify(progress));
  } catch {
    // localStorage full or unavailable
  }
};

interface PdfReaderProps {
  pdfUrl: string;
  title: string;
  author: string;
  contentKey?: string;
  operatorAddress?: string;
  upvoteCount?: number;
  onBack: () => void;
  onShare: () => void;
  onUpvoteSuccess?: () => void;
}

export function PdfReader({
  pdfUrl,
  title,
  author,
  contentKey,
  operatorAddress,
  upvoteCount = 0,
  onBack,
  onShare,
  onUpvoteSuccess,
}: PdfReaderProps) {
  const [numPages, setNumPages] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [localUpvotes, setLocalUpvotes] = useState(0);
  const [showUpvoteModal, setShowUpvoteModal] = useState(false);
  const { upvote, isUpvoting, isConfirmed } = useUpvote();

  // View mode - "canvas" for PDF.js rendering, "native" for browser iframe
  const [viewMode, setViewMode] = useState<"canvas" | "native">("canvas");

  // Listen mode state (TTS)
  const [showAudioPlayer, setShowAudioPlayer] = useState(false);
  const [isPlaying, setIsPlaying] = useState(false);
  const [selectedVoice, setSelectedVoice] = useState<VoiceGender>("female");
  const [speechRate, setSpeechRate] = useState(1);
  const [pageText, setPageText] = useState<string[]>([]); // Text content of current page as sentences
  const [currentSentence, setCurrentSentence] = useState(0);

  // Pan/zoom state for touch gestures
  const [panOffset, setPanOffset] = useState({ x: 0, y: 0 });
  const [isPanning, setIsPanning] = useState(false);
  const lastTouchRef = useRef<{ x: number; y: number } | null>(null);
  const lastPinchDistanceRef = useRef<number | null>(null);

  // Annotation layer ref for clickable links
  const annotationLayerRef = useRef<HTMLDivElement>(null);

  // Bookmark and reading progress state
  const [bookmarks, setBookmarks] = useState<Bookmark[]>([]);
  const [showBookmarksPanel, setShowBookmarksPanel] = useState(false);
  const [showResumePrompt, setShowResumePrompt] = useState(false);
  const [savedPage, setSavedPage] = useState<number | null>(null);
  const hasLoadedProgress = useRef(false);

  const handleUpvote = async (count: number) => {
    if (!contentKey || !operatorAddress) return;
    const success = await upvote(contentKey, operatorAddress, count);
    if (success) {
      setLocalUpvotes((prev) => prev + count);
      setShowUpvoteModal(false);
    }
  };

  // When transaction is confirmed, refresh the counts from the blockchain
  useEffect(() => {
    if (isConfirmed) {
      const timer = setTimeout(() => {
        onUpvoteSuccess?.();
      }, 2000);
      return () => clearTimeout(timer);
    }
  }, [isConfirmed, onUpvoteSuccess]);

  const displayUpvotes = upvoteCount + localUpvotes;
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [scale, setScale] = useState(1.0);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const pdfDocRef = useRef<any>(null);
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const pdfjsRef = useRef<any>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const textLayerRef = useRef<HTMLDivElement>(null);

  // ===== TTS (Listen) Functions =====
  const getVoice = useCallback(() => {
    const voices = window.speechSynthesis?.getVoices() || [];
    const isFemale = selectedVoice === "female";
    const femaleHints = ["female", "samantha", "karen", "victoria", "kate", "susan", "zira", "hazel", "fiona", "siri", "ava", "allison"];
    const maleHints = ["male", "david", "daniel", "james", "george", "guy", "mark", "alex", "fred", "tom"];
    const genderHints = isFemale ? femaleHints : maleHints;
    const genderMatch = voices.find((v) =>
      genderHints.some((hint) => v.name.toLowerCase().includes(hint))
    );
    return genderMatch || voices[0] || null;
  }, [selectedVoice]);

  const speakSentence = useCallback((index: number) => {
    if (index >= pageText.length) {
      setIsPlaying(false);
      setCurrentSentence(0);
      return;
    }

    const utterance = new SpeechSynthesisUtterance(pageText[index]);
    utterance.rate = speechRate;
    const voice = getVoice();
    if (voice) utterance.voice = voice;

    utterance.onend = () => {
      const nextIndex = index + 1;
      setCurrentSentence(nextIndex);
      if (nextIndex < pageText.length) {
        speakSentence(nextIndex);
      } else {
        setIsPlaying(false);
      }
    };

    window.speechSynthesis?.speak(utterance);
    setIsPlaying(true);
    setCurrentSentence(index);
  }, [pageText, speechRate, getVoice]);

  const togglePlayback = useCallback(() => {
    if (isPlaying) {
      window.speechSynthesis?.cancel();
      setIsPlaying(false);
    } else {
      speakSentence(currentSentence);
    }
  }, [isPlaying, currentSentence, speakSentence]);

  const changeSpeed = () => {
    const speeds = [0.75, 1, 1.25, 1.5, 2];
    const currentIndex = speeds.indexOf(speechRate);
    setSpeechRate(speeds[(currentIndex + 1) % speeds.length]);
  };

  // Stop TTS when page changes
  useEffect(() => {
    window.speechSynthesis?.cancel();
    setIsPlaying(false);
    setCurrentSentence(0);
  }, [currentPage]);

  // ===== Touch Gesture Handlers for Pan/Zoom =====
  const handleTouchStart = useCallback((e: React.TouchEvent) => {
    if (scale <= 1) return; // Only enable pan when zoomed in

    if (e.touches.length === 1) {
      // Single finger - start pan
      lastTouchRef.current = { x: e.touches[0].clientX, y: e.touches[0].clientY };
      setIsPanning(true);
    } else if (e.touches.length === 2) {
      // Two fingers - start pinch zoom
      const dx = e.touches[0].clientX - e.touches[1].clientX;
      const dy = e.touches[0].clientY - e.touches[1].clientY;
      lastPinchDistanceRef.current = Math.sqrt(dx * dx + dy * dy);
    }
  }, [scale]);

  const handleTouchMove = useCallback((e: React.TouchEvent) => {
    if (e.touches.length === 1 && isPanning && lastTouchRef.current) {
      // Single finger pan
      const dx = e.touches[0].clientX - lastTouchRef.current.x;
      const dy = e.touches[0].clientY - lastTouchRef.current.y;
      setPanOffset(prev => ({ x: prev.x + dx, y: prev.y + dy }));
      lastTouchRef.current = { x: e.touches[0].clientX, y: e.touches[0].clientY };
    } else if (e.touches.length === 2 && lastPinchDistanceRef.current !== null) {
      // Pinch zoom
      const dx = e.touches[0].clientX - e.touches[1].clientX;
      const dy = e.touches[0].clientY - e.touches[1].clientY;
      const distance = Math.sqrt(dx * dx + dy * dy);
      const delta = (distance - lastPinchDistanceRef.current) / 200;
      setScale(prev => Math.min(3, Math.max(0.5, prev + delta)));
      lastPinchDistanceRef.current = distance;
    }
  }, [isPanning]);

  const handleTouchEnd = useCallback(() => {
    setIsPanning(false);
    lastTouchRef.current = null;
    lastPinchDistanceRef.current = null;
  }, []);

  // Reset pan when scale changes to 1 or below
  useEffect(() => {
    if (scale <= 1) {
      setPanOffset({ x: 0, y: 0 });
    }
  }, [scale]);

  // Auto-save reading progress when page changes
  useEffect(() => {
    if (currentPage > 0 && numPages > 0) {
      saveReadingProgress(pdfUrl, {
        currentPage,
        lastRead: Date.now(),
        bookmarks,
      });
    }
  }, [currentPage, bookmarks, pdfUrl, numPages]);

  // Bookmark handlers
  const isCurrentPageBookmarked = bookmarks.some((b) => b.page === currentPage);

  const toggleBookmark = () => {
    if (isCurrentPageBookmarked) {
      // Remove bookmark
      setBookmarks((prev) => prev.filter((b) => b.page !== currentPage));
    } else {
      // Add bookmark
      setBookmarks((prev) => [
        ...prev,
        { page: currentPage, createdAt: Date.now() },
      ].sort((a, b) => a.page - b.page));
    }
  };

  const jumpToBookmark = (page: number) => {
    setCurrentPage(page);
    setShowBookmarksPanel(false);
  };

  const removeBookmark = (page: number) => {
    setBookmarks((prev) => prev.filter((b) => b.page !== page));
  };

  // Load PDF document
  useEffect(() => {
    let cancelled = false;

    async function loadPdf() {
      try {
        setLoading(true);
        setError(null);

        // Dynamically import pdfjs-dist only on client
        const pdfjsLib = await import("pdfjs-dist");

        // Try multiple CDN sources for the worker in case one is down/blocked
        const workerUrls = [
          `https://unpkg.com/pdfjs-dist@${pdfjsLib.version}/build/pdf.worker.min.mjs`,
          `https://cdn.jsdelivr.net/npm/pdfjs-dist@${pdfjsLib.version}/build/pdf.worker.min.mjs`,
          `https://cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.mjs`,
        ];

        // Try each worker URL until one loads successfully
        let workerLoaded = false;
        for (const workerUrl of workerUrls) {
          try {
            // Test if we can fetch the worker (catches CORS/network issues)
            const testResponse = await fetch(workerUrl, { method: "HEAD" });
            if (testResponse.ok) {
              pdfjsLib.GlobalWorkerOptions.workerSrc = workerUrl;
              workerLoaded = true;
              console.log("[PdfReader] Worker loaded from:", workerUrl);
              break;
            }
          } catch {
            console.warn("[PdfReader] Worker unavailable:", workerUrl);
          }
        }

        if (!workerLoaded) {
          // Fallback: disable worker (slower but works)
          console.warn("[PdfReader] All worker CDNs failed, using main thread fallback");
          pdfjsLib.GlobalWorkerOptions.workerSrc = "";
        }

        pdfjsRef.current = pdfjsLib;

        // Fetch PDF from our API endpoint
        const fullUrl = pdfUrl.startsWith("/") ? window.location.origin + pdfUrl : pdfUrl;
        console.log("[PdfReader] Loading PDF from:", fullUrl);

        const loadingTask = pdfjsLib.getDocument(fullUrl);
        const pdf = await loadingTask.promise;

        if (cancelled) return;

        pdfDocRef.current = pdf;
        setNumPages(pdf.numPages);

        // Load saved reading progress
        if (!hasLoadedProgress.current) {
          hasLoadedProgress.current = true;
          const progress = loadReadingProgress(pdfUrl);
          if (progress) {
            setBookmarks(progress.bookmarks || []);
            // If user was on page > 1, offer to resume
            if (progress.currentPage > 1 && progress.currentPage <= pdf.numPages) {
              setSavedPage(progress.currentPage);
              setShowResumePrompt(true);
            }
          }
        }

        setCurrentPage(1);
        setLoading(false);

        console.log("[PdfReader] Loaded PDF with", pdf.numPages, "pages");
      } catch (err) {
        if (cancelled) return;
        console.error("[PdfReader] Error loading PDF:", err);
        setError(err instanceof Error ? err.message : "Failed to load PDF");
        setLoading(false);
      }
    }

    loadPdf();

    return () => {
      cancelled = true;
    };
  }, [pdfUrl]);

  // Render current page with high-DPI support for crisp text and text layer for selection
  useEffect(() => {
    if (!pdfDocRef.current || !canvasRef.current || loading) return;

    let cancelled = false;

    async function renderPage() {
      try {
        const pdf = pdfDocRef.current!;
        const page = await pdf.getPage(currentPage);

        if (cancelled) return;

        const canvas = canvasRef.current!;
        const context = canvas.getContext("2d")!;

        // Get device pixel ratio for crisp rendering on high-DPI displays
        const pixelRatio = window.devicePixelRatio || 1;

        // Calculate scale to fit width
        const containerWidth = containerRef.current?.clientWidth || 400;
        const viewport = page.getViewport({ scale: 1 });
        const fitScale = (containerWidth - 32) / viewport.width; // 32px padding
        const actualScale = fitScale * scale;

        // Create viewport for display (used for text layer positioning)
        const displayViewport = page.getViewport({ scale: actualScale });

        // Create viewport at higher resolution for crisp canvas rendering
        const scaledViewport = page.getViewport({ scale: actualScale * pixelRatio });

        // Set canvas internal size to high-res
        canvas.height = scaledViewport.height;
        canvas.width = scaledViewport.width;

        // Scale canvas back down with CSS for display
        canvas.style.width = `${displayViewport.width}px`;
        canvas.style.height = `${displayViewport.height}px`;

        // Render at high resolution
        await page.render({
          canvasContext: context,
          viewport: scaledViewport,
        }).promise;

        // Render text layer for selection
        if (textLayerRef.current && pdfjsRef.current) {
          // Clear previous text layer
          textLayerRef.current.innerHTML = "";

          // Set text layer dimensions to match display viewport
          textLayerRef.current.style.width = `${displayViewport.width}px`;
          textLayerRef.current.style.height = `${displayViewport.height}px`;

          // Get text content
          const textContent = await page.getTextContent();

          // Render text layer using pdfjs
          const { renderTextLayer } = pdfjsRef.current;
          await renderTextLayer({
            textContentSource: textContent,
            container: textLayerRef.current,
            viewport: displayViewport,
          }).promise;

          // Extract text for TTS - combine into sentences
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          const fullText = textContent.items.map((item: any) => item.str).join(" ");
          // Split into sentences for TTS
          const sentences = fullText
            .split(/(?<=[.!?])\s+/)
            .map((s: string) => s.trim())
            .filter((s: string) => s.length > 0);
          setPageText(sentences);
        }

        // Render annotation layer for clickable links
        if (annotationLayerRef.current) {
          // Clear previous annotation layer
          annotationLayerRef.current.innerHTML = "";

          // Set annotation layer dimensions to match display viewport
          annotationLayerRef.current.style.width = `${displayViewport.width}px`;
          annotationLayerRef.current.style.height = `${displayViewport.height}px`;

          // Get annotations from the page
          const annotations = await page.getAnnotations();

          // Filter for link annotations and render them
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          for (const annotation of annotations as any[]) {
            if (annotation.subtype === "Link" && (annotation.url || annotation.dest)) {
              // Convert PDF coordinates to viewport coordinates
              // PDF coordinates: bottom-left origin, annotation.rect = [x1, y1, x2, y2]
              const rect = annotation.rect;
              const [x1, y1, x2, y2] = displayViewport.convertToViewportRectangle(rect);

              // Create clickable link element
              const linkElement = document.createElement("a");
              linkElement.className = "pdf-annotation-link";
              linkElement.style.position = "absolute";
              linkElement.style.left = `${Math.min(x1, x2)}px`;
              linkElement.style.top = `${Math.min(y1, y2)}px`;
              linkElement.style.width = `${Math.abs(x2 - x1)}px`;
              linkElement.style.height = `${Math.abs(y2 - y1)}px`;
              linkElement.style.cursor = "pointer";
              linkElement.style.borderRadius = "2px";
              linkElement.style.transition = "background-color 0.2s";

              // Determine if this is an internal link (dest) or external URL
              const isInternalLink = !annotation.url && annotation.dest;

              if (isInternalLink) {
                // Internal link - style with yellow to indicate in-document navigation
                linkElement.style.backgroundColor = "rgba(234, 179, 8, 0.05)";
                linkElement.style.border = "1px solid rgba(234, 179, 8, 0.2)";

                // Resolve the destination to get the page number
                try {
                  const dest = annotation.dest;
                  // dest can be a string (named destination) or array (explicit destination)
                  let destArray = dest;
                  if (typeof dest === "string") {
                    // Named destination - resolve it
                    destArray = await pdf.getDestination(dest);
                  }

                  if (destArray && destArray[0]) {
                    // First element is a page reference - resolve to page index
                    const pageIndex = await pdf.getPageIndex(destArray[0]);
                    const targetPage = pageIndex + 1; // Convert 0-based to 1-based

                    linkElement.title = `Go to page ${targetPage}`;
                    linkElement.onclick = (e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      setCurrentPage(targetPage);
                    };
                  }
                } catch (err) {
                  console.warn("[PdfReader] Could not resolve internal link destination:", err);
                }

                // Hover effect for internal links (yellow)
                linkElement.onmouseenter = () => {
                  linkElement.style.backgroundColor = "rgba(234, 179, 8, 0.15)";
                };
                linkElement.onmouseleave = () => {
                  linkElement.style.backgroundColor = "rgba(234, 179, 8, 0.05)";
                };
              } else if (annotation.url) {
                // External URL - style with green
                linkElement.style.backgroundColor = "rgba(0, 255, 0, 0.05)";
                linkElement.style.border = "1px solid rgba(0, 255, 0, 0.2)";
                linkElement.title = annotation.url;

                linkElement.onclick = async (e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  try {
                    // Dynamic import to avoid SSR issues
                    const sdk = (await import("@farcaster/miniapp-sdk")).default;
                    await sdk.actions.openUrl(annotation.url!);
                  } catch {
                    // Fallback for non-Farcaster environments
                    window.open(annotation.url!, "_blank");
                  }
                };

                // Hover effect for external links (green)
                linkElement.onmouseenter = () => {
                  linkElement.style.backgroundColor = "rgba(0, 255, 0, 0.15)";
                };
                linkElement.onmouseleave = () => {
                  linkElement.style.backgroundColor = "rgba(0, 255, 0, 0.05)";
                };
              }

              annotationLayerRef.current!.appendChild(linkElement);
            }
          }
        }
      } catch (err) {
        console.error("[PdfReader] Error rendering page:", err);
      }
    }

    renderPage();

    return () => {
      cancelled = true;
    };
  }, [currentPage, scale, loading]);

  const goToPage = (page: number) => {
    if (page >= 1 && page <= numPages) {
      setCurrentPage(page);
    }
  };

  if (loading) {
    return (
      <div className="h-dvh flex flex-col overflow-hidden bg-black">
        <header className="shrink-0 px-4 py-3 border-b border-[#1a1a1a] flex items-center gap-3">
          <button
            onClick={onBack}
            className="w-10 h-10 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222]"
          >
            ←
          </button>
          <div className="flex-1 min-w-0">
            <p className="text-[#00ff00] font-mono text-sm font-bold truncate">{title}</p>
            <p className="text-gray-500 font-mono text-xs truncate">{author}</p>
          </div>
        </header>
        <main className="flex-1 flex items-center justify-center">
          <div className="text-center">
            <div className="text-4xl mb-4 animate-pulse">📄</div>
            <p className="text-[#00ff00] font-mono">Loading PDF...</p>
            <p className="text-gray-500 font-mono text-xs mt-2">Fetching from onchain storage</p>
          </div>
        </main>
      </div>
    );
  }

  if (error) {
    return (
      <div className="h-dvh flex flex-col overflow-hidden bg-black">
        <header className="shrink-0 px-4 py-3 border-b border-[#1a1a1a] flex items-center gap-3">
          <button
            onClick={onBack}
            className="w-10 h-10 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222]"
          >
            ←
          </button>
          <div className="flex-1 min-w-0">
            <p className="text-[#00ff00] font-mono text-sm font-bold truncate">{title}</p>
            <p className="text-gray-500 font-mono text-xs truncate">{author}</p>
          </div>
        </header>
        <main className="flex-1 flex items-center justify-center p-6">
          <div className="text-center">
            <div className="mb-4 flex justify-center"><XCircleIcon size={40} className="text-red-400" /></div>
            <p className="text-red-400 font-mono mb-2">Failed to load PDF</p>
            <p className="text-gray-500 font-mono text-xs">{error}</p>
            <button
              onClick={onBack}
              className="mt-6 px-6 py-2 rounded-lg border border-[#00ff00] text-[#00ff00] font-mono text-sm hover:bg-[#00ff00]/10"
            >
              Go Back
            </button>
          </div>
        </main>
      </div>
    );
  }

  return (
    <div className="h-dvh flex flex-col overflow-hidden bg-black">
      {/* PDF.js text layer styles */}
      <style>{`
        .text-layer-container {
          user-select: text;
          -webkit-user-select: text;
        }
        .text-layer-container span {
          position: absolute;
          white-space: pre;
          transform-origin: 0% 0%;
          cursor: text;
          color: transparent;
          background: transparent;
        }
        .text-layer-container span::selection {
          background: rgba(0, 255, 0, 0.4);
        }
        .text-layer-container span::-moz-selection {
          background: rgba(0, 255, 0, 0.4);
        }
      `}</style>
      {/* Header */}
      <header className="shrink-0 px-4 py-3 border-b border-[#1a1a1a] flex items-center gap-2">
        <button
          onClick={onBack}
          className="w-10 h-10 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] shrink-0"
        >
          ←
        </button>
        <div className="flex-1 min-w-0">
          <p className="text-[#00ff00] font-mono text-sm font-bold truncate">{title}</p>
          <p className="text-gray-500 font-mono text-xs truncate">
            Page {currentPage} of {numPages}
          </p>
        </div>
        {/* Upvote button */}
        {contentKey && operatorAddress && (
          <button
            onClick={() => setShowUpvoteModal(true)}
            disabled={isUpvoting}
            className={`h-10 px-3 rounded-full flex items-center gap-1.5 font-mono text-xs transition-all shrink-0 ${
              isUpvoting
                ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/30"
                : isConfirmed
                ? "bg-[#00ff00]/30 text-[#00ff00] border border-[#00ff00]/50"
                : "bg-[#1a1a1a] text-[#00ff00] hover:bg-[#222] border border-[#00ff00]/30"
            }`}
          >
            <span>▲</span>
            <span>{displayUpvotes}</span>
          </button>
        )}
        {/* Listen button */}
        <button
          onClick={() => setShowAudioPlayer(!showAudioPlayer)}
          className={`h-10 px-3 rounded-full flex items-center gap-1 font-mono text-xs transition-all shrink-0 ${
            showAudioPlayer
              ? "bg-[#00ff00] text-black"
              : "bg-[#1a1a1a] text-gray-300 hover:bg-[#222] hover:text-[#00ff00]"
          }`}
        >
          🎧
        </button>
        {/* Bookmark button */}
        <button
          onClick={toggleBookmark}
          className={`h-10 px-3 rounded-full flex items-center gap-1 font-mono text-xs transition-all shrink-0 ${
            isCurrentPageBookmarked
              ? "bg-yellow-500 text-black"
              : "bg-[#1a1a1a] text-gray-300 hover:bg-[#222] hover:text-yellow-500"
          }`}
          title={isCurrentPageBookmarked ? "Remove bookmark" : "Bookmark this page"}
        >
          {isCurrentPageBookmarked ? "🔖" : "📑"}
        </button>
        {/* Bookmarks list button */}
        {bookmarks.length > 0 && (
          <button
            onClick={() => setShowBookmarksPanel(!showBookmarksPanel)}
            className={`h-10 px-3 rounded-full flex items-center gap-1 font-mono text-xs transition-all shrink-0 ${
              showBookmarksPanel
                ? "bg-yellow-500 text-black"
                : "bg-[#1a1a1a] text-gray-300 hover:bg-[#222]"
            }`}
          >
            <span className="text-yellow-500">{bookmarks.length}</span>
          </button>
        )}
        <button
          onClick={onShare}
          className="w-10 h-10 rounded-full bg-[#1a1a1a] flex items-center justify-center text-[#00ff00] hover:bg-[#222] shrink-0"
        >
          <ShareIcon size={18} />
        </button>
      </header>

      {/* Resume Reading Prompt */}
      {showResumePrompt && savedPage && (
        <div className="shrink-0 px-4 py-3 bg-[#00ff00]/10 border-b border-[#00ff00]/30 flex items-center justify-between gap-3">
          <div className="flex items-center gap-2 min-w-0">
            <span className="text-lg">📖</span>
            <p className="text-sm text-gray-300 font-mono truncate">
              Resume from page {savedPage}?
            </p>
          </div>
          <div className="flex items-center gap-2 shrink-0">
            <button
              onClick={() => {
                setCurrentPage(savedPage);
                setShowResumePrompt(false);
              }}
              className="px-3 py-1.5 rounded-lg bg-[#00ff00] text-black font-mono text-xs font-medium"
            >
              Resume
            </button>
            <button
              onClick={() => setShowResumePrompt(false)}
              className="px-3 py-1.5 rounded-lg bg-[#1a1a1a] text-gray-300 font-mono text-xs hover:bg-[#222]"
            >
              Start Over
            </button>
          </div>
        </div>
      )}

      {/* Bookmarks Panel */}
      {showBookmarksPanel && bookmarks.length > 0 && (
        <div className="shrink-0 px-4 py-3 bg-yellow-500/10 border-b border-yellow-500/30">
          <div className="flex items-center justify-between mb-2">
            <p className="text-sm text-yellow-500 font-mono font-medium">🔖 Bookmarks</p>
            <button
              onClick={() => setShowBookmarksPanel(false)}
              className="text-gray-500 hover:text-white text-xs"
            >
              ✕
            </button>
          </div>
          <div className="flex flex-wrap gap-2">
            {bookmarks.map((bookmark) => (
              <div
                key={bookmark.page}
                className="flex items-center gap-1 bg-[#1a1a1a] rounded-lg overflow-hidden"
              >
                <button
                  onClick={() => jumpToBookmark(bookmark.page)}
                  className={`px-3 py-1.5 font-mono text-xs transition-colors ${
                    bookmark.page === currentPage
                      ? "bg-yellow-500 text-black font-medium"
                      : "text-gray-300 hover:bg-[#222] hover:text-yellow-500"
                  }`}
                >
                  Page {bookmark.page}
                </button>
                <button
                  onClick={() => removeBookmark(bookmark.page)}
                  className="px-2 py-1.5 text-gray-500 hover:text-red-400 hover:bg-[#222] text-xs"
                >
                  ✕
                </button>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Audio Player Panel */}
      {showAudioPlayer && pageText.length > 0 && (
        <div className="shrink-0 px-4 py-3 bg-[#00ff00]/10 border-b border-[#00ff00]/30">
          {/* Progress bar */}
          <div className="mb-3">
            <div className="h-1.5 bg-[#1a1a1a] rounded-full overflow-hidden">
              <div
                className="h-full bg-[#00ff00] rounded-full transition-all"
                style={{ width: `${((currentSentence + 1) / pageText.length) * 100}%` }}
              />
            </div>
            <div className="flex justify-between mt-1">
              <span className="text-[10px] text-gray-500 font-mono">
                {currentSentence + 1} / {pageText.length} sentences
              </span>
              <span className="text-[10px] text-gray-500 font-mono">
                {Math.round(((currentSentence + 1) / pageText.length) * 100)}%
              </span>
            </div>
          </div>

          {/* Voice Selector */}
          <div className="flex gap-2 mb-3">
            {VOICE_OPTIONS.map((voice) => (
              <button
                key={voice.id}
                onClick={() => {
                  setSelectedVoice(voice.id);
                  if (isPlaying) {
                    window.speechSynthesis?.cancel();
                    setTimeout(() => speakSentence(currentSentence), 100);
                  }
                }}
                className={`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg transition-all font-mono ${
                  selectedVoice === voice.id
                    ? "bg-[#00ff00] text-black"
                    : "bg-[#1a1a1a] text-gray-300 hover:bg-[#222] border border-[#222]"
                }`}
              >
                <span className="text-lg">{voice.emoji}</span>
                <span className="text-sm">{voice.label}</span>
              </button>
            ))}
          </div>

          {/* Controls */}
          <div className="flex items-center justify-center gap-3">
            <button
              onClick={changeSpeed}
              className="px-2 py-1 rounded bg-[#1a1a1a] text-xs text-gray-300 hover:bg-[#222] min-w-[48px] font-mono"
            >
              {speechRate}x
            </button>
            <button
              onClick={() => {
                window.speechSynthesis?.cancel();
                const prev = Math.max(0, currentSentence - 1);
                setCurrentSentence(prev);
                if (isPlaying) speakSentence(prev);
              }}
              disabled={currentSentence === 0}
              className="w-10 h-10 rounded-full bg-[#1a1a1a] text-white flex items-center justify-center hover:bg-[#222] disabled:opacity-30"
            >
              ⏮
            </button>
            <button
              onClick={togglePlayback}
              className={`w-14 h-14 rounded-full flex items-center justify-center text-xl transition-all ${
                isPlaying
                  ? "bg-[#00ff00] text-black shadow-lg shadow-[#00ff00]/30"
                  : "bg-white text-black hover:scale-105"
              }`}
            >
              {isPlaying ? "⏸" : "▶"}
            </button>
            <button
              onClick={() => {
                window.speechSynthesis?.cancel();
                const next = Math.min(pageText.length - 1, currentSentence + 1);
                setCurrentSentence(next);
                if (isPlaying) speakSentence(next);
              }}
              disabled={currentSentence >= pageText.length - 1}
              className="w-10 h-10 rounded-full bg-[#1a1a1a] text-white flex items-center justify-center hover:bg-[#222] disabled:opacity-30"
            >
              ⏭
            </button>
            {isPlaying && (
              <div className="flex items-center gap-1 ml-2">
                <div className="w-1 h-3 bg-[#00ff00] rounded-full animate-pulse" />
                <div className="w-1 h-4 bg-[#00ff00] rounded-full animate-pulse" style={{ animationDelay: "0.1s" }} />
                <div className="w-1 h-2 bg-[#00ff00] rounded-full animate-pulse" style={{ animationDelay: "0.2s" }} />
              </div>
            )}
          </div>
        </div>
      )}

      {/* View Mode Toggle */}
      <div className="shrink-0 px-4 py-2 border-b border-[#1a1a1a] flex items-center justify-center gap-2">
        <button
          onClick={() => setViewMode("canvas")}
          className={`px-3 py-1.5 rounded-lg font-mono text-xs transition-all ${
            viewMode === "canvas"
              ? "bg-[#00ff00] text-black font-medium"
              : "bg-[#1a1a1a] text-gray-400 hover:text-white hover:bg-[#222]"
          }`}
        >
          📖 Reader
        </button>
        <button
          onClick={() => setViewMode("native")}
          className={`px-3 py-1.5 rounded-lg font-mono text-xs transition-all ${
            viewMode === "native"
              ? "bg-[#00ff00] text-black font-medium"
              : "bg-[#1a1a1a] text-gray-400 hover:text-white hover:bg-[#222]"
          }`}
        >
          📄 Native View
        </button>
      </div>

      {/* Native PDF View (iframe) */}
      {viewMode === "native" ? (
        <main className="flex-1 overflow-hidden bg-white">
          <iframe
            src={pdfUrl}
            title={title}
            className="w-full h-full border-none"
            style={{ minHeight: "100%", background: "white" }}
          />
        </main>
      ) : (
        <>
          {/* PDF Canvas with touch gestures for pan/zoom when zoomed in */}
          <main
            ref={containerRef}
            className={`flex-1 overflow-auto p-4 flex justify-center relative ${scale > 1 ? "touch-none" : ""}`}
            onTouchStart={handleTouchStart}
            onTouchMove={handleTouchMove}
            onTouchEnd={handleTouchEnd}
          >
            <div
              className="relative"
              style={{
                transform: scale > 1 ? `translate(${panOffset.x}px, ${panOffset.y}px)` : undefined,
                transition: isPanning ? "none" : "transform 0.1s ease-out",
              }}
            >
              <canvas ref={canvasRef} className="max-w-full shadow-lg" style={{ display: "block" }} />
              {/* Text selection layer - positioned over canvas, allows text selection */}
              <div
                ref={textLayerRef}
                className="absolute top-0 left-0 text-layer-container"
                style={{
                  // Text layer styling for PDF.js
                  overflow: "hidden",
                  lineHeight: 1,
                }}
              />
              {/* Annotation layer - clickable links from PDF */}
              <div
                ref={annotationLayerRef}
                className="absolute top-0 left-0 annotation-layer-container"
                style={{
                  overflow: "hidden",
                  pointerEvents: "auto",
                }}
              />
            </div>

            {/* Pan hint when zoomed */}
            {scale > 1 && !isPanning && (
              <div className="absolute top-2 left-1/2 -translate-x-1/2 bg-black/80 backdrop-blur-sm px-3 py-1 rounded-full">
                <span className="text-[10px] text-gray-400 font-mono">Drag to pan • Pinch to zoom</span>
              </div>
            )}
          </main>

          {/* Floating zoom controls - positioned above the footer to avoid home indicator */}
          <div className="absolute bottom-32 right-4 flex flex-col gap-2 z-40">
            <button
              onClick={() => setScale(Math.min(3, scale + 0.25))}
              className="w-11 h-11 rounded-full bg-[#1a1a1a]/90 backdrop-blur-sm border border-[#333] text-white font-mono text-lg hover:bg-[#222] hover:border-[#00ff00] shadow-lg flex items-center justify-center"
            >
              +
            </button>
            <button
              onClick={() => {
                setScale(1);
                setPanOffset({ x: 0, y: 0 });
              }}
              className="w-11 h-8 rounded-full bg-black/80 backdrop-blur-sm flex items-center justify-center hover:bg-[#222] transition-colors"
            >
              <span className="text-[#00ff00] font-mono text-[10px]">
                {Math.round(scale * 100)}%
              </span>
            </button>
            <button
              onClick={() => setScale(Math.max(0.5, scale - 0.25))}
              className="w-11 h-11 rounded-full bg-[#1a1a1a]/90 backdrop-blur-sm border border-[#333] text-white font-mono text-lg hover:bg-[#222] hover:border-[#00ff00] shadow-lg flex items-center justify-center"
            >
              −
            </button>
          </div>

          {/* Navigation Footer - with extra padding for iPhone home indicator */}
          <footer className="shrink-0 px-3 pt-3 pb-6 border-t border-[#1a1a1a] bg-black">
            {/* Page navigation */}
            <div className="flex items-center justify-center gap-4">
              <button
                onClick={() => goToPage(currentPage - 1)}
                disabled={currentPage <= 1}
                className="w-12 h-12 rounded-lg bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] disabled:opacity-30 disabled:cursor-not-allowed font-mono text-lg"
              >
                ←
              </button>
              <div className="flex items-center gap-2">
                <input
                  type="number"
                  value={currentPage}
                  onChange={(e) => goToPage(parseInt(e.target.value) || 1)}
                  min={1}
                  max={numPages}
                  className="w-16 h-10 bg-[#1a1a1a] border border-[#333] rounded-lg text-center text-[#00ff00] font-mono text-sm focus:outline-none focus:border-[#00ff00]"
                />
                <span className="text-gray-500 font-mono text-sm">/ {numPages}</span>
              </div>
              <button
                onClick={() => goToPage(currentPage + 1)}
                disabled={currentPage >= numPages}
                className="w-12 h-12 rounded-lg bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] disabled:opacity-30 disabled:cursor-not-allowed font-mono text-lg"
              >
                →
              </button>
            </div>
          </footer>
        </>
      )}

      {/* Upvote Modal */}
      <UpvoteModal
        isOpen={showUpvoteModal}
        onClose={() => setShowUpvoteModal(false)}
        onUpvote={handleUpvote}
        isUpvoting={isUpvoting}
        bookTitle={title}
        currentUpvotes={displayUpvotes}
      />
    </div>
  );
}
src/features/app/components/premium-upload-modal.tsx
"use client";

import { useState } from "react";
import { Button, P, Small, H4 } from "@neynar/ui";
import { CheckCircleIcon } from "@/components/icons/net-library-icons";
import { useUsdcTransfer, useUsdcBalanceOf } from "@/neynar-web-sdk/src/blockchain/contracts/base/usdc/hooks";
import { useAccount } from "wagmi";
import { parseUnits, formatUnits } from "viem";
import {
  FREE_TIER_MEMBER_MAX_SIZE,
  PREMIUM_PRICE_PER_MB,
  calculatePremiumFee,
  PREMIUM_UPLOAD_TREASURY,
  UPLOAD_PASS_PRICE,
} from "@/lib/net-protocol";

type PaymentReason = "file-size" | "upload-pass";

interface PremiumUploadModalProps {
  isOpen: boolean;
  onClose: () => void;
  onPaymentComplete: () => void;
  fileSize: number;
  fileName: string;
  // Optional: specify reason for payment (defaults to file-size for backwards compatibility)
  paymentReason?: PaymentReason;
  // Optional: override fee amount (for Upload Pass)
  overrideFee?: number;
}

export function PremiumUploadModal({
  isOpen,
  onClose,
  onPaymentComplete,
  fileSize,
  fileName,
  paymentReason = "file-size",
  overrideFee,
}: PremiumUploadModalProps) {
  const { address } = useAccount();
  const [isPaying, setIsPaying] = useState(false);
  const [paymentError, setPaymentError] = useState<string | null>(null);
  const [paymentSuccess, setPaymentSuccess] = useState(false);

  // Get user's USDC balance
  const { data: usdcBalance } = useUsdcBalanceOf(address as `0x${string}`, {
    enabled: !!address,
  });

  // USDC transfer hook
  const { writeAsync: transferUsdc } = useUsdcTransfer();

  // Calculate the fee based on reason
  const isUploadPass = paymentReason === "upload-pass";
  const premiumFee = overrideFee ?? (isUploadPass
    ? UPLOAD_PASS_PRICE
    : calculatePremiumFee(fileSize));
  const excessBytes = fileSize - FREE_TIER_MEMBER_MAX_SIZE;
  const excessMB = Math.ceil(excessBytes / (1024 * 1024));
  const fileSizeMB = (fileSize / (1024 * 1024)).toFixed(1);

  // Format user's USDC balance (USDC has 6 decimals)
  const formattedBalance = usdcBalance
    ? parseFloat(formatUnits(usdcBalance, 6)).toFixed(2)
    : "0.00";
  const hasEnoughUsdc = usdcBalance
    ? usdcBalance >= parseUnits(premiumFee.toString(), 6)
    : false;

  const handlePayment = async () => {
    if (!address || !hasEnoughUsdc) return;

    setIsPaying(true);
    setPaymentError(null);

    try {
      // Convert fee to USDC units (6 decimals)
      const feeInUnits = parseUnits(premiumFee.toString(), 6);

      await transferUsdc({
        to: PREMIUM_UPLOAD_TREASURY,
        value: feeInUnits,
      });

      setPaymentSuccess(true);

      // Brief delay to show success state, then proceed
      setTimeout(() => {
        onPaymentComplete();
      }, 1500);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : "Payment failed";

      if (errorMessage.toLowerCase().includes("user rejected") ||
          errorMessage.toLowerCase().includes("user denied")) {
        setPaymentError("Payment cancelled");
      } else if (errorMessage.toLowerCase().includes("insufficient")) {
        setPaymentError("Insufficient USDC balance");
      } else {
        setPaymentError(errorMessage);
      }
    } finally {
      setIsPaying(false);
    }
  };

  if (!isOpen) return null;

  // Theme colors based on payment reason
  const borderColor = isUploadPass ? "border-yellow-500/30" : "border-purple-500/30";
  const bgColor = isUploadPass ? "bg-yellow-500/10" : "bg-purple-500/10";
  const textColor = isUploadPass ? "text-yellow-400" : "text-purple-400";
  const lightTextColor = isUploadPass ? "text-yellow-300" : "text-purple-300";
  const btnBgColor = isUploadPass ? "bg-yellow-500 hover:bg-yellow-600" : "bg-purple-500 hover:bg-purple-600";
  const btnLoadingBg = isUploadPass ? "bg-yellow-500/20 text-yellow-400" : "bg-purple-500/20 text-purple-400";
  const btnTextColor = isUploadPass ? "text-black" : "text-white";

  return (
    <div
      className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4"
      onClick={isPaying || paymentSuccess ? undefined : onClose}
    >
      <div
        className={`bg-[#0a0a0a] border ${borderColor} rounded-xl w-full max-w-sm overflow-hidden`}
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className={`px-4 py-3 border-b ${borderColor} flex items-center justify-between ${bgColor}`}>
          <H4 className={`${textColor} font-mono`}>
            {isUploadPass ? "Upload Pass" : "Premium Upload"}
          </H4>
          {!isPaying && !paymentSuccess && (
            <button
              onClick={onClose}
              className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors"
            >
              ✕
            </button>
          )}
        </div>

        {/* Content */}
        <div className="p-4 space-y-4">
          {paymentSuccess ? (
            // Success state
            <div className="text-center py-6">
              <div className="mb-3 flex justify-center"><CheckCircleIcon size={48} className="text-[#00ff00]" /></div>
              <H4 className="text-[#00ff00] font-mono mb-2">
                {isUploadPass ? "Upload Pass Activated!" : "Payment Complete!"}
              </H4>
              <P className="text-gray-400 font-mono text-sm">
                {isUploadPass ? "You now have 100 uploads/day during warm-up" : "Proceeding with upload..."}
              </P>
            </div>
          ) : (
            <>
              {/* Explanation - different based on reason */}
              <div className={`${bgColor} border ${borderColor} rounded-lg p-3`}>
                <div className="flex items-start gap-2">
                  <span className={`${textColor} text-lg`}>
                    {isUploadPass ? "⚡" : "💎"}
                  </span>
                  <div>
                    <P className={`${lightTextColor} font-mono text-xs font-bold`}>
                      {isUploadPass ? "Unlock Full Upload Access" : "Large File Upload"}
                    </P>
                    <Small className={`${lightTextColor}/70 font-mono text-[10px] leading-tight block mt-0.5`}>
                      {isUploadPass
                        ? "Get 100 uploads per day during your warm-up period instead of the standard 10."
                        : "Files over 15MB require a small fee to cover the additional onchain storage costs."}
                    </Small>
                  </div>
                </div>
              </div>

              {/* Upload Pass benefits (only show for upload pass) */}
              {isUploadPass && (
                <div className="bg-[#1a1a1a] rounded-lg p-3 space-y-2">
                  <Small className="text-yellow-400 font-mono font-bold block mb-2">Upload Pass Benefits</Small>
                  <div className="flex justify-between">
                    <Small className="text-gray-400 font-mono">Daily uploads</Small>
                    <Small className="text-green-400 font-mono">100/day (was 10)</Small>
                  </div>
                  <div className="flex justify-between">
                    <Small className="text-gray-400 font-mono">File size limit</Small>
                    <Small className="text-white font-mono">100MB (unchanged)</Small>
                  </div>
                  <div className="flex justify-between">
                    <Small className="text-gray-400 font-mono">Duration</Small>
                    <Small className="text-white font-mono">Rest of warm-up period</Small>
                  </div>
                </div>
              )}

              {/* File details (only show for file-size payment) */}
              {!isUploadPass && (
                <div className="bg-[#1a1a1a] rounded-lg p-3 space-y-2">
                  <div className="flex justify-between">
                    <Small className="text-gray-400 font-mono">File</Small>
                    <Small className="text-white font-mono truncate max-w-[200px]">{fileName}</Small>
                  </div>
                  <div className="flex justify-between">
                    <Small className="text-gray-400 font-mono">Size</Small>
                    <Small className="text-white font-mono">{fileSizeMB} MB</Small>
                  </div>
                  <div className="flex justify-between">
                    <Small className="text-gray-400 font-mono">Member free tier</Small>
                    <Small className="text-green-400 font-mono">15 MB</Small>
                  </div>
                  <div className="flex justify-between">
                    <Small className="text-gray-400 font-mono">Excess</Small>
                    <Small className="text-yellow-400 font-mono">{excessMB} MB</Small>
                  </div>
                </div>
              )}

              {/* Pricing breakdown */}
              <div className="bg-[#1a1a1a] rounded-lg p-3 space-y-2">
                {!isUploadPass && (
                  <>
                    <div className="flex justify-between items-center">
                      <Small className="text-gray-400 font-mono">Rate</Small>
                      <Small className="text-green-400 font-mono">
                        ${PREMIUM_PRICE_PER_MB}/MB over 15MB
                      </Small>
                    </div>
                    <div className="h-px bg-[#333]" />
                  </>
                )}
                <div className="flex justify-between items-center">
                  <Small className="text-gray-400 font-mono">
                    {isUploadPass ? "Upload Pass Price" : "Total Fee"}
                  </Small>
                  <div className="text-right">
                    <P className={`${textColor} font-mono font-bold`}>
                      ${premiumFee} USDC
                    </P>
                  </div>
                </div>
              </div>

              {/* USDC Balance */}
              <div className={`rounded-lg p-3 ${hasEnoughUsdc ? "bg-[#00ff00]/10 border border-[#00ff00]/30" : "bg-red-500/10 border border-red-500/30"}`}>
                <div className="flex justify-between items-center">
                  <Small className="text-gray-400 font-mono">Your USDC</Small>
                  <Small className={`font-mono font-bold ${hasEnoughUsdc ? "text-[#00ff00]" : "text-red-400"}`}>
                    ${formattedBalance}
                  </Small>
                </div>
                {!hasEnoughUsdc && (
                  <Small className="text-red-400 font-mono text-[10px] block mt-2">
                    You need ${(premiumFee - parseFloat(formattedBalance)).toFixed(2)} more USDC
                  </Small>
                )}
              </div>

              {/* Error message */}
              {paymentError && (
                <div className="bg-red-500/10 border border-red-500/30 rounded-lg p-3">
                  <Small className="text-red-400 font-mono text-center block">
                    {paymentError}
                  </Small>
                </div>
              )}

              {/* Action buttons */}
              <div className="flex gap-2">
                <Button
                  onClick={onClose}
                  variant="outline"
                  disabled={isPaying}
                  className="flex-1 border-[#333] text-gray-400 hover:border-[#00ff00] hover:text-[#00ff00]"
                >
                  Cancel
                </Button>
                <Button
                  onClick={handlePayment}
                  disabled={isPaying || !hasEnoughUsdc}
                  className={`flex-1 font-mono font-bold ${
                    isPaying
                      ? btnLoadingBg + " cursor-wait"
                      : !hasEnoughUsdc
                      ? "bg-gray-600 text-gray-400 cursor-not-allowed"
                      : btnBgColor + " " + btnTextColor
                  }`}
                >
                  {isPaying ? "Processing..." : isUploadPass ? "Buy Upload Pass" : `Pay $${premiumFee} USDC`}
                </Button>
              </div>

              {/* Info text */}
              <Small className="text-gray-500 font-mono text-center block text-[10px]">
                Payment goes to Net Library treasury to sustain the service
              </Small>
            </>
          )}
        </div>
      </div>
    </div>
  );
}
src/features/app/components/pull-to-refresh.tsx
"use client";

import { useState, useRef, useCallback, ReactNode } from "react";
import { triggerHaptic } from "@/lib/app-mode";

interface PullToRefreshProps {
  children: ReactNode;
  onRefresh: () => Promise<void> | void;
  className?: string;
  threshold?: number; // Distance to trigger refresh (default 80px)
  disabled?: boolean;
}

export function PullToRefresh({
  children,
  onRefresh,
  className = "",
  threshold = 80,
  disabled = false,
}: PullToRefreshProps) {
  const [pullDistance, setPullDistance] = useState(0);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [hasTriggeredHaptic, setHasTriggeredHaptic] = useState(false);
  const startY = useRef(0);
  const containerRef = useRef<HTMLDivElement>(null);

  const handleTouchStart = useCallback((e: React.TouchEvent) => {
    if (disabled || isRefreshing) return;

    // Only enable pull-to-refresh when scrolled to top
    if (containerRef.current && containerRef.current.scrollTop === 0) {
      startY.current = e.touches[0].clientY;
    }
  }, [disabled, isRefreshing]);

  const handleTouchMove = useCallback((e: React.TouchEvent) => {
    if (disabled || isRefreshing || startY.current === 0) return;

    // Only pull when at scroll top
    if (containerRef.current && containerRef.current.scrollTop > 0) {
      startY.current = 0;
      setPullDistance(0);
      return;
    }

    const currentY = e.touches[0].clientY;
    const diff = currentY - startY.current;

    if (diff > 0) {
      // Apply resistance - the further you pull, the harder it gets
      const resistance = 0.4;
      const pull = diff * resistance;
      setPullDistance(Math.min(pull, threshold * 1.5));

      // Trigger haptic when threshold is crossed
      if (pull >= threshold && !hasTriggeredHaptic) {
        triggerHaptic("medium");
        setHasTriggeredHaptic(true);
      } else if (pull < threshold && hasTriggeredHaptic) {
        setHasTriggeredHaptic(false);
      }
    }
  }, [disabled, isRefreshing, threshold, hasTriggeredHaptic]);

  const handleTouchEnd = useCallback(async () => {
    if (disabled || isRefreshing) return;

    if (pullDistance >= threshold) {
      setIsRefreshing(true);
      setPullDistance(threshold * 0.5); // Keep some visual indication

      // Trigger success haptic
      triggerHaptic("success");

      try {
        await onRefresh();
      } finally {
        setIsRefreshing(false);
        setPullDistance(0);
      }
    } else {
      setPullDistance(0);
    }

    startY.current = 0;
    setHasTriggeredHaptic(false);
  }, [disabled, isRefreshing, pullDistance, threshold, onRefresh]);

  const indicatorOpacity = Math.min(pullDistance / threshold, 1);
  const indicatorScale = 0.5 + (indicatorOpacity * 0.5);

  return (
    <div
      ref={containerRef}
      className={`relative overflow-y-auto ${className}`}
      onTouchStart={handleTouchStart}
      onTouchMove={handleTouchMove}
      onTouchEnd={handleTouchEnd}
    >
      {/* Pull indicator */}
      <div
        className="absolute left-0 right-0 flex items-center justify-center pointer-events-none z-10 transition-transform"
        style={{
          top: -40,
          transform: `translateY(${pullDistance}px)`,
        }}
      >
        <div
          className="flex items-center justify-center w-8 h-8 rounded-full bg-[#00ff00]/20 border border-[#00ff00]/30 transition-all"
          style={{
            opacity: indicatorOpacity,
            transform: `scale(${indicatorScale}) rotate(${isRefreshing ? 360 : pullDistance * 2}deg)`,
          }}
        >
          {isRefreshing ? (
            <div className="w-4 h-4 border-2 border-[#00ff00] border-t-transparent rounded-full animate-spin" />
          ) : (
            <span className="text-[#00ff00] text-sm">↓</span>
          )}
        </div>
      </div>

      {/* Content with pull transform */}
      <div
        className="transition-transform h-full flex flex-col"
        style={{
          transform: `translateY(${pullDistance}px)`,
          transitionDuration: pullDistance === 0 ? "200ms" : "0ms",
        }}
      >
        {children}
      </div>
    </div>
  );
}
src/features/app/components/reading-stats-card.tsx
"use client";

import { useEffect, useState } from "react";
import { Card, CardContent, Small, P, H4 } from "@neynar/ui";
import { useAccount } from "wagmi";
import { ChartIcon, LibraryIcon, FlameIcon } from "@/components/icons/net-library-icons";

interface ReadingStats {
  currentStreak: number;
  longestStreak: number;
  totalBooksCompleted: number;
  totalReadingTimeMinutes: number;
  totalPagesRead: number;
  averageRating: number;
  totalReviewsWritten: number;
  lastReadDate: string | null;
  weeklyProgress: number[];
}

export function ReadingStatsCard() {
  const { address } = useAccount();
  const [stats, setStats] = useState<ReadingStats | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    if (!address) {
      setStats(null);
      setIsLoading(false);
      return;
    }

    setIsLoading(true);
    fetch(`/api/reading-stats?userAddress=${address}`)
      .then((res) => res.json())
      .then((data) => {
        if (data.stats) {
          setStats(data.stats);
        }
      })
      .catch((err) => {
        console.error("Failed to fetch reading stats:", err);
      })
      .finally(() => {
        setIsLoading(false);
      });
  }, [address]);

  const formatReadingTime = (minutes: number) => {
    if (minutes < 60) return `${minutes}m`;
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;
  };

  if (!address) {
    return (
      <Card className="bg-[#0a0a0a] border border-[#00ff00]/30">
        <CardContent className="p-4 text-center">
          <Small className="text-gray-500 font-mono">Connect wallet to see reading stats</Small>
        </CardContent>
      </Card>
    );
  }

  if (isLoading) {
    return (
      <Card className="bg-[#0a0a0a] border border-[#00ff00]/30">
        <CardContent className="p-4 text-center">
          <Small className="text-[#00ff00] font-mono animate-pulse">Loading stats...</Small>
        </CardContent>
      </Card>
    );
  }

  if (!stats) {
    return (
      <Card className="bg-[#0a0a0a] border border-[#00ff00]/30">
        <CardContent className="p-4 text-center">
          <Small className="text-gray-500 font-mono">Start reading to track your stats!</Small>
        </CardContent>
      </Card>
    );
  }

  return (
    <div className="space-y-3">
      <H4 className="text-[#00ff00] font-mono flex items-center gap-2"><ChartIcon size={18} /> Your Reading Stats</H4>

      {/* Streak Card */}
      <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
        <CardContent className="p-4">
          <div className="flex items-center justify-between">
            <div>
              <Small className="text-gray-500 font-mono uppercase tracking-wider">Current Streak</Small>
              <div className="flex items-baseline gap-2 mt-1">
                <span className="text-4xl font-bold text-[#00ff00] font-mono">
                  {stats.currentStreak}
                </span>
                <FlameIcon size={24} className="text-orange-400" />
              </div>
            </div>
            <div className="text-right">
              <Small className="text-gray-500 font-mono uppercase tracking-wider">Best</Small>
              <P className="text-[#00ff00] font-mono mt-1">{stats.longestStreak} days</P>
            </div>
          </div>

          {/* Weekly Progress */}
          {stats.weeklyProgress && stats.weeklyProgress.length > 0 && (
            <div className="mt-4">
              <Small className="text-gray-500 font-mono text-[10px] block mb-2">This Week</Small>
              <div className="flex gap-1">
                {["M", "T", "W", "T", "F", "S", "S"].map((day, i) => {
                  const hasActivity = stats.weeklyProgress[i] > 0;
                  return (
                    <div key={i} className="flex-1 text-center">
                      <div
                        className={`h-6 rounded-sm ${
                          hasActivity ? "bg-[#00ff00]" : "bg-[#1a1a1a]"
                        }`}
                        style={{
                          opacity: hasActivity ? 0.3 + (stats.weeklyProgress[i] / Math.max(...stats.weeklyProgress)) * 0.7 : 1,
                        }}
                      />
                      <Small className="text-gray-600 font-mono text-[9px] mt-0.5 block">{day}</Small>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* Stats Grid */}
      <div className="grid grid-cols-2 gap-2">
        <Card className="bg-[#0a0a0a] border border-[#1a1a1a]">
          <CardContent className="p-3 text-center">
            <span className="text-2xl text-[#00ff00]"><LibraryIcon size={28} /></span>
            <P className="text-xl font-bold text-white font-mono mt-1">
              {stats.totalBooksCompleted}
            </P>
            <Small className="text-gray-500 font-mono text-[10px]">Books Completed</Small>
          </CardContent>
        </Card>

        <Card className="bg-[#0a0a0a] border border-[#1a1a1a]">
          <CardContent className="p-3 text-center">
            <span className="text-2xl">⏱️</span>
            <P className="text-xl font-bold text-white font-mono mt-1">
              {formatReadingTime(stats.totalReadingTimeMinutes)}
            </P>
            <Small className="text-gray-500 font-mono text-[10px]">Total Reading Time</Small>
          </CardContent>
        </Card>

        <Card className="bg-[#0a0a0a] border border-[#1a1a1a]">
          <CardContent className="p-3 text-center">
            <span className="text-2xl">📄</span>
            <P className="text-xl font-bold text-white font-mono mt-1">
              {stats.totalPagesRead}
            </P>
            <Small className="text-gray-500 font-mono text-[10px]">Pages Read</Small>
          </CardContent>
        </Card>

        <Card className="bg-[#0a0a0a] border border-[#1a1a1a]">
          <CardContent className="p-3 text-center">
            <span className="text-2xl">⭐</span>
            <P className="text-xl font-bold text-white font-mono mt-1">
              {stats.totalReviewsWritten}
            </P>
            <Small className="text-gray-500 font-mono text-[10px]">Reviews Written</Small>
          </CardContent>
        </Card>
      </div>
    </div>
  );
}
src/features/app/components/reading-view.tsx
"use client";

import { useState, useEffect } from "react";
import { Button, Small } from "@neynar/ui";
import type { Book, VoiceOption, VoiceGender, Category } from "@/features/app/types";
import { useUpvote } from "@/hooks/use-upvotes";
import { UpvoteModal } from "./upvote-modal";
import { ShareIcon } from "@/components/icons/net-library-icons";

interface ReadingViewProps {
  book: Book;
  sentences: string[];
  voiceOptions: VoiceOption[];
  categories: Category[];
  upvoteCount?: number;
  onBack: () => void;
  onShare: () => void;
  onUpvoteSuccess?: () => void;
}

// Helper to get storage key for a book's reading progress
const getProgressKey = (bookId: string) => `net-library-progress-${bookId}`;

export function ReadingView({
  book,
  sentences,
  voiceOptions,
  categories,
  upvoteCount = 0,
  onBack,
  onShare,
  onUpvoteSuccess,
}: ReadingViewProps) {
  const [fontSize, setFontSize] = useState(16);
  const [localUpvotes, setLocalUpvotes] = useState(0);
  const [showUpvoteModal, setShowUpvoteModal] = useState(false);
  const { upvote, isUpvoting, isConfirmed } = useUpvote();

  const handleUpvote = async (count: number) => {
    if (!book.contentKey || !book.uploader?.address) return;
    const success = await upvote(book.contentKey, book.uploader.address, count);
    if (success) {
      setLocalUpvotes((prev) => prev + count);
      setShowUpvoteModal(false);
    }
  };

  // When transaction is confirmed, refresh the counts from the blockchain
  useEffect(() => {
    if (isConfirmed) {
      const timer = setTimeout(() => {
        onUpvoteSuccess?.();
      }, 2000);
      return () => clearTimeout(timer);
    }
  }, [isConfirmed, onUpvoteSuccess]);

  const displayUpvotes = upvoteCount + localUpvotes;
  const [isPlaying, setIsPlaying] = useState(false);
  const [speechRate, setSpeechRate] = useState(1);
  const [currentSentence, setCurrentSentence] = useState(0);
  const [showAudioPlayer, setShowAudioPlayer] = useState(false);
  const [selectedVoice, setSelectedVoice] = useState<VoiceGender>("female");
  const [currentPage, setCurrentPage] = useState(1);
  const [showJumpTo, setShowJumpTo] = useState(false);
  const [jumpToPage, setJumpToPage] = useState("");
  const [progressLoaded, setProgressLoaded] = useState(false);

  // Load saved progress on mount
  useEffect(() => {
    const savedProgress = localStorage.getItem(getProgressKey(book.id));
    if (savedProgress) {
      try {
        const { page, sentence } = JSON.parse(savedProgress);
        setCurrentPage(page);
        setCurrentSentence(sentence);
      } catch {
        // Invalid saved data, start fresh
      }
    }
    setProgressLoaded(true);
  }, [book.id]);

  // Save progress whenever page or sentence changes
  useEffect(() => {
    if (progressLoaded) {
      localStorage.setItem(
        getProgressKey(book.id),
        JSON.stringify({ page: currentPage, sentence: currentSentence })
      );
    }
  }, [currentPage, currentSentence, book.id, progressLoaded]);

  // Start over function
  const handleStartOver = () => {
    window.speechSynthesis?.cancel();
    setIsPlaying(false);
    setCurrentPage(1);
    setCurrentSentence(0);
    localStorage.removeItem(getProgressKey(book.id));
  };

  // Dynamic pagination: show more sentences per page for shorter content
  // Short content (< 20 sentences): show all on one page
  // Medium content (20-100 sentences): show 10 per page
  // Long content (> 100 sentences): show 5 per page
  const sentencesPerPage = sentences.length <= 20 ? sentences.length : sentences.length <= 100 ? 10 : 5;
  const totalPages = Math.max(1, Math.ceil(sentences.length / sentencesPerPage));

  // Get sentences for current page
  const startIndex = (currentPage - 1) * sentencesPerPage;
  const endIndex = startIndex + sentencesPerPage;
  const currentPageSentences = sentences.slice(startIndex, endIndex);

  const _categoryInfo = categories.find((c) => c.id === (book.categories?.[0]));

  // Get the best matching voice from available voices
  // FIXED: female voice for female selection, male voice for male selection
  const getVoice = () => {
    const voices = window.speechSynthesis?.getVoices() || [];
    const isFemale = selectedVoice === "female";

    // Female voice indicators
    const femaleHints = ["female", "samantha", "karen", "victoria", "kate", "susan", "zira", "hazel", "fiona", "siri", "ava", "allison"];
    // Male voice indicators
    const maleHints = ["male", "david", "daniel", "james", "george", "guy", "mark", "alex", "fred", "tom"];

    const genderHints = isFemale ? femaleHints : maleHints;

    const genderMatch = voices.find((v) =>
      genderHints.some((hint) => v.name.toLowerCase().includes(hint))
    );

    if (genderMatch) return genderMatch;
    return voices[0] || null;
  };

  // Calculate which page a sentence belongs to
  const getPageForSentence = (sentenceIndex: number) => {
    return Math.floor(sentenceIndex / sentencesPerPage) + 1;
  };

  const speakSentence = (index: number) => {
    if (index >= sentences.length) {
      setIsPlaying(false);
      setCurrentSentence(0);
      setCurrentPage(1);
      return;
    }

    // Auto-advance page to keep up with the reader
    const targetPage = getPageForSentence(index);
    if (targetPage !== currentPage) {
      setCurrentPage(targetPage);
    }

    const utterance = new SpeechSynthesisUtterance(sentences[index]);
    utterance.rate = speechRate;

    const voice = getVoice();
    if (voice) {
      utterance.voice = voice;
    }

    utterance.onend = () => {
      const nextIndex = index + 1;
      setCurrentSentence(nextIndex);

      // Auto-advance page when moving to next sentence
      const nextPage = getPageForSentence(nextIndex);
      if (nextPage !== currentPage && nextIndex < sentences.length) {
        setCurrentPage(nextPage);
      }

      if (nextIndex < sentences.length) {
        speakSentence(nextIndex);
      } else {
        setIsPlaying(false);
      }
    };

    window.speechSynthesis?.speak(utterance);
    setIsPlaying(true);
    setCurrentSentence(index);
  };

  const togglePlayback = () => {
    if (isPlaying) {
      // Use pause() instead of cancel() to preserve position
      window.speechSynthesis?.pause();
      setIsPlaying(false);
    } else {
      // Check if we have paused speech to resume
      if (window.speechSynthesis?.paused) {
        window.speechSynthesis.resume();
        setIsPlaying(true);
      } else {
        // Start fresh from current sentence
        speakSentence(currentSentence);
      }
    }
  };

  const skipForward = () => {
    window.speechSynthesis?.cancel();
    const nextIndex = Math.min(currentSentence + 1, sentences.length - 1);
    setCurrentSentence(nextIndex);
    // Sync page with new sentence position
    setCurrentPage(getPageForSentence(nextIndex));
    if (isPlaying) {
      speakSentence(nextIndex);
    }
  };

  const skipBackward = () => {
    window.speechSynthesis?.cancel();
    const prevIndex = Math.max(currentSentence - 1, 0);
    setCurrentSentence(prevIndex);
    // Sync page with new sentence position
    setCurrentPage(getPageForSentence(prevIndex));
    if (isPlaying) {
      speakSentence(prevIndex);
    }
  };

  const changeSpeed = () => {
    const speeds = [0.75, 1, 1.25, 1.5, 2];
    const currentIndex = speeds.indexOf(speechRate);
    const nextSpeed = speeds[(currentIndex + 1) % speeds.length];
    setSpeechRate(nextSpeed);
  };

  const handleBack = () => {
    window.speechSynthesis?.cancel();
    setIsPlaying(false);
    onBack();
  };

  return (
    <div className="h-dvh flex flex-col overflow-hidden bg-black">
      {/* Header */}
      <header className="shrink-0 px-4 py-3 border-b border-[#1a1a1a] flex items-center gap-2">
        <button
          onClick={handleBack}
          className="w-10 h-10 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] shrink-0"
        >
          ←
        </button>
        <div className="flex-1 min-w-0">
          <p className="text-[#00ff00] font-mono text-sm font-bold truncate">{book.title}</p>
          <p className="text-gray-500 font-mono text-xs truncate">{book.author}</p>
        </div>
        {/* Upvote button */}
        {book.contentKey && book.uploader?.address && (
          <button
            onClick={() => setShowUpvoteModal(true)}
            disabled={isUpvoting}
            className={`h-10 px-3 rounded-full flex items-center gap-1.5 font-mono text-xs transition-all shrink-0 ${
              isUpvoting
                ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/30"
                : isConfirmed
                ? "bg-[#00ff00]/30 text-[#00ff00] border border-[#00ff00]/50"
                : "bg-[#1a1a1a] text-[#00ff00] hover:bg-[#222] border border-[#00ff00]/30"
            }`}
          >
            <span>▲</span>
            <span>{displayUpvotes}</span>
          </button>
        )}
      </header>

      {/* Reading controls */}
      <div className="shrink-0 flex items-center justify-between px-4 py-2 bg-[#0a0a0a] border-b border-[#1a1a1a]">
        <div className="flex items-center gap-2">
          <button
            onClick={() => setFontSize((s) => Math.max(12, s - 2))}
            className="px-3 py-1.5 rounded border border-[#222] text-gray-300 hover:border-[#00ff00] hover:text-[#00ff00] font-mono text-xs"
          >
            A-
          </button>
          <Small className="text-gray-400 font-mono text-xs">{fontSize}px</Small>
          <button
            onClick={() => setFontSize((s) => Math.min(24, s + 2))}
            className="px-3 py-1.5 rounded border border-[#222] text-gray-300 hover:border-[#00ff00] hover:text-[#00ff00] font-mono text-xs"
          >
            A+
          </button>
        </div>
        {/* Listen button */}
        <button
          onClick={() => setShowAudioPlayer(!showAudioPlayer)}
          className={`px-3 py-1.5 rounded-full text-xs font-mono flex items-center gap-1.5 transition-all ${
            showAudioPlayer
              ? "bg-[#00ff00] text-black"
              : "bg-[#1a1a1a] text-gray-300 hover:bg-[#222] hover:text-[#00ff00]"
          }`}
        >
          🎧 {showAudioPlayer ? "Hide" : "Listen"}
        </button>
        <Small className="text-gray-500 font-mono">Page {currentPage} / {totalPages}</Small>
      </div>

      {/* Audio Player */}
      {showAudioPlayer && (
        <div className="shrink-0 px-4 py-3 bg-[#00ff00]/10 border-b border-[#00ff00]/30">
          {/* Progress bar */}
          <div className="mb-3">
            <div className="h-1.5 bg-[#1a1a1a] rounded-full overflow-hidden">
              <div
                className="h-full bg-[#00ff00] rounded-full transition-all"
                style={{ width: `${((currentSentence + 1) / sentences.length) * 100}%` }}
              />
            </div>
            <div className="flex justify-between mt-1">
              <Small className="text-[10px] text-gray-500 font-mono">
                Sentence {currentSentence + 1} of {sentences.length}
              </Small>
              <Small className="text-[10px] text-gray-500 font-mono">
                {Math.round(((currentSentence + 1) / sentences.length) * 100)}%
              </Small>
            </div>
          </div>

          {/* Voice Selector */}
          <div className="flex gap-2 mb-3">
            {voiceOptions.map((voice) => (
              <button
                key={voice.id}
                onClick={() => {
                  setSelectedVoice(voice.id);
                  if (isPlaying) {
                    window.speechSynthesis?.cancel();
                    setTimeout(() => speakSentence(currentSentence), 100);
                  }
                }}
                className={`flex-1 flex items-center justify-center gap-2 px-3 py-2 rounded-lg transition-all font-mono ${
                  selectedVoice === voice.id
                    ? "bg-[#00ff00] text-black"
                    : "bg-[#1a1a1a] text-gray-300 hover:bg-[#222] border border-[#222]"
                }`}
              >
                <span className="text-lg">{voice.emoji}</span>
                <span className="text-sm">{voice.label}</span>
              </button>
            ))}
          </div>

          {/* Controls */}
          <div className="flex items-center justify-center gap-3">
            <button
              onClick={changeSpeed}
              className="px-2 py-1 rounded bg-[#1a1a1a] text-xs text-gray-300 hover:bg-[#222] min-w-[48px] font-mono"
            >
              {speechRate}x
            </button>
            <button
              onClick={skipBackward}
              disabled={currentSentence === 0}
              className="w-10 h-10 rounded-full bg-[#1a1a1a] text-white flex items-center justify-center hover:bg-[#222] disabled:opacity-30"
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                <path d="M6 6h2v12H6V6zm3.5 6l8.5 6V6l-8.5 6z" />
              </svg>
            </button>
            <button
              onClick={togglePlayback}
              className={`w-14 h-14 rounded-full flex items-center justify-center transition-all ${
                isPlaying
                  ? "bg-[#00ff00] text-black shadow-lg shadow-[#00ff00]/30"
                  : "bg-white text-black hover:scale-105"
              }`}
            >
              {isPlaying ? (
                <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                  <rect x="6" y="4" width="4" height="16" rx="1" />
                  <rect x="14" y="4" width="4" height="16" rx="1" />
                </svg>
              ) : (
                <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                  <path d="M8 5.14v13.72c0 .86.98 1.36 1.68.86l9.02-6.86c.58-.44.58-1.28 0-1.72L9.68 4.28C8.98 3.78 8 4.28 8 5.14z" />
                </svg>
              )}
            </button>
            <button
              onClick={skipForward}
              disabled={currentSentence === sentences.length - 1}
              className="w-10 h-10 rounded-full bg-[#1a1a1a] text-white flex items-center justify-center hover:bg-[#222] disabled:opacity-30"
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
                <path d="M6 18l8.5-6L6 6v12zM16 6v12h2V6h-2z" />
              </svg>
            </button>
            {isPlaying && (
              <div className="flex items-center gap-1 ml-2">
                <div className="w-1 h-3 bg-[#00ff00] rounded-full animate-pulse" />
                <div className="w-1 h-4 bg-[#00ff00] rounded-full animate-pulse" style={{ animationDelay: "0.1s" }} />
                <div className="w-1 h-2 bg-[#00ff00] rounded-full animate-pulse" style={{ animationDelay: "0.2s" }} />
              </div>
            )}
          </div>
        </div>
      )}

      {/* Reading content */}
      <main className="flex-1 overflow-y-auto p-4">
        <div className="bg-[#0a0a0a] rounded-lg p-4 min-h-full border border-[#1a1a1a]">
          <div className="leading-relaxed space-y-4 font-mono" style={{ fontSize: `${fontSize}px` }}>
            {currentPageSentences.map((sentence, pageIndex) => {
              // Calculate the actual index in the full sentences array
              const actualIndex = startIndex + pageIndex;
              return (
                <span
                  key={actualIndex}
                  onClick={() => {
                    window.speechSynthesis?.cancel();
                    setCurrentSentence(actualIndex);
                    if (isPlaying) {
                      speakSentence(actualIndex);
                    }
                  }}
                  className={`inline cursor-pointer transition-all duration-300 ${
                    showAudioPlayer && actualIndex === currentSentence
                      ? "text-[#00ff00] bg-[#00ff00]/10 px-1 rounded"
                      : showAudioPlayer && actualIndex < currentSentence
                      ? "text-gray-500"
                      : "text-gray-300"
                  } ${showAudioPlayer ? "hover:text-[#00ff00]" : ""}`}
                >
                  {sentence}{" "}
                </span>
              );
            })}
          </div>
        </div>
      </main>

      {/* Jump to modal */}
      {showJumpTo && (
        <div className="absolute inset-0 bg-black/80 flex items-center justify-center z-50 p-4">
          <div className="bg-[#0a0a0a] border border-[#1a1a1a] rounded-lg p-4 w-full max-w-xs">
            <Small className="text-gray-400 font-mono mb-2 block">Jump to page</Small>
            <input
              type="number"
              min={1}
              max={totalPages}
              value={jumpToPage}
              onChange={(e) => setJumpToPage(e.target.value)}
              placeholder={`1 - ${totalPages}`}
              className="w-full bg-black border border-[#222] rounded px-3 py-2 text-white font-mono mb-3 focus:border-[#00ff00] outline-none"
            />
            <div className="flex gap-2">
              <button
                onClick={() => setShowJumpTo(false)}
                className="flex-1 py-2 rounded bg-[#1a1a1a] text-gray-400 font-mono text-sm hover:bg-[#222]"
              >
                Cancel
              </button>
              <button
                onClick={() => {
                  const page = parseInt(jumpToPage);
                  if (page >= 1 && page <= totalPages) {
                    setCurrentPage(page);
                    setShowJumpTo(false);
                    setJumpToPage("");
                  }
                }}
                className="flex-1 py-2 rounded bg-[#00ff00] text-black font-mono text-sm hover:bg-[#00dd00]"
              >
                Go
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Page navigation */}
      <div className="shrink-0 flex items-center justify-between px-4 py-2 bg-[#0a0a0a] border-t border-[#1a1a1a]">
        <button
          onClick={() => setCurrentPage(Math.max(1, currentPage - 1))}
          disabled={currentPage === 1}
          className="px-3 py-2 rounded bg-[#1a1a1a] text-white text-sm hover:bg-[#222] font-mono disabled:opacity-30 disabled:cursor-not-allowed"
        >
          ← Prev
        </button>
        <div className="flex gap-1 items-center">
          {/* Show current page and nearby pages */}
          {currentPage > 2 && (
            <>
              <button
                onClick={() => setCurrentPage(1)}
                className="w-8 h-8 rounded text-sm font-mono bg-[#1a1a1a] text-gray-400 hover:bg-[#222]"
              >
                1
              </button>
              {currentPage > 3 && <span className="text-gray-500 px-1">...</span>}
            </>
          )}
          {[currentPage - 1, currentPage, currentPage + 1]
            .filter(n => n >= 1 && n <= totalPages)
            .map((n) => (
              <button
                key={n}
                onClick={() => setCurrentPage(n)}
                className={`w-8 h-8 rounded text-sm font-mono ${
                  n === currentPage
                    ? "bg-[#00ff00] text-black"
                    : "bg-[#1a1a1a] text-gray-400 hover:bg-[#222]"
                }`}
              >
                {n}
              </button>
            ))}
          {currentPage < totalPages - 1 && (
            <>
              {currentPage < totalPages - 2 && <span className="text-gray-500 px-1">...</span>}
              <button
                onClick={() => setCurrentPage(totalPages)}
                className="w-8 h-8 rounded text-sm font-mono bg-[#1a1a1a] text-gray-400 hover:bg-[#222]"
              >
                {totalPages}
              </button>
            </>
          )}
          {/* Jump to button */}
          <button
            onClick={() => setShowJumpTo(true)}
            className="ml-1 px-2 h-8 rounded text-xs font-mono bg-[#1a1a1a] text-gray-400 hover:bg-[#222] hover:text-[#00ff00]"
          >
            Jump
          </button>
        </div>
        <button
          onClick={() => setCurrentPage(Math.min(totalPages, currentPage + 1))}
          disabled={currentPage === totalPages}
          className="px-3 py-2 rounded bg-[#1a1a1a] text-white text-sm hover:bg-[#222] font-mono disabled:opacity-30 disabled:cursor-not-allowed"
        >
          Next →
        </button>
      </div>

      {/* Footer */}
      <footer className="shrink-0 p-4 border-t border-[#1a1a1a]">
        <div className="flex gap-2 mb-2">
          <Button
            onClick={handleBack}
            variant="outline"
            className="flex-1 border-[#222] text-gray-300 hover:border-[#00ff00] hover:text-[#00ff00] font-mono"
          >
            ← Back
          </Button>
          <Button
            onClick={onShare}
            variant="outline"
            className="flex-1 border-[#00ff00] text-[#00ff00] hover:bg-[#00ff00]/10 font-mono flex items-center justify-center gap-1.5"
          >
            <ShareIcon size={14} /> Share
          </Button>
        </div>
        {/* Start Over - only show if not on page 1 */}
        {currentPage > 1 && (
          <Button
            onClick={handleStartOver}
            variant="outline"
            className="w-full border-[#222] text-gray-500 hover:border-red-500/50 hover:text-red-400 font-mono text-xs"
          >
            ↺ Start Over
          </Button>
        )}
      </footer>

      {/* Upvote Modal */}
      <UpvoteModal
        isOpen={showUpvoteModal}
        onClose={() => setShowUpvoteModal(false)}
        onUpvote={handleUpvote}
        isUpvoting={isUpvoting}
        bookTitle={book.title}
        currentUpvotes={displayUpvotes}
      />
    </div>
  );
}
src/features/app/components/recommendations-section.tsx
"use client";

import { useEffect, useState } from "react";
import { Small, P } from "@neynar/ui";
import { useAccount } from "wagmi";
import type { Book } from "@/features/app/types";
// Icons available if needed: FlameIcon, LibraryIcon from "@/components/icons/net-library-icons"

interface RecommendationsProps {
  onSelectBook: (book: Book) => void;
}

interface RecommendedItem {
  contentKey: string;
  title: string;
  author: string;
  categories: string[];
  coverUrl?: string;
  operator: string;
  score?: number;
  reason?: string;
}

export function RecommendationsSection({ onSelectBook }: RecommendationsProps) {
  const { address } = useAccount();
  const [recommendations, setRecommendations] = useState<RecommendedItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    setIsLoading(true);

    // Fetch personalized recommendations if wallet connected, otherwise trending
    const endpoint = address
      ? `/api/recommendations?userAddress=${address}&limit=5`
      : `/api/recommendations?type=trending&limit=5`;

    fetch(endpoint)
      .then((res) => res.json())
      .then((data) => {
        if (data.recommendations) {
          setRecommendations(data.recommendations);
        }
      })
      .catch((err) => {
        console.error("Failed to fetch recommendations:", err);
      })
      .finally(() => {
        setIsLoading(false);
      });
  }, [address]);

  const handleSelectRecommendation = (item: RecommendedItem) => {
    // Convert to Book format
    const book: Book = {
      id: item.contentKey,
      title: item.title,
      author: item.author,
      categories: item.categories,
      coverUrl: item.coverUrl,
      contentKey: item.contentKey,
      uploader: {
        username: item.operator ? item.operator.slice(0, 6) + "..." : "Unknown",
        pfpUrl: `https://api.dicebear.com/7.x/identicon/svg?seed=${item.operator || 'unknown'}`,
        address: item.operator || "",
      },
      uploadDate: "",
      size: "",
    };
    onSelectBook(book);
  };

  // Don't show anything until we have recommendations to display
  // This prevents the "For You loading" flicker on app start
  if (isLoading || recommendations.length === 0) {
    return null;
  }

  return (
    <div className="space-y-2">
      <Small className="text-[#00ff00] font-mono">
        {address ? "📖 For You" : "🔥 Trending"}
      </Small>
      <div className="flex gap-2 overflow-x-auto pb-2 scrollbar-hide">
        {recommendations.map((item) => (
          <button
            key={item.contentKey}
            onClick={() => handleSelectRecommendation(item)}
            className="shrink-0 w-28 bg-[#0a0a0a] border border-[#00ff00]/20 rounded-lg overflow-hidden hover:border-[#00ff00]/50 transition-colors text-left"
          >
            {/* Cover */}
            <div className="w-full h-20 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] flex items-center justify-center border-b border-[#00ff00]/10">
              {item.coverUrl ? (
                <img
                  src={item.coverUrl}
                  alt={item.title}
                  className="w-full h-full object-cover"
                />
              ) : (
                <img src="/app-logo.png" alt="Net Library" className="w-8 h-8 object-contain opacity-50" />
              )}
            </div>
            {/* Info */}
            <div className="p-2">
              <P className="text-[11px] font-mono text-white line-clamp-2 leading-tight">
                {item.title}
              </P>
              <Small className="text-[9px] text-gray-500 font-mono block mt-0.5 truncate">
                {item.author}
              </Small>
              {item.reason && (
                <Small className="text-[8px] text-[#00ff00]/60 font-mono block mt-1 truncate">
                  {item.reason}
                </Small>
              )}
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}
src/features/app/components/scrolling-banner.tsx
"use client";

import { useStoragePassModal } from "./unlimited-storage-pass-modal";
import { useMembershipStatus } from "@/hooks/use-membership-status";

export function ScrollingBanner() {
  const { openStoragePassModal } = useStoragePassModal();
  const { hasStackPass, isLoading } = useMembershipStatus();

  // Wait for membership status to load before showing — avoids flash for pass holders
  if (isLoading || hasStackPass) return null;

  const bannerText = "✦ UNLIMITED PASS — $10 USDC • Upload unlimited items to stacks & grids • FREE membership included • Tap here to mint ✦";
  const repeatedText = `${bannerText}   •   `.repeat(4);

  return (
    <button
      onClick={openStoragePassModal}
      className="w-full overflow-hidden border-y bg-gradient-to-r from-purple-500/20 via-[#00ff00]/10 to-purple-500/20 border-purple-500/30 cursor-pointer hover:from-purple-500/30 hover:to-purple-500/30 transition-colors"
    >
      <div
        className="whitespace-nowrap py-2 inline-block"
        style={{ animation: "marquee 50s linear infinite" }}
      >
        <span className="font-mono text-xs tracking-wide bg-gradient-to-r from-purple-400 via-[#00ff00] to-purple-400 bg-clip-text text-transparent">
          {repeatedText}
        </span>
      </div>
    </button>
  );
}
src/features/app/components/search-bar.tsx
"use client";

import { Input } from "@neynar/ui";
import { SearchIcon } from "@/components/icons/net-library-icons";

interface SearchBarProps {
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  onMagnifyingGlassClick?: () => void;
}

export function SearchBar({ value, onChange, placeholder = "Search books...", onMagnifyingGlassClick }: SearchBarProps) {
  return (
    <div className="relative">
      <Input
        value={value}
        onChange={(e) => onChange(e.target.value)}
        placeholder={placeholder}
        className="bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] placeholder:text-[#00ff00]/50 font-mono focus:border-[#00ff00] focus:ring-[#00ff00]/20 pr-10 rounded-lg"
      />
      <button
        type="button"
        onClick={onMagnifyingGlassClick}
        className="absolute right-3 top-1/2 -translate-y-1/2 text-[#00ff00]/50 hover:text-[#00ff00] transition-colors cursor-pointer"
      >
        <SearchIcon size={18} />
      </button>
    </div>
  );
}
src/features/app/components/share-modal.tsx
"use client";

import { useState, useEffect } from "react";
import { Small } from "@neynar/ui";
import { safeComposeCast, safeOpenUrl, useAppMode } from "@/lib/app-mode";
import { X, Link2, Check } from "lucide-react";
import { normalizeCoverUrl } from "@/lib/cover-url-utils";

interface ShareModalProps {
  isOpen: boolean;
  onClose: () => void;
  title: string;
  author: string;
  coverUrl?: string;
  shareUrl: string;
}

export function ShareModal({
  isOpen,
  onClose,
  title,
  author,
  coverUrl,
  shareUrl,
}: ShareModalProps) {
  const [isSharing, setIsSharing] = useState<"farcaster" | "x" | null>(null);
  const [copied, setCopied] = useState(false);
  const [imageError, setImageError] = useState(false);
  const appMode = useAppMode();
  const isBaseApp = appMode === "base-app";

  // Normalize cover URL for display
  const normalizedCoverUrl = normalizeCoverUrl(coverUrl);

  // Reset image error state when coverUrl changes
  useEffect(() => {
    setImageError(false);
  }, [coverUrl]);

  if (!isOpen) return null;

  const shareText = `Check out "${title}" by ${author} on Net Library!\n\nDecentralized onchain media powered by @netprotocol`;
  const shareTextForX = `Check out "${title}" by ${author} on Net Library!\n\nDecentralized onchain media powered by @netprotocolapp`;

  const handleShareToFarcaster = async () => {
    setIsSharing("farcaster");
    try {
      // Ensure share URL isn't too long - Farcaster has embed limits
      // Truncate title/author in URL params if needed
      let finalShareUrl = shareUrl;
      if (shareUrl.length > 500) {
        // Try to shorten by removing cover param first
        const url = new URL(shareUrl);
        url.searchParams.delete("cover");
        finalShareUrl = url.toString();
      }

      const success = await safeComposeCast({
        text: shareText,
        embeds: [finalShareUrl],
        // Don't force channel - let user choose or post to home feed
      });

      if (success) {
        onClose();
      } else {
        // safeComposeCast returned false - show error to user
        console.error("Failed to share - safeComposeCast returned false");
        alert("Failed to create cast. Please try again.");
      }
    } catch (err) {
      console.error("Failed to share to Farcaster:", err);
      alert("Failed to share. Please try again.");
    } finally {
      setIsSharing(null);
    }
  };

  const handleShareToX = async () => {
    setIsSharing("x");
    try {
      // Build X share URL with source=web for browser deep link
      // This ensures X users land in the web browser experience, not Farcaster mini app
      const xShareUrl = new URL(shareUrl);
      xShareUrl.searchParams.set("source", "web");

      // Build X intent URL - use twitter.com to avoid Base App intercepting x.com as a profile
      const xIntentParams = new URLSearchParams({
        text: shareTextForX,
        url: xShareUrl.toString(),
      });
      const xIntentUrl = `https://twitter.com/intent/tweet?${xIntentParams.toString()}`;

      // For Base App, open in system browser to avoid in-app interception
      if (isBaseApp) {
        window.open(xIntentUrl, "_blank", "noopener,noreferrer");
      } else {
        await safeOpenUrl(xIntentUrl);
      }
      onClose();
    } catch (err) {
      console.error("Failed to share to X:", err);
    } finally {
      setIsSharing(null);
    }
  };

  const handleCopyLink = async () => {
    try {
      await navigator.clipboard.writeText(shareUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error("Failed to copy link:", err);
      // Fallback for older browsers
      const textArea = document.createElement("textarea");
      textArea.value = shareUrl;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand("copy");
      document.body.removeChild(textArea);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  // Truncate URL for display (show domain + truncated path)
  const truncatedUrl = (() => {
    try {
      const url = new URL(shareUrl);
      const path = url.pathname + url.search;
      const maxPathLength = 25;
      const truncatedPath = path.length > maxPathLength
        ? path.slice(0, maxPathLength) + "..."
        : path;
      return url.host.replace(/^www\./, "") + truncatedPath;
    } catch {
      return shareUrl.slice(0, 35) + "...";
    }
  })();

  return (
    <div className="fixed inset-0 z-[9999] flex items-center justify-center">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/80 backdrop-blur-sm"
        onClick={onClose}
      />

      {/* Modal */}
      <div className="relative w-[90%] max-w-sm bg-black border border-[#00ff00]/30 rounded-xl overflow-hidden shadow-[0_0_30px_rgba(0,255,0,0.15)]">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-[#00ff00]/20">
          <Small className="text-[#00ff00] font-mono font-bold text-sm">
            Share Book
          </Small>
          <button
            onClick={onClose}
            className="p-1.5 rounded-lg hover:bg-white/10 transition-colors"
          >
            <X size={18} className="text-gray-400" />
          </button>
        </div>

        {/* Book preview */}
        <div className="p-4 border-b border-[#00ff00]/10">
          <div className="flex items-center gap-3">
            {normalizedCoverUrl && !imageError ? (
              <img
                src={normalizedCoverUrl}
                alt={title}
                className="w-12 h-16 object-cover rounded border border-[#00ff00]/20"
                onError={() => setImageError(true)}
              />
            ) : (
              <div className="w-12 h-16 bg-[#00ff00]/10 rounded border border-[#00ff00]/20 flex items-center justify-center">
                {/* Net Library shield placeholder */}
                <svg width="24" height="30" viewBox="0 0 80 100">
                  <path
                    d="M 40,2 L 78,15 L 78,50 Q 78,85 40,98 Q 2,85 2,50 L 2,15 Z"
                    fill="rgba(0,255,0,0.1)"
                    stroke="#00ff00"
                    strokeWidth="2"
                  />
                  <g transform="translate(40, 44)">
                    <path d="M -12,-9 L -12,9 Q -6,7 0,9 L 0,-9 Q -6,-7 -12,-9" stroke="#00ff00" fill="none" strokeWidth="2" />
                    <path d="M 12,-9 L 12,9 Q 6,7 0,9 L 0,-9 Q 6,-7 12,-9" stroke="#00ff00" fill="none" strokeWidth="2" />
                  </g>
                </svg>
              </div>
            )}
            <div className="flex-1 min-w-0">
              <Small className="text-white font-mono font-bold block truncate">
                {title}
              </Small>
              <Small className="text-gray-400 font-mono text-xs truncate block">
                by {author}
              </Small>
            </div>
          </div>
        </div>

        {/* Share options */}
        <div className="p-4 space-y-3">
          {/* Farcaster / Feed button - adapts based on app mode */}
          <button
            onClick={handleShareToFarcaster}
            disabled={isSharing !== null}
            className={`w-full flex items-center gap-3 p-3 rounded-lg border transition-all disabled:opacity-50 ${
              isBaseApp
                ? "bg-[#0052FF]/10 border-[#0052FF]/30 hover:bg-[#0052FF]/20 hover:border-[#0052FF]/50"
                : "bg-[#8A63D2]/10 border-[#8A63D2]/30 hover:bg-[#8A63D2]/20 hover:border-[#8A63D2]/50"
            }`}
          >
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
              isBaseApp ? "bg-[#0052FF]/20" : "bg-[#8A63D2]/20"
            }`}>
              {isBaseApp ? (
                /* Base logo */
                <svg width="20" height="20" viewBox="0 0 111 111" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M54.921 110.034C85.359 110.034 110.034 85.402 110.034 55.017C110.034 24.6319 85.359 0 54.921 0C26.0432 0 2.35281 22.1714 0 50.3923H72.8467V59.6416H0C2.35281 87.8625 26.0432 110.034 54.921 110.034Z" fill="#0052FF"/>
                </svg>
              ) : (
                /* Farcaster logo - official brand color #8A63D2 */
                <svg
                  width="20"
                  height="20"
                  viewBox="0 0 1000 1000"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M257.778 155.556H742.222V844.444H671.111V528.889H670.414C662.554 441.677 589.258 373.333 500 373.333C410.742 373.333 337.446 441.677 329.586 528.889H328.889V844.444H257.778V155.556Z"
                    fill="#8A63D2"
                  />
                  <path
                    d="M128.889 253.333L157.778 351.111H182.222V746.667C169.949 746.667 160 756.616 160 768.889V795.556H155.556C143.283 795.556 133.333 805.505 133.333 817.778V844.444H382.222V817.778C382.222 805.505 372.273 795.556 360 795.556H355.556V768.889C355.556 756.616 345.606 746.667 333.333 746.667H306.667V253.333H128.889Z"
                    fill="#8A63D2"
                  />
                  <path
                    d="M675.556 746.667C663.283 746.667 653.333 756.616 653.333 768.889V795.556H648.889C636.616 795.556 626.667 805.505 626.667 817.778V844.444H875.556V817.778C875.556 805.505 865.606 795.556 853.333 795.556H848.889V768.889C848.889 756.616 838.94 746.667 826.667 746.667V351.111H851.111L880 253.333H702.222V746.667H675.556Z"
                    fill="#8A63D2"
                  />
                </svg>
              )}
            </div>
            <div className="flex-1 text-left">
              <Small className={`font-mono font-bold block ${isBaseApp ? "text-[#0052FF]" : "text-[#8A63D2]"}`}>
                {isSharing === "farcaster"
                  ? "Sharing..."
                  : isBaseApp
                    ? "Share to Feed"
                    : "Share to Farcaster"}
              </Small>
              <Small className="text-gray-500 font-mono text-[10px]">
                {isBaseApp ? "Post to your social feed" : "Cast to /netprotocol channel"}
              </Small>
            </div>
            <svg
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              className={isBaseApp ? "text-[#0052FF]/50" : "text-[#8A63D2]/50"}
            >
              <path d="M9 18l6-6-6-6" />
            </svg>
          </button>

          {/* X (Twitter) */}
          <button
            onClick={handleShareToX}
            disabled={isSharing !== null}
            className="w-full flex items-center gap-3 p-3 rounded-lg bg-white/5 border border-white/20 hover:bg-white/10 hover:border-white/30 transition-all disabled:opacity-50"
          >
            <div className="w-10 h-10 rounded-lg bg-white/10 flex items-center justify-center">
              <svg
                width="18"
                height="18"
                viewBox="0 0 24 24"
                fill="white"
              >
                <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
              </svg>
            </div>
            <div className="flex-1 text-left">
              <Small className="text-white font-mono font-bold block">
                {isSharing === "x" ? "Opening X..." : "Share to X"}
              </Small>
              <Small className="text-gray-500 font-mono text-[10px]">
                Post to your timeline
              </Small>
            </div>
            <svg
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="2"
              className="text-white/30"
            >
              <path d="M9 18l6-6-6-6" />
            </svg>
          </button>

          {/* Copy Link */}
          <button
            onClick={handleCopyLink}
            className={`w-full flex items-center gap-3 p-3 rounded-lg transition-all ${
              copied
                ? "bg-[#00ff00]/10 border border-[#00ff00]/50"
                : "bg-[#00ff00]/5 border border-[#00ff00]/20 hover:bg-[#00ff00]/10 hover:border-[#00ff00]/30"
            }`}
          >
            <div className={`w-10 h-10 rounded-lg flex items-center justify-center ${
              copied ? "bg-[#00ff00]/20" : "bg-[#00ff00]/10"
            }`}>
              {copied ? (
                <Check size={18} className="text-[#00ff00]" />
              ) : (
                <Link2 size={18} className="text-[#00ff00]" />
              )}
            </div>
            <div className="flex-1 text-left min-w-0">
              <Small className="text-[#00ff00] font-mono font-bold block">
                {copied ? "Copied!" : "Copy Link"}
              </Small>
              <Small className="text-gray-500 font-mono text-[10px] truncate block">
                {truncatedUrl}
              </Small>
            </div>
            {!copied && (
              <svg
                width="16"
                height="16"
                viewBox="0 0 24 24"
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                className="text-[#00ff00]/30"
              >
                <path d="M9 18l6-6-6-6" />
              </svg>
            )}
          </button>
        </div>
      </div>
    </div>
  );
}
src/features/app/components/skeleton-card.tsx
"use client";

/**
 * Skeleton loading cards for browse/discovery views
 * Shows animated placeholders while content is loading
 */
export function SkeletonBookCard() {
  return (
    <div className="bg-[#0a0a0a] border border-[#00ff00]/10 rounded-lg overflow-hidden animate-pulse">
      {/* Cover image skeleton */}
      <div className="aspect-[3/4] bg-[#1a1a1a]" />

      {/* Content skeleton */}
      <div className="p-3 space-y-2">
        {/* Title */}
        <div className="h-4 bg-[#1a1a1a] rounded w-3/4" />
        {/* Author */}
        <div className="h-3 bg-[#1a1a1a] rounded w-1/2" />
        {/* Stats row */}
        <div className="flex items-center gap-2 pt-1">
          <div className="h-3 bg-[#1a1a1a] rounded w-10" />
          <div className="h-3 bg-[#1a1a1a] rounded w-16" />
        </div>
      </div>
    </div>
  );
}

export function SkeletonStackCard() {
  return (
    <div className="bg-[#0a0a0a] border border-[#00ff00]/10 rounded-lg p-3 animate-pulse">
      <div className="flex items-start gap-3">
        {/* Rank badge skeleton */}
        <div className="w-8 h-8 bg-[#1a1a1a] rounded-full shrink-0" />

        {/* Content */}
        <div className="flex-1 space-y-2">
          <div className="h-4 bg-[#1a1a1a] rounded w-2/3" />
          <div className="h-3 bg-[#1a1a1a] rounded w-1/2" />
          <div className="flex items-center gap-2">
            <div className="w-4 h-4 bg-[#1a1a1a] rounded-full" />
            <div className="h-2 bg-[#1a1a1a] rounded w-20" />
          </div>
        </div>

        {/* Upvote count skeleton */}
        <div className="h-4 bg-[#1a1a1a] rounded w-8" />
      </div>
    </div>
  );
}

/**
 * Grid of skeleton cards for loading state
 */
export function SkeletonGrid({ count = 6 }: { count?: number }) {
  return (
    <div className="grid grid-cols-2 sm:grid-cols-3 gap-3 p-4">
      {Array.from({ length: count }).map((_, i) => (
        <SkeletonBookCard key={i} />
      ))}
    </div>
  );
}

export function SkeletonStackList({ count = 5 }: { count?: number }) {
  return (
    <div className="space-y-2 p-4">
      {Array.from({ length: count }).map((_, i) => (
        <SkeletonStackCard key={i} />
      ))}
    </div>
  );
}
src/features/app/components/social-platform-logos.tsx
"use client";

/**
 * Official brand logos for social platforms (white/monochrome versions)
 * Used in Social Archives section of the upload tab
 */

import { type SVGProps } from "react";

type LogoProps = SVGProps<SVGSVGElement> & {
  size?: number;
};

// X (Twitter) logo
export function XLogo({ size = 16, ...props }: LogoProps) {
  return (
    <svg
      viewBox="0 0 24 24"
      width={size}
      height={size}
      fill="currentColor"
      {...props}
    >
      <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
    </svg>
  );
}

// Farcaster logo (official)
export function FarcasterLogo({ size = 16, ...props }: LogoProps) {
  return (
    <svg
      viewBox="0 0 1000 1000"
      width={size}
      height={size}
      fill="currentColor"
      {...props}
    >
      <path d="M257.778 155.556H742.222V844.444H671.111V528.889H670.414C662.554 441.677 589.258 373.333 500 373.333C410.742 373.333 337.446 441.677 329.586 528.889H328.889V844.444H257.778V155.556Z" />
      <path d="M128.889 253.333L157.778 351.111H182.222V746.667C169.949 746.667 160 756.616 160 768.889V795.556H155.556C143.283 795.556 133.333 805.505 133.333 817.778V844.444H382.222V817.778C382.222 805.505 372.273 795.556 360 795.556H355.556V768.889C355.556 756.616 345.606 746.667 333.333 746.667H306.667V253.333H128.889Z" />
      <path d="M675.556 746.667C663.283 746.667 653.333 756.616 653.333 768.889V795.556H648.889C636.616 795.556 626.667 805.505 626.667 817.778V844.444H875.556V817.778C875.556 805.505 865.606 795.556 853.333 795.556H848.889V768.889C848.889 756.616 838.939 746.667 826.667 746.667V351.111H851.111L880 253.333H702.222V746.667H675.556Z" />
    </svg>
  );
}

// YouTube logo (play button)
export function YouTubeLogo({ size = 16, ...props }: LogoProps) {
  return (
    <svg
      viewBox="0 0 24 24"
      width={size}
      height={size}
      fill="currentColor"
      {...props}
    >
      <path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z" />
    </svg>
  );
}

// Instagram logo
export function InstagramLogo({ size = 16, ...props }: LogoProps) {
  return (
    <svg
      viewBox="0 0 24 24"
      width={size}
      height={size}
      fill="currentColor"
      {...props}
    >
      <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 2.618-6.98 6.98-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98 1.281.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98-1.281-.059-1.69-.073-4.949-.073zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z" />
    </svg>
  );
}

// TikTok logo
export function TikTokLogo({ size = 16, ...props }: LogoProps) {
  return (
    <svg
      viewBox="0 0 24 24"
      width={size}
      height={size}
      fill="currentColor"
      {...props}
    >
      <path d="M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z" />
    </svg>
  );
}

// Reddit logo
export function RedditLogo({ size = 16, ...props }: LogoProps) {
  return (
    <svg
      viewBox="0 0 24 24"
      width={size}
      height={size}
      fill="currentColor"
      {...props}
    >
      <path d="M12 0A12 12 0 0 0 0 12a12 12 0 0 0 12 12 12 12 0 0 0 12-12A12 12 0 0 0 12 0zm5.01 4.744c.688 0 1.25.561 1.25 1.249a1.25 1.25 0 0 1-2.498.056l-2.597-.547-.8 3.747c1.824.07 3.48.632 4.674 1.488.308-.309.73-.491 1.207-.491.968 0 1.754.786 1.754 1.754 0 .716-.435 1.333-1.01 1.614a3.111 3.111 0 0 1 .042.52c0 2.694-3.13 4.87-7.004 4.87-3.874 0-7.004-2.176-7.004-4.87 0-.183.015-.366.043-.534A1.748 1.748 0 0 1 4.028 12c0-.968.786-1.754 1.754-1.754.463 0 .898.196 1.207.49 1.207-.883 2.878-1.43 4.744-1.487l.885-4.182a.342.342 0 0 1 .14-.197.35.35 0 0 1 .238-.042l2.906.617a1.214 1.214 0 0 1 1.108-.701zM9.25 12C8.561 12 8 12.562 8 13.25c0 .687.561 1.248 1.25 1.248.687 0 1.248-.561 1.248-1.249 0-.688-.561-1.249-1.249-1.249zm5.5 0c-.687 0-1.248.561-1.248 1.25 0 .687.561 1.248 1.249 1.248.688 0 1.249-.561 1.249-1.249 0-.687-.562-1.249-1.25-1.249zm-5.466 3.99a.327.327 0 0 0-.231.094.33.33 0 0 0 0 .463c.842.842 2.484.913 2.961.913.477 0 2.105-.056 2.961-.913a.361.361 0 0 0 .029-.463.33.33 0 0 0-.464 0c-.547.533-1.684.73-2.512.73-.828 0-1.979-.196-2.512-.73a.326.326 0 0 0-.232-.095z" />
    </svg>
  );
}

// Bluesky logo (butterfly)
export function BlueskyLogo({ size = 16, ...props }: LogoProps) {
  return (
    <svg
      viewBox="0 0 24 24"
      width={size}
      height={size}
      fill="currentColor"
      {...props}
    >
      <path d="M12 10.8c-1.087-2.114-4.046-6.053-6.798-7.995C2.566.944 1.561 1.266.902 1.565.139 1.908 0 3.08 0 3.768c0 .69.378 5.65.624 6.479.815 2.736 3.713 3.66 6.383 3.364.136-.02.275-.039.415-.056-.138.022-.276.04-.415.056-3.912.58-7.387 2.005-2.83 7.078 5.013 5.19 6.87-1.113 7.823-4.308.953 3.195 2.05 9.271 7.733 4.308 4.267-4.308 1.172-6.498-2.74-7.078a8.741 8.741 0 0 1-.415-.056c.14.017.279.036.415.056 2.67.297 5.568-.628 6.383-3.364.246-.828.624-5.79.624-6.478 0-.69-.139-1.861-.902-2.206-.659-.298-1.664-.62-4.3 1.24C16.046 4.748 13.087 8.687 12 10.8z" />
    </svg>
  );
}

// Threads logo
export function ThreadsLogo({ size = 16, ...props }: LogoProps) {
  return (
    <svg
      viewBox="0 0 24 24"
      width={size}
      height={size}
      fill="currentColor"
      {...props}
    >
      <path d="M12.186 24h-.007c-3.581-.024-6.334-1.205-8.184-3.509C2.35 18.44 1.5 15.586 1.472 12.01v-.017c.03-3.579.879-6.43 2.525-8.482C5.845 1.205 8.6.024 12.18 0h.014c2.746.02 5.043.725 6.826 2.098 1.677 1.29 2.858 3.13 3.509 5.467l-2.04.569c-1.104-3.96-3.898-5.984-8.304-6.015-2.91.022-5.11.936-6.54 2.717C4.307 6.504 3.616 8.914 3.589 12c.027 3.086.718 5.496 2.057 7.164 1.43 1.783 3.631 2.698 6.54 2.717 2.623-.02 4.358-.631 5.8-2.045 1.647-1.613 1.618-3.593 1.09-4.798-.31-.71-.873-1.3-1.634-1.75-.192 1.352-.622 2.446-1.284 3.272-.886 1.102-2.14 1.704-3.73 1.79-1.202.065-2.361-.218-3.259-.801-1.063-.689-1.685-1.74-1.752-2.96-.065-1.182.408-2.256 1.33-3.022.88-.73 2.082-1.138 3.477-1.181 1.027-.032 1.98.092 2.853.372-.089-.69-.286-1.257-.585-1.684-.412-.59-1.053-.916-1.904-.968-1.32-.012-2.028.386-2.378.765l-1.465-1.44c.744-.758 1.916-1.406 3.783-1.441h.05c1.327.014 2.412.436 3.225 1.255.722.728 1.19 1.726 1.394 2.97.583.192 1.12.444 1.604.761 1.127.736 1.942 1.756 2.357 2.95.63 1.82.47 4.359-1.6 6.394-1.834 1.8-4.14 2.594-7.26 2.617z" />
    </svg>
  );
}

// LinkedIn logo
export function LinkedInLogo({ size = 16, ...props }: LogoProps) {
  return (
    <svg
      viewBox="0 0 24 24"
      width={size}
      height={size}
      fill="currentColor"
      {...props}
    >
      <path d="M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z" />
    </svg>
  );
}

// Component to render the appropriate logo
export function SocialPlatformLogo({
  platform,
  size = 16,
  className = "",
}: {
  platform: string;
  size?: number;
  className?: string;
}) {
  const props = { size, className };

  switch (platform) {
    case "twitter":
      return <XLogo {...props} />;
    case "farcaster":
      return <FarcasterLogo {...props} />;
    case "youtube":
      return <YouTubeLogo {...props} />;
    case "instagram":
      return <InstagramLogo {...props} />;
    case "tiktok":
      return <TikTokLogo {...props} />;
    case "reddit":
      return <RedditLogo {...props} />;
    case "bluesky":
      return <BlueskyLogo {...props} />;
    case "threads":
      return <ThreadsLogo {...props} />;
    case "linkedin":
      return <LinkedInLogo {...props} />;
    default:
      return <span className={className}>📱</span>;
  }
}
src/features/app/components/social-receipt-share-modal.tsx
"use client";

import { useState } from "react";
import { createPortal } from "react-dom";
import { Small, P } from "@neynar/ui";
import { safeComposeCast, safeOpenUrl, useAppMode } from "@/lib/app-mode";
import { Link2, Check } from "lucide-react";
import type { SocialPlatform } from "./social-receipt-upload";

// Platform display names
const PLATFORM_NAMES: Record<SocialPlatform, string> = {
  farcaster: "Farcaster",
  twitter: "Twitter/X",
  youtube: "YouTube",
  instagram: "Instagram",
  tiktok: "TikTok",
  reddit: "Reddit",
  bluesky: "Bluesky",
  threads: "Threads",
  linkedin: "LinkedIn",
  paragraph: "Paragraph",
};

interface SocialReceiptShareModalProps {
  isOpen: boolean;
  onClose: () => void;
  platform: SocialPlatform;
  author: string;
  contentKey: string;
  receiptImageUrl?: string;
}

export function SocialReceiptShareModal({
  isOpen,
  onClose,
  platform,
  author,
  contentKey,
  receiptImageUrl,
}: SocialReceiptShareModalProps) {
  const [isSharing, setIsSharing] = useState<"farcaster" | "x" | null>(null);
  const [showShareMenu, setShowShareMenu] = useState(false);
  const [imageLoaded, setImageLoaded] = useState(false);
  const [copied, setCopied] = useState(false);
  const appMode = useAppMode();
  const isBaseApp = appMode === "base-app";

  if (!isOpen) return null;

  // Build the share URL (the page that crawlers will see)
  const baseUrl = typeof window !== "undefined" ? window.location.origin : "";
  const source = isBaseApp ? "base" : "farcaster";
  const shareUrl = `${baseUrl}/share/social/${encodeURIComponent(contentKey)}?source=${source}`;

  // Platform name for display
  const platformName = PLATFORM_NAMES[platform] || "Social";

  // Share text - follows same pattern as other shares in the app
  const castText = `Check out this archived ${platformName} post by @${author} on Net Library!\n\nDecentralized onchain media powered by @netprotocol`;
  const xText = castText.replace("@netprotocol", "@netprotocolapp");

  const handleShareToFarcaster = async () => {
    setIsSharing("farcaster");
    setShowShareMenu(false);
    try {
      await safeComposeCast({
        text: castText,
        embeds: [shareUrl],
      });
      onClose();
    } catch (err) {
      console.error("Failed to share to Farcaster:", err);
    } finally {
      setIsSharing(null);
    }
  };

  const handleShareToX = async () => {
    setIsSharing("x");
    setShowShareMenu(false);
    try {
      // Build X share URL with source=web for browser deep link
      const xShareUrl = new URL(shareUrl);
      xShareUrl.searchParams.set("source", "web");

      const xIntentParams = new URLSearchParams({
        text: xText,
        url: xShareUrl.toString(),
      });
      const xIntentUrl = `https://twitter.com/intent/tweet?${xIntentParams.toString()}`;
      if (isBaseApp) {
        window.open(xIntentUrl, "_blank", "noopener,noreferrer");
      } else {
        await safeOpenUrl(xIntentUrl);
      }
      onClose();
    } catch (err) {
      console.error("Failed to share to X:", err);
    } finally {
      setIsSharing(null);
    }
  };

  const handleCopyLink = async () => {
    setShowShareMenu(false);
    try {
      await navigator.clipboard.writeText(shareUrl);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch (err) {
      console.error("Failed to copy link:", err);
      // Fallback for older browsers
      const textArea = document.createElement("textarea");
      textArea.value = shareUrl;
      document.body.appendChild(textArea);
      textArea.select();
      document.execCommand("copy");
      document.body.removeChild(textArea);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  // Truncate URL for display
  const truncatedUrl = (() => {
    try {
      const url = new URL(shareUrl);
      const path = url.pathname + url.search;
      const maxPathLength = 20;
      const truncatedPath = path.length > maxPathLength
        ? path.slice(0, maxPathLength) + "..."
        : path;
      return url.host.replace(/^www\./, "").slice(0, 25) + truncatedPath;
    } catch {
      return shareUrl.slice(0, 35) + "...";
    }
  })();

  const modalContent = (
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/95"
      onClick={onClose}
    >
      <div
        className="w-full max-w-md"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Close button */}
        <div className="flex justify-end mb-2">
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors"
          >
            ✕
          </button>
        </div>

        {/* Modal Card */}
        <div className="bg-[#0a0a0a] border border-cyan-500/30 rounded-xl overflow-hidden shadow-[0_0_30px_rgba(0,255,255,0.15)]">
          {/* Header */}
          <div className="p-3 border-b border-cyan-500/20 bg-cyan-500/5">
            <div className="flex items-center gap-2">
              <div className="w-2 h-2 rounded-full bg-cyan-400 animate-pulse shadow-[0_0_8px_#00ffff]" />
              <P className="text-cyan-400 font-mono text-sm font-bold">
                Share Your Receipt
              </P>
            </div>
            <Small className="text-gray-400 font-mono mt-1 block">
              @{author} on {platformName} - archived on Net Library
            </Small>
          </div>

          {/* Receipt Image Preview */}
          {receiptImageUrl && (
            <div className="p-4">
              <div className="relative rounded-lg overflow-hidden border-2 border-cyan-500/30 bg-black">
                {/* Loading state */}
                {!imageLoaded && (
                  <div className="absolute inset-0 flex items-center justify-center bg-black">
                    <div className="flex flex-col items-center gap-2">
                      <div className="w-8 h-8 border-2 border-cyan-500/30 border-t-cyan-500 rounded-full animate-spin" />
                      <Small className="text-cyan-500/50 font-mono">Loading receipt...</Small>
                    </div>
                  </div>
                )}
                {/* The receipt image */}
                <img
                  src={receiptImageUrl}
                  alt="Receipt preview"
                  className={`w-full aspect-[3/2] object-cover transition-opacity duration-300 ${imageLoaded ? 'opacity-100' : 'opacity-0'}`}
                  onLoad={() => setImageLoaded(true)}
                  onError={() => setImageLoaded(true)}
                />
              </div>
            </div>
          )}

          {/* Share Actions */}
          <div className="p-4 pt-0 space-y-2 relative">
            {/* Primary share button with dropdown */}
            <button
              onClick={() => setShowShareMenu(!showShareMenu)}
              disabled={isSharing !== null}
              className={`w-full py-3 rounded-lg font-mono text-sm font-bold transition-all disabled:opacity-50 ${
                isBaseApp
                  ? "bg-[#0052FF] text-white hover:bg-[#0052FF]/90"
                  : "bg-cyan-500 text-black hover:bg-cyan-400"
              }`}
            >
              {isSharing ? "Sharing..." : "Share Receipt ▾"}
            </button>

            {/* Share dropdown menu */}
            {showShareMenu && (
              <>
                <div className="fixed inset-0 z-40" onClick={() => setShowShareMenu(false)} />
                <div className="absolute bottom-full left-4 right-4 mb-2 bg-black border border-cyan-500/30 rounded-lg overflow-hidden z-50 shadow-lg">
                  <button
                    onClick={handleShareToFarcaster}
                    className={`w-full px-4 py-3 text-left text-sm font-mono flex items-center gap-3 transition-colors ${
                      isBaseApp
                        ? "hover:bg-[#0052FF]/20 text-[#0052FF]"
                        : "hover:bg-[#8A63D2]/20 text-[#8A63D2]"
                    }`}
                  >
                    {isBaseApp ? (
                      <svg width="18" height="18" viewBox="0 0 111 111" fill="none">
                        <path d="M54.921 110.034C85.359 110.034 110.034 85.402 110.034 55.017C110.034 24.6319 85.359 0 54.921 0C26.0432 0 2.35281 22.1714 0 50.3923H72.8467V59.6416H0C2.35281 87.8625 26.0432 110.034 54.921 110.034Z" fill="#0052FF"/>
                      </svg>
                    ) : (
                      <svg width="18" height="18" viewBox="0 0 1000 1000" fill="#8A63D2">
                        <path d="M257.778 155.556H742.222V844.445H671.111V528.889H670.414C662.554 441.677 589.258 373.333 500 373.333C410.742 373.333 337.446 441.677 329.586 528.889H328.889V844.445H257.778V155.556Z"/>
                        <path d="M128.889 253.333L157.778 351.111H182.222V746.667C169.949 746.667 160 756.616 160 768.889V795.556H155.556C143.283 795.556 133.333 805.505 133.333 817.778V844.445H382.222V817.778C382.222 805.505 372.273 795.556 360 795.556H355.556V768.889C355.556 756.616 345.606 746.667 333.333 746.667H306.667V253.333H128.889Z"/>
                        <path d="M675.556 746.667C663.283 746.667 653.333 756.616 653.333 768.889V795.556H648.889C636.616 795.556 626.667 805.505 626.667 817.778V844.445H875.556V817.778C875.556 805.505 865.606 795.556 853.333 795.556H848.889V768.889C848.889 756.616 838.94 746.667 826.667 746.667V351.111H851.111L880 253.333H702.222V746.667H675.556Z"/>
                      </svg>
                    )}
                    {isBaseApp ? "Share to Feed" : "Share to Farcaster"}
                  </button>
                  <button
                    onClick={handleShareToX}
                    className="w-full px-4 py-3 text-left text-sm font-mono flex items-center gap-3 hover:bg-white/10 text-white transition-colors border-t border-gray-800"
                  >
                    <svg width="16" height="16" viewBox="0 0 24 24" fill="white">
                      <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                    </svg>
                    Share to X
                  </button>
                  <button
                    onClick={handleCopyLink}
                    className="w-full px-4 py-3 text-left text-sm font-mono flex items-center gap-3 hover:bg-cyan-500/10 text-cyan-400 transition-colors border-t border-gray-800"
                  >
                    {copied ? (
                      <Check size={16} className="text-cyan-400" />
                    ) : (
                      <Link2 size={16} className="text-cyan-400" />
                    )}
                    <div className="flex-1 min-w-0">
                      <span className="block">{copied ? "Copied!" : "Copy Link"}</span>
                      <span className="block text-[10px] text-gray-500 truncate">{truncatedUrl}</span>
                    </div>
                  </button>
                </div>
              </>
            )}

            {/* Cancel button */}
            <button
              onClick={onClose}
              className="w-full py-2 rounded-lg text-gray-500 font-mono text-sm hover:text-gray-400 transition-colors"
            >
              Cancel
            </button>
          </div>
        </div>
      </div>
    </div>
  );

  // Use portal to render at document root
  if (typeof document === "undefined") return null;
  return createPortal(modalContent, document.body);
}
src/features/app/components/social-receipt-upload.tsx
"use client";

import { useState, useCallback, useEffect, useRef } from "react";
import { Card, CardContent, Button, P, Small, H4 } from "@neynar/ui";
import { useCast } from "@/neynar-web-sdk/src/neynar/api-hooks/hooks/cast";
import type { Category, Stack } from "@/features/app/types";
import type { ContentType } from "./cdn-link-upload";
import { SocialPlatformLogo } from "./social-platform-logos";
import { LibraryIcon, WarningIcon, ClipboardIcon, UserIcon, ReceiptIcon, GlobeIcon, LockIcon, CheckIcon } from "@/components/icons/net-library-icons";

// Supported platforms
export type SocialPlatform =
  | "farcaster"
  | "twitter"
  | "youtube"
  | "instagram"
  | "tiktok"
  | "reddit"
  | "bluesky"
  | "threads"
  | "linkedin"
  | "paragraph";

// Platform display info
export const PLATFORM_INFO: Record<SocialPlatform, {
  name: string;
  icon: string;
  color: string;
  bgColor: string;
  borderColor: string;
}> = {
  farcaster: { name: "Farcaster", icon: "🟣", color: "text-purple-400", bgColor: "bg-purple-500/20", borderColor: "border-purple-500/30" },
  twitter: { name: "Twitter/X", icon: "𝕏", color: "text-blue-400", bgColor: "bg-blue-500/20", borderColor: "border-blue-500/30" },
  youtube: { name: "YouTube", icon: "▶️", color: "text-red-400", bgColor: "bg-red-500/20", borderColor: "border-red-500/30" },
  instagram: { name: "Instagram", icon: "📸", color: "text-pink-400", bgColor: "bg-pink-500/20", borderColor: "border-pink-500/30" },
  tiktok: { name: "TikTok", icon: "🎵", color: "text-cyan-400", bgColor: "bg-cyan-500/20", borderColor: "border-cyan-500/30" },
  reddit: { name: "Reddit", icon: "🤖", color: "text-orange-400", bgColor: "bg-orange-500/20", borderColor: "border-orange-500/30" },
  bluesky: { name: "Bluesky", icon: "🦋", color: "text-sky-400", bgColor: "bg-sky-500/20", borderColor: "border-sky-500/30" },
  threads: { name: "Threads", icon: "🧵", color: "text-gray-300", bgColor: "bg-gray-500/20", borderColor: "border-gray-500/30" },
  linkedin: { name: "LinkedIn", icon: "💼", color: "text-blue-500", bgColor: "bg-blue-600/20", borderColor: "border-blue-600/30" },
  paragraph: { name: "Paragraph", icon: "📝", color: "text-emerald-400", bgColor: "bg-emerald-500/20", borderColor: "border-emerald-500/30" },
};

// Types for social content
interface SocialAuthor {
  displayName: string;
  username: string;
  avatarUrl?: string;
  fid?: number; // Farcaster ID (for casts)
  verified?: boolean;
}

export interface SocialContent {
  platform: SocialPlatform;
  id: string; // Platform-specific ID
  url: string; // Original URL
  text: string;
  author: SocialAuthor;
  timestamp: Date;
  images?: string[];
  thumbnailUrl?: string; // For video content (YouTube, TikTok)
  likes?: number;
  reposts?: number; // recasts, retweets, shares
  replies?: number;
  views?: number; // For video platforms
  duration?: string; // For video content
  quotedContent?: SocialContent; // For quote tweets/casts
  subreddit?: string; // Reddit-specific
  score?: number; // Reddit upvotes
}

interface SocialReceiptUploadProps {
  categories: Category[];
  stacks: Stack[];
  isLoadingStacks: boolean;
  onUpload: (data: {
    cdnUrl: string; // Will be the receipt image URL
    contentType: ContentType;
    title: string;
    author: string;
    selectedCategories: string[];
    selectedStackIds: string[];
    coverArtUrl?: string;
    // Social-specific metadata
    socialPlatform: SocialPlatform;
    originalUrl: string;
    socialContent: SocialContent;
  }) => Promise<void>;
  isUploading: boolean;
}

// URL pattern matching for all platforms
function detectPlatform(url: string): SocialPlatform | null {
  const patterns: { platform: SocialPlatform; pattern: RegExp }[] = [
    // Twitter/X
    { platform: "twitter", pattern: /^https?:\/\/(twitter\.com|x\.com)\/\w+\/status\/\d+/i },
    // Farcaster (Warpcast)
    { platform: "farcaster", pattern: /^https?:\/\/warpcast\.com\/[\w.]+\/0x[a-f0-9]+/i },
    // YouTube (videos, shorts, live)
    { platform: "youtube", pattern: /^https?:\/\/(www\.)?(youtube\.com\/(watch|shorts|live)|youtu\.be\/)/i },
    // Instagram (posts, reels, p)
    { platform: "instagram", pattern: /^https?:\/\/(www\.)?instagram\.com\/(p|reel|reels)\/[\w-]+/i },
    // TikTok (videos)
    { platform: "tiktok", pattern: /^https?:\/\/(www\.)?(tiktok\.com\/@[\w.]+\/video\/|vm\.tiktok\.com\/)/i },
    // Reddit (posts, comments)
    { platform: "reddit", pattern: /^https?:\/\/(www\.|old\.)?reddit\.com\/r\/\w+\/(comments|s)\/\w+/i },
    // Bluesky
    { platform: "bluesky", pattern: /^https?:\/\/bsky\.app\/profile\/[\w.]+\/post\/\w+/i },
    // Threads
    { platform: "threads", pattern: /^https?:\/\/(www\.)?threads\.net\/@[\w.]+\/post\/\w+/i },
    // LinkedIn (posts)
    { platform: "linkedin", pattern: /^https?:\/\/(www\.)?linkedin\.com\/(posts|feed\/update|pulse)\//i },
    // Paragraph (articles and posts)
    { platform: "paragraph", pattern: /paragraph\.xyz/i },
  ];

  for (const { platform, pattern } of patterns) {
    if (pattern.test(url)) return platform;
  }
  return null;
}

// Extract IDs from URLs
function extractContentId(url: string, platform: SocialPlatform): string | null {
  switch (platform) {
    case "twitter": {
      const match = url.match(/(?:twitter\.com|x\.com)\/\w+\/status\/(\d+)/i);
      return match ? match[1] : null;
    }
    case "farcaster": {
      const match = url.match(/warpcast\.com\/[\w.]+\/(0x[a-f0-9]+)/i);
      return match ? match[1] : null;
    }
    case "youtube": {
      // Handle youtube.com/watch?v=, youtu.be/, youtube.com/shorts/, youtube.com/live/
      let match = url.match(/[?&]v=([a-zA-Z0-9_-]{11})/);
      if (match) return match[1];
      match = url.match(/youtu\.be\/([a-zA-Z0-9_-]{11})/);
      if (match) return match[1];
      match = url.match(/youtube\.com\/(shorts|live)\/([a-zA-Z0-9_-]{11})/);
      if (match) return match[2];
      return null;
    }
    case "instagram": {
      const match = url.match(/instagram\.com\/(p|reel|reels)\/([\w-]+)/i);
      return match ? match[2] : null;
    }
    case "tiktok": {
      const match = url.match(/video\/(\d+)/i);
      return match ? match[1] : null;
    }
    case "reddit": {
      const match = url.match(/comments\/(\w+)/i);
      return match ? match[1] : null;
    }
    case "bluesky": {
      const match = url.match(/post\/(\w+)/i);
      return match ? match[1] : null;
    }
    case "threads": {
      const match = url.match(/post\/(\w+)/i);
      return match ? match[1] : null;
    }
    case "linkedin": {
      // LinkedIn URLs are complex, just use a hash of the URL
      return url.split("/").pop()?.split("?")[0] || null;
    }
    default:
      return null;
  }
}

// Stack selection dropdown (reused from upload-tab)
function StackSelectionDropdown({
  stacks,
  selectedStackIds,
  onToggle,
  isLoading,
}: {
  stacks: Stack[];
  selectedStackIds: string[];
  onToggle: (stackId: string) => void;
  isLoading: boolean;
}) {
  const [isOpen, setIsOpen] = useState(false);

  if (isLoading) {
    return (
      <div className="w-full px-3 py-2.5 rounded-lg bg-black border border-[#00ff00]/30 text-gray-500 font-mono text-sm">
        Loading your stacks...
      </div>
    );
  }

  if (stacks.length === 0) {
    return (
      <div className="w-full px-3 py-2.5 rounded-lg bg-black border border-[#00ff00]/20 text-gray-500 font-mono text-sm">
        No stacks yet - create one in the Stacks tab!
      </div>
    );
  }

  const selectedStacks = stacks.filter(s => selectedStackIds.includes(s.id));

  return (
    <div className="relative">
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="w-full px-3 py-2.5 rounded-lg bg-black border border-[#00ff00]/30 text-left font-mono focus:outline-none focus:border-[#00ff00] transition-colors flex items-center justify-between"
      >
        <div className="flex-1 min-w-0">
          {selectedStacks.length === 0 ? (
            <span className="text-gray-500 text-sm">Select stacks (optional)...</span>
          ) : (
            <div className="flex flex-wrap gap-1">
              {selectedStacks.map(stack => (
                <span
                  key={stack.id}
                  className="inline-flex items-center gap-1 px-2 py-0.5 bg-purple-500/20 text-purple-400 rounded text-xs"
                >
                  <LibraryIcon size={12} /> {stack.name}
                </span>
              ))}
            </div>
          )}
        </div>
        <svg
          className={`w-5 h-5 text-[#00ff00] transition-transform shrink-0 ml-2 ${isOpen ? "rotate-180" : ""}`}
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {isOpen && (
        <>
          {/* Backdrop to close on click outside */}
          <div
            className="fixed inset-0 z-10"
            onClick={() => setIsOpen(false)}
          />
          <div className="absolute top-full left-0 right-0 mt-1 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg overflow-hidden z-20">
            <div className="max-h-40 overflow-y-auto">
              {stacks.map((stack) => {
                const isSelected = selectedStackIds.includes(stack.id);
                return (
                  <button
                    key={stack.id}
                    type="button"
                    onClick={() => {
                      onToggle(stack.id);
                      // Keep dropdown open for multi-select
                    }}
                    className={`w-full px-3 py-2.5 text-left font-mono text-sm flex items-center gap-2 transition-colors ${
                      isSelected
                        ? "bg-purple-500/20 text-purple-400"
                        : "text-gray-300 hover:bg-[#1a1a1a] hover:text-white"
                    }`}
                  >
                    <span className={`w-5 h-5 rounded border-2 flex items-center justify-center shrink-0 ${
                      isSelected ? 'border-purple-500 bg-purple-500' : 'border-gray-600'
                    }`}>
                      {isSelected && <CheckIcon size={10} className="text-white" />}
                    </span>
                    <LibraryIcon size={14} className="text-purple-400" />
                    <span className="truncate">{stack.name}</span>
                    {stack.isPrivate && <LockIcon size={12} className="text-gray-500 ml-auto" />}
                  </button>
                );
              })}
            </div>
            {/* Done button for mobile */}
            <button
              type="button"
              onClick={() => setIsOpen(false)}
              className="w-full px-3 py-2 text-center font-mono text-sm text-[#00ff00] bg-[#00ff00]/10 border-t border-[#00ff00]/20 hover:bg-[#00ff00]/20 transition-colors"
            >
              Done
            </button>
          </div>
        </>
      )}
    </div>
  );
}

// Category dropdown (simplified version)
function CategoryDropdown({
  categories,
  selectedCategories,
  onToggle,
}: {
  categories: Category[];
  selectedCategories: string[];
  onToggle: (categoryId: string) => void;
}) {
  const [isOpen, setIsOpen] = useState(false);
  const filteredCategories = categories.filter(c => c.id !== "all");
  const selectedCats = filteredCategories.filter(c => selectedCategories.includes(c.id));

  return (
    <div className="relative">
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="w-full px-3 py-2.5 rounded-lg bg-black border border-[#00ff00]/30 text-left font-mono focus:outline-none focus:border-[#00ff00] transition-colors flex items-center justify-between"
      >
        <div className="flex-1 min-w-0">
          {selectedCats.length === 0 ? (
            <span className="text-gray-500 text-sm">Select categories...</span>
          ) : (
            <div className="flex flex-wrap gap-1">
              {selectedCats.map(cat => (
                <span
                  key={cat.id}
                  className="inline-flex items-center gap-1 px-2 py-0.5 bg-[#00ff00]/20 text-[#00ff00] rounded text-xs"
                >
                  {cat.emoji} {cat.label}
                </span>
              ))}
            </div>
          )}
        </div>
        <svg
          className={`w-5 h-5 text-[#00ff00] transition-transform shrink-0 ml-2 ${isOpen ? "rotate-180" : ""}`}
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {isOpen && (
        <div className="absolute top-full left-0 right-0 mt-1 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg overflow-hidden z-20 max-h-64 overflow-y-auto">
          {filteredCategories.map((cat) => {
            const isSelected = selectedCategories.includes(cat.id);
            const isDisabled = !isSelected && selectedCategories.length >= 3;
            return (
              <button
                key={cat.id}
                type="button"
                onClick={() => {
                  if (!isDisabled) onToggle(cat.id);
                }}
                disabled={isDisabled}
                className={`w-full px-3 py-2.5 text-left font-mono text-sm flex items-center gap-2 transition-colors ${
                  isSelected
                    ? "bg-[#00ff00]/20 text-[#00ff00]"
                    : isDisabled
                    ? "text-gray-600 cursor-not-allowed"
                    : "text-gray-300 hover:bg-[#1a1a1a] hover:text-white"
                }`}
              >
                <span className={`w-5 h-5 rounded border-2 flex items-center justify-center shrink-0 ${
                  isSelected ? 'border-[#00ff00] bg-[#00ff00]' : 'border-gray-600'
                }`}>
                  {isSelected && <span className="text-black text-xs font-bold">✓</span>}
                </span>
                <span>{cat.emoji}</span>
                <span>{cat.label}</span>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

// Preview Card for social content - supports all platforms
function SocialPreviewCard({ content }: { content: SocialContent }) {
  const platformInfo = PLATFORM_INFO[content.platform];

  const formatDate = (date: Date) => {
    return new Intl.DateTimeFormat("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
      hour: "numeric",
      minute: "2-digit",
    }).format(date);
  };

  // Check if this is video content
  const isVideoContent = content.platform === "youtube" || content.platform === "tiktok";

  return (
    <Card className={`bg-[#0a0a0a] border-2 ${platformInfo.borderColor}`}>
      <CardContent className="p-4">
        {/* Platform badge */}
        <div className="flex items-center justify-between mb-3">
          <div className={`flex items-center gap-2 px-2 py-1 rounded-full text-xs font-mono ${platformInfo.bgColor} ${platformInfo.color}`}>
            <SocialPlatformLogo platform={content.platform} size={14} className="text-white" />
            {platformInfo.name}
          </div>
          <Small className="text-gray-500 font-mono text-[10px]">
            {formatDate(content.timestamp)}
          </Small>
        </div>

        {/* Reddit subreddit */}
        {content.subreddit && (
          <div className="mb-2">
            <Small className="text-orange-400 font-mono">r/{content.subreddit}</Small>
          </div>
        )}

        {/* Author */}
        <div className="flex items-center gap-3 mb-3">
          {content.author?.avatarUrl ? (
            <img
              src={content.author.avatarUrl}
              alt={content.author?.displayName || 'Author'}
              className="w-10 h-10 rounded-full border border-gray-700"
            />
          ) : (
            <div className="w-10 h-10 rounded-full bg-gray-700 flex items-center justify-center">
              <UserIcon size={20} className="text-gray-400" />
            </div>
          )}
          <div className="flex-1 min-w-0">
            <div className="flex items-center gap-1">
              <P className="font-mono text-white font-bold truncate text-sm">
                {content.author?.displayName || 'Unknown'}
              </P>
              {content.author?.verified && (
                <span className="text-[#00ff00]">✓</span>
              )}
            </div>
            <Small className="text-gray-500 font-mono">
              {content.platform === "reddit" ? `u/${content.author?.username || 'unknown'}` : `@${content.author?.username || 'unknown'}`}
            </Small>
          </div>
        </div>

        {/* Content text */}
        {content.text && (
          <P className="text-white font-mono text-sm whitespace-pre-wrap mb-3 leading-relaxed line-clamp-6">
            {content.text}
          </P>
        )}

        {/* Video thumbnail for YouTube/TikTok */}
        {isVideoContent && content.thumbnailUrl && (
          <div className="relative aspect-video rounded-lg overflow-hidden border border-gray-700 mb-3">
            <img src={content.thumbnailUrl} alt="" className="w-full h-full object-cover" />
            <div className="absolute inset-0 flex items-center justify-center bg-black/40">
              <div className="w-14 h-14 rounded-full bg-white/90 flex items-center justify-center">
                <span className="text-2xl ml-1">▶</span>
              </div>
            </div>
            {content.duration && (
              <div className="absolute bottom-2 right-2 px-2 py-0.5 bg-black/80 rounded text-white text-xs font-mono">
                {content.duration}
              </div>
            )}
          </div>
        )}

        {/* Images if any (non-video platforms) */}
        {!isVideoContent && content.images && content.images.length > 0 && (
          <div className={`grid gap-2 mb-3 ${
            content.images.length === 1 ? "grid-cols-1" :
            content.images.length === 2 ? "grid-cols-2" :
            "grid-cols-2"
          }`}>
            {content.images.slice(0, 4).map((img, i) => (
              <div key={i} className={`relative rounded-lg overflow-hidden border border-gray-700 bg-[#0a0a0a] ${
                content.images!.length === 1 ? "max-h-64" : "aspect-video"
              }`}>
                <img
                  src={img}
                  alt=""
                  className={`w-full h-full ${
                    content.images!.length === 1 ? "object-contain" : "object-cover"
                  }`}
                />
              </div>
            ))}
          </div>
        )}

        {/* Timestamp footer */}
        <div className="pt-3 border-t border-gray-800">
          <Small className="text-gray-500 font-mono">
            Posted {content.timestamp.toLocaleDateString()}
          </Small>
        </div>
      </CardContent>
    </Card>
  );
}

export function SocialReceiptUpload({
  categories,
  stacks,
  isLoadingStacks,
  onUpload,
  isUploading,
}: SocialReceiptUploadProps) {
  const [url, setUrl] = useState("");
  const [detectedPlatform, setDetectedPlatform] = useState<SocialPlatform | null>(null);
  const [socialContent, setSocialContent] = useState<SocialContent | null>(null);
  const [isFetching, setIsFetching] = useState(false);
  const [fetchError, setFetchError] = useState<string | null>(null);
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [selectedStackIds, setSelectedStackIds] = useState<string[]>([]);
  const [isGeneratingReceipt, setIsGeneratingReceipt] = useState(false);

  // Tracks whether we have already auto-populated from castData for the current URL.
  // Prevents a castData refetch from overwriting user edits made after the initial populate.
  const hasAutoPopulatedRef = useRef(false);

  // For Farcaster cast fetching via Neynar API
  const castIdentifier = detectedPlatform === "farcaster" ? url : "";
  const { data: castData, isLoading: isCastLoading, error: castError } = useCast(
    castIdentifier,
    { type: "url" },
    { enabled: !!castIdentifier && detectedPlatform === "farcaster" }
  );

  // Reset the auto-populate guard whenever the URL or detected platform changes.
  // Covers both: user pasting a new URL, and user switching platform tabs while
  // a URL is already in the input (which changes detectedPlatform independently).
  useEffect(() => {
    hasAutoPopulatedRef.current = false;
  }, [url, detectedPlatform]);

  // Handle URL input change
  const handleUrlChange = useCallback((newUrl: string) => {
    setUrl(newUrl);
    setFetchError(null);
    setSocialContent(null);

    const platform = detectPlatform(newUrl);
    setDetectedPlatform(platform);
  }, []);

  // Fetch content when user clicks "Fetch"
  const handleFetch = useCallback(async () => {
    if (!detectedPlatform || !url) return;

    setIsFetching(true);
    setFetchError(null);

    try {
      if (detectedPlatform === "farcaster") {
        // Use Neynar API hook — it fetches asynchronously.
        // If the hook is still loading, keep isFetching=true and let the
        // useEffect below auto-populate content once castData arrives.
        if (isCastLoading) {
          // Don't clear isFetching — the useEffect will handle it when data resolves
          return;
        }
        if (castData) {
          setSocialContent({
            platform: "farcaster",
            id: castData.hash,
            url: url,
            text: castData.text,
            author: {
              displayName: castData.author?.display_name || castData.author?.username || 'Unknown',
              username: castData.author?.username || 'unknown',
              avatarUrl: castData.author?.pfp_url,
              fid: castData.author?.fid,
              verified: castData.author?.power_badge,
            },
            timestamp: new Date(castData.timestamp),
            images: castData.embeds
              ?.filter((e): e is { url: string } => 'url' in e && typeof e.url === 'string')
              .filter(e => e.url.match(/\.(jpg|jpeg|png|gif|webp)/i))
              .map(e => e.url) || [],
            likes: castData.reactions?.likes_count,
            reposts: castData.reactions?.recasts_count,
            replies: castData.replies?.count,
          });
        } else if (castError) {
          setFetchError("Failed to fetch cast. Make sure the URL is correct.");
        } else {
          setFetchError("Could not load cast. Try again.");
        }
      } else {
        // Use our unified social API for all other platforms
        const contentId = extractContentId(url, detectedPlatform);
        if (!contentId) {
          setFetchError(`Invalid ${PLATFORM_INFO[detectedPlatform].name} URL`);
          setIsFetching(false);
          return;
        }

        const response = await fetch(`/api/social/fetch?platform=${detectedPlatform}&url=${encodeURIComponent(url)}`);
        const data = await response.json();

        if (!response.ok) {
          setFetchError(data.error || `Failed to fetch ${PLATFORM_INFO[detectedPlatform].name} content`);
          setIsFetching(false);
          return;
        }

        // Parse timestamp if it's a string
        if (data.content?.timestamp && typeof data.content.timestamp === 'string') {
          data.content.timestamp = new Date(data.content.timestamp);
        }

        setSocialContent(data.content);
      }
    } catch (err) {
      setFetchError(err instanceof Error ? err.message : "Failed to fetch content");
    }

    setIsFetching(false);
  }, [detectedPlatform, url, castData, castError, isCastLoading]);

  // Auto-populate content when the Farcaster useCast hook resolves after a pending fetch.
  // hasAutoPopulatedRef prevents a subsequent refetch from overwriting user edits.
  useEffect(() => {
    if (
      detectedPlatform === "farcaster" &&
      castData &&
      isFetching &&
      !socialContent &&
      !hasAutoPopulatedRef.current
    ) {
      hasAutoPopulatedRef.current = true;
      setSocialContent({
        platform: "farcaster",
        id: castData.hash,
        url: url,
        text: castData.text,
        author: {
          displayName: castData.author?.display_name || castData.author?.username || 'Unknown',
          username: castData.author?.username || 'unknown',
          avatarUrl: castData.author?.pfp_url,
          fid: castData.author?.fid,
          verified: castData.author?.power_badge,
        },
        timestamp: new Date(castData.timestamp),
        images: castData.embeds
          ?.filter((e): e is { url: string } => 'url' in e && typeof e.url === 'string')
          .filter(e => e.url.match(/\.(jpg|jpeg|png|gif|webp)/i))
          .map(e => e.url) || [],
        likes: castData.reactions?.likes_count,
        reposts: castData.reactions?.recasts_count,
        replies: castData.replies?.count,
      });
      setIsFetching(false);
    }
  }, [castData, detectedPlatform, isFetching, socialContent, url]);

  // Toggle category selection
  const toggleCategory = (categoryId: string) => {
    setSelectedCategories(prev => {
      if (prev.includes(categoryId)) {
        return prev.filter(id => id !== categoryId);
      }
      if (prev.length >= 3) return prev;
      return [...prev, categoryId];
    });
  };

  // Toggle stack selection
  const toggleStack = (stackId: string) => {
    setSelectedStackIds(prev =>
      prev.includes(stackId)
        ? prev.filter(id => id !== stackId)
        : [...prev, stackId]
    );
  };

  // Handle archive upload
  const handleArchive = async () => {
    if (!socialContent) return;

    setIsGeneratingReceipt(true);

    try {
      // Generate the receipt image via API
      const receiptResponse = await fetch("/api/social/receipt", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          content: socialContent,
        }),
      });

      if (!receiptResponse.ok) {
        throw new Error("Failed to generate receipt image");
      }

      const receiptData = await receiptResponse.json();

      // Build title for the archived item using the full PLATFORM_INFO map
      const platformName = PLATFORM_INFO[socialContent.platform]?.name || socialContent.platform;
      const title = `${socialContent.author?.displayName || 'Unknown'} on ${platformName}`;

      // Call the parent upload handler
      await onUpload({
        cdnUrl: receiptData.imageUrl, // The generated receipt image URL
        contentType: "image" as ContentType,
        title,
        author: `@${socialContent.author?.username || 'unknown'}`,
        selectedCategories,
        selectedStackIds,
        coverArtUrl: receiptData.imageUrl,
        socialPlatform: socialContent.platform,
        originalUrl: socialContent.url,
        socialContent,
      });
    } catch (err) {
      setFetchError(err instanceof Error ? err.message : "Failed to archive");
    }

    setIsGeneratingReceipt(false);
  };

  // Reset state
  const handleReset = () => {
    setUrl("");
    setDetectedPlatform(null);
    setSocialContent(null);
    setFetchError(null);
    setSelectedCategories([]);
    setSelectedStackIds([]);
  };

  const isLoading = isFetching || isCastLoading;

  return (
    <div className="space-y-4">
      {/* Header */}
      <div className="flex items-center gap-2 mb-2">
        <ReceiptIcon size={20} className="text-[#00ff00]" />
        <H4 className="text-[#00ff00] font-mono">Archive Social Post</H4>
      </div>

      <Small className="text-gray-400 font-mono block -mt-2 mb-4">
        Create a permanent, hyperlinked receipt of any social post.
      </Small>

      {!socialContent ? (
        // URL Input Stage
        <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
          <CardContent className="p-4 space-y-4">
            {/* URL Input */}
            <div>
              <Small className="text-[#00ff00] font-mono mb-2 block">Paste URL</Small>
              <input
                type="url"
                value={url}
                onChange={(e) => handleUrlChange(e.target.value)}
                placeholder="Paste any social media post URL..."
                className="w-full px-3 py-3 rounded-lg bg-black border border-[#00ff00]/30 text-white font-mono placeholder:text-gray-600 focus:border-[#00ff00] focus:ring-1 focus:ring-[#00ff00] focus:outline-none"
              />
            </div>

            {/* Platform detection indicator */}
            {url && (
              <div className={`flex items-center gap-2 px-3 py-2 rounded-lg ${
                detectedPlatform
                  ? `${PLATFORM_INFO[detectedPlatform].bgColor} border ${PLATFORM_INFO[detectedPlatform].borderColor}`
                  : "bg-yellow-500/10 border border-yellow-500/30"
              }`}>
                {detectedPlatform ? (
                  <>
                    <SocialPlatformLogo platform={detectedPlatform} size={18} className="text-white" />
                    <Small className={`font-mono ${PLATFORM_INFO[detectedPlatform].color}`}>
                      {PLATFORM_INFO[detectedPlatform].name} content detected
                    </Small>
                  </>
                ) : (
                  <>
                    <WarningIcon size={18} className="text-yellow-400" />
                    <Small className="text-yellow-400 font-mono">
                      Unrecognized URL format
                    </Small>
                  </>
                )}
              </div>
            )}

            {/* Error message */}
            {fetchError && (
              <div className="px-3 py-2 rounded-lg bg-red-500/10 border border-red-500/30">
                <Small className="text-red-400 font-mono">{fetchError}</Small>
              </div>
            )}

            {/* Fetch button */}
            <Button
              onClick={handleFetch}
              disabled={!detectedPlatform || isLoading}
              className="w-full bg-[#00ff00] text-black hover:bg-[#00ff00]/80 font-mono disabled:opacity-50"
            >
              {isLoading ? (
                <span className="flex items-center justify-center gap-2">
                  <span className="w-4 h-4 border-2 border-black/30 border-t-black rounded-full animate-spin" />
                  Fetching...
                </span>
              ) : (
                "Fetch Post"
              )}
            </Button>

            {/* Supported platforms info */}
            <div className="pt-3 border-t border-gray-800">
              <Small className="text-gray-500 font-mono text-[10px] block mb-2">
                Supported Platforms:
              </Small>
              <div className="flex flex-wrap gap-x-3 gap-y-1.5">
                {(Object.keys(PLATFORM_INFO) as SocialPlatform[]).map((platform) => (
                  <div key={platform} className="flex items-center gap-1.5">
                    <SocialPlatformLogo platform={platform} size={12} className="text-white" />
                    <Small className="text-gray-400 font-mono text-[10px]">{PLATFORM_INFO[platform].name}</Small>
                  </div>
                ))}
              </div>
            </div>
          </CardContent>
        </Card>
      ) : (
        // Preview & Archive Stage
        <div className="space-y-4">
          {/* Preview Card */}
          <div>
            <div className="flex items-center justify-between mb-2">
              <Small className="text-[#00ff00] font-mono uppercase tracking-wider text-[10px]">
                Preview
              </Small>
              <button
                onClick={handleReset}
                className="text-gray-500 hover:text-white font-mono text-xs"
              >
                ← Change URL
              </button>
            </div>
            <SocialPreviewCard content={socialContent} />
          </div>

          {/* Metadata Form */}
          <Card className="bg-[#0a0a0a] border border-[#00ff00]/20">
            <CardContent className="p-4 space-y-4">
              {/* Category Selection */}
              <div>
                <div className="flex items-center justify-between mb-1">
                  <Small className="text-[#00ff00] font-mono">Category</Small>
                  <Small className="text-gray-500 font-mono text-[10px]">
                    {selectedCategories.length}/3 selected
                  </Small>
                </div>
                <CategoryDropdown
                  categories={categories}
                  selectedCategories={selectedCategories}
                  onToggle={toggleCategory}
                />
              </div>

              {/* Stack Selection */}
              <div>
                <div className="flex items-center justify-between mb-1">
                  <Small className="text-[#00ff00] font-mono">Add to Stack (optional)</Small>
                  {selectedStackIds.length > 0 && (
                    <Small className="text-purple-400 font-mono text-[10px]">
                      {selectedStackIds.length} selected
                    </Small>
                  )}
                </div>
                <StackSelectionDropdown
                  stacks={stacks}
                  selectedStackIds={selectedStackIds}
                  onToggle={toggleStack}
                  isLoading={isLoadingStacks}
                />
              </div>

              {/* Info about what will be archived */}
              <div className="bg-[#00ff00]/5 border border-[#00ff00]/20 rounded-lg p-3">
                <Small className="text-[#00ff00]/80 font-mono text-[11px] flex items-center gap-1 mb-2">
                  <ClipboardIcon size={12} /> What gets archived:
                </Small>
                <ul className="space-y-1">
                  <li className="text-gray-400 font-mono text-[10px] flex items-center gap-2">
                    <span className="text-[#00ff00]">✓</span> Author info (name, handle, avatar)
                  </li>
                  <li className="text-gray-400 font-mono text-[10px] flex items-center gap-2">
                    <span className="text-[#00ff00]">✓</span> Full text content
                  </li>
                  <li className="text-gray-400 font-mono text-[10px] flex items-center gap-2">
                    <span className="text-[#00ff00]">✓</span> Timestamp
                  </li>
                  <li className="text-gray-400 font-mono text-[10px] flex items-center gap-2">
                    <span className="text-[#00ff00]">✓</span> Engagement stats (likes, reposts, replies)
                  </li>
                  <li className="text-gray-400 font-mono text-[10px] flex items-center gap-2">
                    <span className="text-[#00ff00]">✓</span> Embedded images
                  </li>
                  <li className="text-gray-400 font-mono text-[10px] flex items-center gap-2">
                    <span className="text-[#00ff00]">✓</span> Hyperlink to original
                  </li>
                </ul>
              </div>

              {/* Visibility note */}
              <div className="flex items-center gap-2 px-3 py-2 rounded-lg bg-[#00ff00]/5 border border-[#00ff00]/20">
                <GlobeIcon size={16} className="text-[#00ff00]" />
                <Small className="text-gray-400 font-mono text-[10px]">
                  <span className="text-[#00ff00]">Public by default.</span> Add to a private stack to keep hidden.
                </Small>
              </div>
            </CardContent>
          </Card>

          {/* Archive Button */}
          <Button
            onClick={handleArchive}
            disabled={isUploading || isGeneratingReceipt}
            className="w-full bg-[#00ff00] text-black hover:bg-[#00ff00]/80 font-mono h-12 disabled:opacity-50"
          >
            {isGeneratingReceipt ? (
              <span className="flex items-center justify-center gap-2">
                <span className="w-4 h-4 border-2 border-black/30 border-t-black rounded-full animate-spin" />
                Generating Receipt...
              </span>
            ) : isUploading ? (
              <span className="flex items-center justify-center gap-2">
                <span className="w-4 h-4 border-2 border-black/30 border-t-black rounded-full animate-spin" />
                Archiving...
              </span>
            ) : (
              <span className="flex items-center gap-2"><ReceiptIcon size={16} /> Archive This Post</span>
            )}
          </Button>

          {/* Cancel button */}
          <button
            onClick={handleReset}
            className="w-full py-2 text-gray-500 hover:text-white font-mono text-sm transition-colors"
          >
            Cancel
          </button>
        </div>
      )}
    </div>
  );
}
src/features/app/components/stack-detail.tsx
"use client";

import { useState, useMemo, useEffect, useCallback } from "react";
import { useAccount } from "wagmi";
import { Card, CardContent, P, Small, H4 } from "@neynar/ui";
import { useStack } from "@/hooks/use-stacks";
import { useDiscoveryContext } from "@/contexts/discovery-context";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { safeComposeCast, safeOpenUrl, useAppMode } from "@/lib/app-mode";
import { useRelayUploadV2 } from "@/hooks/use-relay-upload-v2";
import { useUserProfile } from "@/hooks/use-user-profile";
import { CoverImage } from "./cover-image";
import { FolderTreeView } from "./folder-tree-view";
import { FolderUploadModal } from "./folder-upload-modal";
import { GitHubImportModal } from "./github-import-modal";
import { ZipImportModal } from "./zip-import-modal";
import { LibraryIcon, LockIcon, UnlockIcon, WarningIcon, LinkIcon, LoadingIcon, CloseIcon, ClipboardIcon, CheckCircleIcon, AddIcon, InboxEmptyIcon, ShareIcon, FolderIcon, ListIcon, GlobeIcon, PackageIcon, EditIcon, ChevronDownIcon } from "@/components/icons/net-library-icons";
import { UpvoteButton } from "./upvote-button";
import type { Book, StackItem } from "@/features/app/types";
import type { FileSystemItem } from "@/features/app/types-filesystem";
import { buildFileTree } from "@/features/app/types-filesystem";
import { decodeBytes32Key } from "@/lib/net-protocol";

// Get effective cover URL - prefer coverUrl, fallback to cdnUrl for image/video content
function getEffectiveCoverUrl(item: { coverUrl?: string; cdnUrl?: string; mediaType?: string }): string | undefined {
  // If explicit cover art is set, use it
  if (item.coverUrl) return item.coverUrl;

  // For image/video content, cdnUrl IS the visual content - use it as thumbnail
  if (item.cdnUrl && item.mediaType && ["image", "video"].includes(item.mediaType)) {
    return item.cdnUrl;
  }

  // No cover available
  return undefined;
}

interface StackDetailProps {
  stackId: string;
  onBack: () => void;
  onSelectBook: (book: Book) => void;
  initialFiles?: File[] | null; // Pre-loaded files from drag-and-drop folder
  onInitialFilesProcessed?: () => void; // Called when initial files have been processed
}

// Convert StackItem + DiscoveryEntry to Book format
// Uses ONLY stored discovery entry fields - no runtime API calls
function itemToBook(
  item: StackItem,
  entries: Map<string, {
    title: string; author: string; categories: string[]; operator: string; fileSize: number; uploadedAt: number;
    coverUrl?: string; storageType?: string; cdnUrl?: string; fileName?: string; mediaType?: string; contentKey: string;
    uploaderUsername?: string; uploaderStoredUsername?: string; uploaderPfpUrl?: string; uploaderAddress?: string; uploaderFid?: number;
  }>
): Book | null {
  const entry = entries.get(item.contentKey);
  if (!entry) return null;

  // DEFENSIVE: Ensure all required fields have safe defaults
  const safeUploadedAt = typeof entry.uploadedAt === 'number' ? entry.uploadedAt : Date.now();
  const safeFileSize = typeof entry.fileSize === 'number' ? entry.fileSize : 0;

  // Use uploaderAddress if available, fallback to operator for legacy items
  const uploaderAddress = entry.uploaderAddress || entry.operator || "";

  // Priority for username: uploaderUsername > uploaderStoredUsername > truncated address
  const username = entry.uploaderUsername ||
    entry.uploaderStoredUsername ||
    (uploaderAddress ? uploaderAddress.slice(0, 6) + "..." + uploaderAddress.slice(-4) : "Unknown");

  // Priority for pfpUrl: stored pfpUrl > dicebear based on uploaderAddress
  const pfpUrl = entry.uploaderPfpUrl ||
    `https://api.dicebear.com/7.x/identicon/svg?seed=${uploaderAddress || 'unknown'}`;

  return {
    id: item.contentKey,
    title: entry.title || 'Untitled',
    author: entry.author || 'Unknown Author',
    categories: Array.isArray(entry.categories) ? entry.categories : [],
    uploader: {
      username,
      pfpUrl,
      address: uploaderAddress,
      fid: entry.uploaderFid,
    },
    uploadDate: new Date(safeUploadedAt).toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    }),
    size: formatFileSize(safeFileSize),
    coverUrl: entry.coverUrl,
    contentKey: item.contentKey,
    storageType: entry.storageType as "regular" | "chunked" | "xml" | undefined,
    // Viewer-critical fields — without these the multimedia viewer can't determine
    // content type or where to fetch the file from (especially for agent-uploaded items).
    mediaType: entry.mediaType as Book["mediaType"],
    cdnUrl: entry.cdnUrl,
    operator: entry.operator,
  };
}

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

// Type for restore prompt items
type RestorePromptItem = {
  contentKey: string;
  title?: string;
  previousStacks: Array<{ id: string; name: string }>;
};

export function StackDetail({ stackId, onBack, onSelectBook, initialFiles, onInitialFilesProcessed }: StackDetailProps) {
  const { address } = useAccount();
  const { stack, items, isLoading, error, removeItem, reorderItems, updateMetadata, setPrivacy, restoreToStacks, refresh } = useStack(stackId);
  const { entries: discoveryEntries } = useDiscoveryContext();
  const { isMember } = useMembershipStatus();
  const appMode = useAppMode();
  const isBaseApp = appMode === "base-app";
  const { uploadFile, isUploading: _isRelayUploading } = useRelayUploadV2();
  const { profile } = useUserProfile();

  const [isRemoving, setIsRemoving] = useState<string | null>(null);
  const [isReordering, setIsReordering] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [showShareMenu, setShowShareMenu] = useState(false);
  const [showSharePrompt, setShowSharePrompt] = useState(false);
  const [isTogglingPrivacy, setIsTogglingPrivacy] = useState(false);

  // Restore prompt state (when making stack public)
  const [showRestorePrompt, setShowRestorePrompt] = useState(false);
  const [restoreItems, setRestoreItems] = useState<RestorePromptItem[]>([]);
  const [selectedRestores, setSelectedRestores] = useState<Map<string, Set<string>>>(new Map());
  const [isRestoring, setIsRestoring] = useState(false);

  // Edit mode state for name/description
  const [editName, setEditName] = useState("");
  const [editDescription, setEditDescription] = useState("");
  const [isSavingMetadata, setIsSavingMetadata] = useState(false);

  // Add items modal state
  const [showAddItemsModal, setShowAddItemsModal] = useState(false);
  const [selectedItemsToAdd, setSelectedItemsToAdd] = useState<Set<string>>(new Set());
  const [isAddingItems, setIsAddingItems] = useState(false);

  // CDN links popup state
  const [showCdnLinks, setShowCdnLinks] = useState(false);
  const [copiedLink, setCopiedLink] = useState<string | null>(null);

  // Filesystem mode state
  const [showFolderUpload, setShowFolderUpload] = useState(false);
  const [showGitHubImport, setShowGitHubImport] = useState(false);
  const [showZipImport, setShowZipImport] = useState(false);
  const [viewMode, setViewMode] = useState<"list" | "tree">("list");
  const [showActionsMenu, setShowActionsMenu] = useState(false);

  // Set view mode based on stack type when stack loads
  useEffect(() => {
    if (stack?.isFileSystem) {
      setViewMode("tree");
    }
  }, [stack?.isFileSystem]);

  // Auto-open folder upload modal when initialFiles are provided (from drag-and-drop)
  useEffect(() => {
    if (initialFiles && initialFiles.length > 0 && stack?.isFileSystem) {
      console.log("[StackDetail] Opening folder upload with", initialFiles.length, "initial files");
      setShowFolderUpload(true);
    }
  }, [initialFiles, stack?.isFileSystem]);

  // Calculate if this is a "compact" stack (few items) - affects layout
  const isCompact = items.length <= 3;

  // Build a map of contentKey -> entry for quick lookup
  const entryMap = useMemo(() => {
    const map = new Map<string, {
      title: string;
      author: string;
      categories: string[];
      operator: string;
      fileSize: number;
      uploadedAt: number;
      coverUrl?: string;
      storageType?: string;
      cdnUrl?: string;
      fileName?: string;
      mediaType?: string;
      contentKey: string;
      // Uploader attribution fields - prefer these over operator
      uploaderUsername?: string;
      uploaderStoredUsername?: string;
      uploaderPfpUrl?: string;
      uploaderAddress?: string;
      uploaderFid?: number;
    }>();
    for (const entry of discoveryEntries) {
      if (!entry.contentKey) continue; // Skip entries without contentKey
      map.set(entry.contentKey, {
        title: entry.title || 'Untitled',
        author: entry.author || 'Unknown Author',
        categories: Array.isArray(entry.categories) ? entry.categories : [],
        operator: entry.operator || '',
        fileSize: typeof entry.fileSize === 'number' ? entry.fileSize : 0,
        uploadedAt: typeof entry.uploadedAt === 'number' ? entry.uploadedAt : Date.now(),
        coverUrl: entry.coverUrl,
        storageType: entry.storageType,
        cdnUrl: entry.cdnUrl,
        fileName: entry.fileName,
        mediaType: entry.mediaType,
        contentKey: entry.contentKey,
        // Uploader attribution fields
        uploaderUsername: entry.uploaderUsername,
        uploaderStoredUsername: entry.uploaderStoredUsername,
        uploaderPfpUrl: entry.uploaderPfpUrl,
        uploaderAddress: entry.uploaderAddress,
        uploaderFid: entry.uploaderFid,
      });
    }
    return map;
  }, [discoveryEntries]);

  // Convert items to books using stored discovery entry data only
  const books = useMemo(() => {
    return items
      .map(item => itemToBook(item, entryMap))
      .filter((book): book is Book => book !== null);
  }, [items, entryMap]);

  // Build CDN links list for the popup
  const cdnLinks = useMemo(() => {
    return items.map(item => {
      const entry = entryMap.get(item.contentKey);
      if (!entry) return null;

      // Prefer cdnUrl > /storage/load/ with fileName > decoded bytes32 key > /storage/raw/
      const decodedKey = !entry.cdnUrl && !entry.fileName ? decodeBytes32Key(entry.contentKey) : null;
      const cdnUrl = entry.cdnUrl ||
        (entry.fileName
          ? `https://storedon.net/net/8453/storage/load/${entry.operator}/${encodeURIComponent(entry.fileName)}`
          : decodedKey
            ? `https://storedon.net/net/8453/storage/load/${entry.operator}/${encodeURIComponent(decodedKey)}`
            : `https://storedon.net/net/8453/storage/raw/${entry.operator}/${entry.contentKey}`);

      return {
        contentKey: item.contentKey,
        title: entry.title || 'Untitled',
        author: entry.author || 'Unknown Author',
        cdnUrl,
      };
    }).filter((link): link is NonNullable<typeof link> => link !== null);
  }, [items, entryMap]);

  // Get user's uploads that aren't in this stack (for add items modal)
  // Check uploaderAddress first (relay uploads), then operator (legacy/direct uploads)
  const userUploadsNotInStack = useMemo(() => {
    if (!address) return [];
    const itemContentKeys = new Set(items.map(item => item.contentKey));
    const normalizedAddress = address.toLowerCase();
    return discoveryEntries.filter(entry => {
      const entryUploader = (entry.uploaderAddress || entry.operator || '').toLowerCase();
      return entryUploader === normalizedAddress && !itemContentKeys.has(entry.contentKey);
    });
  }, [discoveryEntries, items, address]);

  // Build file tree for filesystem mode stacks
  const fileTree = useMemo(() => {
    if (!stack?.isFileSystem) return [];
    const fsItems: FileSystemItem[] = items
      .filter(item => item.path) // Only items with path data
      .map(item => ({
        contentKey: item.contentKey,
        addedAt: item.addedAt,
        addedBy: item.addedBy,
        path: item.path || "/" + (item.fileName || item.contentKey),
        fileName: item.fileName || item.contentKey.slice(0, 10),
        fileSize: item.fileSize || 0,
        mimeType: item.mimeType,
        isDirectory: item.isDirectory || false,
        parentPath: item.parentPath || "/",
      }));
    return buildFileTree(fsItems);
  }, [items, stack?.isFileSystem]);

  // Real filesystem upload handler - uploads to relay then adds to stack
  const handleFsUploadFile = useCallback(async (
    file: File,
    metadata: { path: string; fileName: string; fileSize: number; mimeType: string }
  ): Promise<{ success: boolean; error?: string }> => {
    if (!address || !stack) {
      return { success: false, error: "Not connected or no stack" };
    }

    // Check stack limit before paying for an upload
    const currentItems = items.length;
    const stackLimit = stack?.unlocked ? Infinity : 20;
    if (currentItems >= stackLimit) {
      return { success: false, error: "Stack is full. Unlock unlimited capacity or remove items first." };
    }

    try {
      console.log("[StackDetail] FS upload starting:", metadata.path, file.size, "bytes");

      // Step 1: Upload file to relay
      // Note: File will be added to discovery index AND to stack
      const uploadResult = await uploadFile(file, {
        title: metadata.fileName,
        author: profile?.username || profile?.displayName || address.slice(0, 10),
        categories: ["filesystem", stack.name],
      });

      if (!uploadResult.success || !uploadResult.contentKey) {
        console.error("[StackDetail] Upload failed:", uploadResult.error);
        return { success: false, error: uploadResult.error || "Upload failed" };
      }

      console.log("[StackDetail] Upload success, contentKey:", uploadResult.contentKey);

      // Step 2: Add to stack with filesystem metadata
      const addResponse = await fetch("/api/stacks", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          stackId,
          action: "add-fs-item",
          owner: address,
          contentKey: uploadResult.contentKey,
          path: metadata.path,
          fileName: metadata.fileName,
          fileSize: metadata.fileSize,
          mimeType: metadata.mimeType,
        }),
      });

      if (!addResponse.ok) {
        const errorData = await addResponse.json().catch(() => ({}));
        console.error("[StackDetail] Add to stack failed:", errorData);
        return { success: false, error: errorData.error || "Failed to add to stack" };
      }

      console.log("[StackDetail] Added to stack:", metadata.path);
      return { success: true };
    } catch (error) {
      console.error("[StackDetail] FS upload error:", error);
      return { success: false, error: error instanceof Error ? error.message : "Upload failed" };
    }
  }, [address, stack, stackId, uploadFile, profile, items.length]);

  // Handler for setting source metadata (used by GitHub import)
  const handleSetSourceMeta = useCallback(async (meta: { sourceUrl: string; sourceCommit?: string }) => {
    if (!address || !stack) return;

    try {
      // Determine source type from URL
      const sourceType = meta.sourceUrl.includes("github.com") ? "github" : "url";

      const response = await fetch("/api/stacks", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          stackId,
          action: "update-metadata",
          owner: address,
          sourceUrl: meta.sourceUrl,
          sourceType,
          sourceCommit: meta.sourceCommit,
        }),
      });

      if (!response.ok) {
        console.error("[StackDetail] Failed to set source metadata");
      } else {
        console.log("[StackDetail] Source metadata set:", meta.sourceUrl, meta.sourceCommit);
      }
    } catch (error) {
      console.error("[StackDetail] Error setting source metadata:", error);
    }
  }, [address, stack, stackId]);

  // Stack limits
  const STACK_LIMIT = 20;
  const currentCount = items.length;
  const isStackFull = currentCount >= STACK_LIMIT && !stack?.unlocked;
  const remainingSlots = stack?.unlocked ? Infinity : Math.max(0, STACK_LIMIT - currentCount);

  // Check if current user is the owner
  const isOwner = stack && address && stack.owner && stack.owner.toLowerCase() === address.toLowerCase();

  const handleRemoveItem = async (contentKey: string) => {
    if (!isOwner) return;

    setIsRemoving(contentKey);
    try {
      await removeItem(contentKey);
      await refresh();
    } catch (err) {
      console.error("Failed to remove item:", err);
    } finally {
      setIsRemoving(null);
    }
  };

  const handleMoveItem = async (contentKey: string, direction: "up" | "down") => {
    if (!isOwner || isReordering) return;

    const currentIndex = items.findIndex(item => item.contentKey === contentKey);
    if (currentIndex === -1) return;
    if (direction === "up" && currentIndex === 0) return;
    if (direction === "down" && currentIndex === items.length - 1) return;

    setIsReordering(true);
    try {
      const newOrder = [...items.map(item => item.contentKey)];
      const swapIndex = direction === "up" ? currentIndex - 1 : currentIndex + 1;
      [newOrder[currentIndex], newOrder[swapIndex]] = [newOrder[swapIndex], newOrder[currentIndex]];
      await reorderItems(newOrder);
    } catch (err) {
      console.error("Failed to reorder items:", err);
    } finally {
      setIsReordering(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex flex-col items-center justify-center py-20">
        <div className="text-4xl mb-4 animate-pulse text-[#00ff00]"><LibraryIcon size={48} /></div>
        <P className="text-[#00ff00] font-mono">Loading stack...</P>
      </div>
    );
  }

  if (error || !stack) {
    return (
      <div className="flex flex-col items-center justify-center py-20">
        <div className="text-4xl mb-4 text-yellow-400"><WarningIcon size={48} /></div>
        <P className="text-red-400 font-mono mb-2">Stack not found</P>
        <button
          onClick={onBack}
          className="px-4 py-2 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-lg text-[#00ff00] font-mono hover:bg-[#00ff00]/20 transition-colors"
        >
          ← Go Back
        </button>
      </div>
    );
  }

  return (
    <div className={`space-y-4 ${isCompact ? 'pb-4' : ''}`}>
      {/* Header - Compact card style */}
      <Card className="bg-[#0a0a0a] border border-[#00ff00]/30">
        <CardContent className="p-3">
          <div className="flex items-center gap-3">
            <button
              onClick={onBack}
              className="w-9 h-9 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors shrink-0 text-sm"
            >
              ←
            </button>
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2">
                <H4 className="text-[#00ff00] font-mono truncate text-base">{stack.name}</H4>
                {stack.isPrivate && isOwner && (
                  <span className="px-1.5 py-0.5 text-[10px] bg-purple-500/20 text-purple-400 rounded font-mono flex items-center gap-1">
                    <LockIcon size={10} /> Private
                  </span>
                )}
                {stack.isFileSystem && (
                  <span className="px-1.5 py-0.5 text-[10px] bg-[#00ff00]/20 text-[#00ff00] rounded font-mono flex items-center gap-1">
                    <FolderIcon size={10} /> {stack.sourceType === "github" ? "GitHub" : stack.sourceType === "url" ? "URL" : "Folder"}
                  </span>
                )}
              </div>
              <div className="flex items-center gap-2">
                {stack.ownerPfpUrl && (
                  <img
                    src={stack.ownerPfpUrl}
                    alt={stack.ownerUsername || "owner"}
                    className={`w-4 h-4 rounded-full border ${
                      stack.isAgentCreated ? "border-[#B794F4]/50" : "border-transparent"
                    }`}
                  />
                )}
                <span
                  className="font-mono text-[10px]"
                  style={{ color: stack.isAgentCreated ? "#B794F4" : "#6b7280" }}
                >
                  {stack.ownerUsername ? `@${stack.ownerUsername}` : (stack.owner || '').slice(0, 6) + "..."}
                  {stack.isAgentCreated && (
                    <span style={{ fontSize: "0.8em", marginLeft: "4px", opacity: 0.8 }}>
                      AGENT
                    </span>
                  )}
                </span>
                <Small className="text-gray-600 font-mono text-[10px]">•</Small>
                <Small className={`font-mono text-[10px] ${
                  stack.unlocked
                    ? "text-[#00ff00]/70"
                    : currentCount >= STACK_LIMIT
                    ? "text-[#00ff00]"
                    : currentCount >= 15
                    ? "text-yellow-400"
                    : "text-[#00ff00]/70"
                }`}>
                  {stack.unlocked
                    ? `${stack.itemCount} items ∞`
                    : `${currentCount}/${STACK_LIMIT} items`}
                </Small>
                <Small className="text-gray-600 font-mono text-[10px]">•</Small>
                <UpvoteButton
                  contentKey={stack.id}
                  operatorAddress={stack.owner}
                  upvoteCount={stack.upvotes || 0}
                  title={stack.name}
                  inline
                />
              </div>
            </div>
            {/* Share Stack Button */}
            <div className="relative">
              <button
                onClick={() => setShowShareMenu(!showShareMenu)}
                className={`w-9 h-9 rounded-full flex items-center justify-center transition-colors shrink-0 ${
                  isBaseApp
                    ? "bg-[#0052FF]/20 text-[#0052FF] hover:bg-[#0052FF]/30"
                    : "bg-[#8A63D2]/20 text-[#8A63D2] hover:bg-[#8A63D2]/30"
                }`}
                title="Share stack"
              >
                <ShareIcon size={16} />
              </button>

              {showShareMenu && (
                <>
                  <div className="fixed inset-0 z-40" onClick={() => setShowShareMenu(false)} />
                  <div className="absolute right-0 top-full mt-1 bg-black border border-[#00ff00]/30 rounded-lg overflow-hidden z-50 shadow-lg min-w-[160px]">
                    <button
                      onClick={async () => {
                        setShowShareMenu(false);
                        const source = isBaseApp ? "base" : "farcaster";
                        const stackUrl = `${window.location.origin}/share/stack/${encodeURIComponent(stack.id)}?source=${source}`;
                        const creatorTag = stack.ownerUsername ? `@${stack.ownerUsername}` : "a Net Library member";
                        const castText = `Check out "${stack.name}" - a curated stack of ${stack.itemCount} items by ${creatorTag} on Net Library!\n\nDecentralized onchain media powered by @netprotocol`;
                        await safeComposeCast({
                          text: castText,
                          embeds: [stackUrl],
                        });
                      }}
                      className={`w-full px-3 py-2.5 text-left text-xs font-mono flex items-center gap-2 transition-colors ${
                        isBaseApp
                          ? "hover:bg-[#0052FF]/20 text-[#0052FF]"
                          : "hover:bg-[#8A63D2]/20 text-[#8A63D2]"
                      }`}
                    >
                      {isBaseApp ? (
                        <svg width="14" height="14" viewBox="0 0 111 111" fill="none">
                          <path d="M54.921 110.034C85.359 110.034 110.034 85.402 110.034 55.017C110.034 24.6319 85.359 0 54.921 0C26.0432 0 2.35281 22.1714 0 50.3923H72.8467V59.6416H0C2.35281 87.8625 26.0432 110.034 54.921 110.034Z" fill="#0052FF"/>
                        </svg>
                      ) : (
                        <svg width="14" height="14" viewBox="0 0 1000 1000" fill="#8A63D2">
                          <path d="M257.778 155.556H742.222V844.445H671.111V528.889H670.414C662.554 441.677 589.258 373.333 500 373.333C410.742 373.333 337.446 441.677 329.586 528.889H328.889V844.445H257.778V155.556Z"/>
                          <path d="M128.889 253.333L157.778 351.111H182.222V746.667C169.949 746.667 160 756.616 160 768.889V795.556H155.556C143.283 795.556 133.333 805.505 133.333 817.778V844.445H382.222V817.778C382.222 805.505 372.273 795.556 360 795.556H355.556V768.889C355.556 756.616 345.606 746.667 333.333 746.667H306.667V253.333H128.889Z"/>
                          <path d="M675.556 746.667C663.283 746.667 653.333 756.616 653.333 768.889V795.556H648.889C636.616 795.556 626.667 805.505 626.667 817.778V844.445H875.556V817.778C875.556 805.505 865.606 795.556 853.333 795.556H848.889V768.889C848.889 756.616 838.94 746.667 826.667 746.667V351.111H851.111L880 253.333H702.222V746.667H675.556Z"/>
                        </svg>
                      )}
                      {isBaseApp ? "Share to Feed" : "Share to Farcaster"}
                    </button>
                    <button
                      onClick={async () => {
                        setShowShareMenu(false);
                        // Always use source=web for X shares so users land in browser experience
                        const stackUrl = `${window.location.origin}/share/stack/${encodeURIComponent(stack.id)}?source=web`;
                        const creatorTag = stack.ownerUsername ? `@${stack.ownerUsername}` : "a Net Library member";
                        const xText = `Check out "${stack.name}" - a curated stack of ${stack.itemCount} items by ${creatorTag} on Net Library!\n\nDecentralized onchain media powered by @netprotocolapp`;
                        const xIntentParams = new URLSearchParams({
                          text: xText,
                          url: stackUrl,
                        });
                        const xIntentUrl = `https://twitter.com/intent/tweet?${xIntentParams.toString()}`;
                        if (isBaseApp) {
                          window.open(xIntentUrl, "_blank", "noopener,noreferrer");
                        } else {
                          await safeOpenUrl(xIntentUrl);
                        }
                      }}
                      className="w-full px-3 py-2.5 text-left text-xs font-mono flex items-center gap-2 hover:bg-white/10 text-white transition-colors border-t border-gray-800"
                    >
                      <svg width="12" height="12" viewBox="0 0 24 24" fill="white">
                        <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                      </svg>
                      Share to X
                    </button>
                    <button
                      onClick={async () => {
                        setShowShareMenu(false);
                        const stackUrl = `${window.location.origin}/share/stack/${encodeURIComponent(stack.id)}`;
                        try {
                          await navigator.clipboard.writeText(stackUrl);
                          // Could show a toast notification here
                        } catch (err) {
                          console.error("Failed to copy link:", err);
                        }
                      }}
                      className="w-full px-3 py-2.5 text-left text-xs font-mono flex items-center gap-2 hover:bg-white/10 text-white transition-colors border-t border-gray-800"
                    >
                      <ClipboardIcon size={12} />
                      Copy Link
                    </button>
                  </div>
                </>
              )}
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Description (only if exists and not in edit mode) */}
      {!editMode && stack.description && (
        <P className="text-gray-400 font-mono text-sm px-1">{stack.description}</P>
      )}

      {/* Filesystem Mode Info Bar */}
      {stack.isFileSystem && (
        <div className="flex items-center justify-between px-1">
          <div className="flex items-center gap-3">
            <Small className="text-[#00ff00] font-mono">
              {stack.fileCount || 0} files • {formatFileSize(stack.totalSize || 0)}
            </Small>
            {stack.sourceUrl && (
              <a
                href={stack.sourceUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="text-[10px] text-gray-500 hover:text-[#00ff00] font-mono truncate max-w-[150px]"
              >
                {stack.sourceUrl.length > 40
                  ? stack.sourceUrl.replace(/^https?:\/\/(www\.)?/, '').slice(0, 40) + "..."
                  : stack.sourceUrl.replace(/^https?:\/\/(www\.)?/, '')}
              </a>
            )}
          </div>
          {/* View Mode Toggle - only show when there are items */}
          {items.length > 0 && (
            <div className="flex items-center gap-1 bg-[#1a1a1a] rounded-lg p-0.5">
              <button
                onClick={() => setViewMode("list")}
                className={`p-1.5 rounded transition-colors ${
                  viewMode === "list"
                    ? "bg-[#00ff00]/20 text-[#00ff00]"
                    : "text-gray-500 hover:text-gray-300"
                }`}
                title="List view"
              >
                <ListIcon size={14} />
              </button>
              <button
                onClick={() => setViewMode("tree")}
                className={`p-1.5 rounded transition-colors ${
                  viewMode === "tree"
                    ? "bg-[#00ff00]/20 text-[#00ff00]"
                    : "text-gray-500 hover:text-gray-300"
                }`}
                title="Tree view"
              >
                <FolderIcon size={14} />
              </button>
            </div>
          )}
        </div>
      )}

      {/* Edit Mode Panel - inline editing */}
      {editMode && isOwner && (
        <Card className="bg-[#0a0a0a] border border-[#00ff00]/50">
          <CardContent className="p-3 space-y-3">
            <div>
              <label className="text-[10px] font-mono text-gray-500 uppercase tracking-wider block mb-1">
                Stack Name
              </label>
              <input
                type="text"
                value={editName}
                onChange={(e) => setEditName(e.target.value)}
                placeholder="Stack name"
                maxLength={50}
                className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00]"
              />
            </div>
            <div>
              <label className="text-[10px] font-mono text-gray-500 uppercase tracking-wider block mb-1">
                Description
              </label>
              <textarea
                value={editDescription}
                onChange={(e) => setEditDescription(e.target.value)}
                placeholder="Optional description..."
                maxLength={200}
                rows={2}
                className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00] resize-none"
              />
            </div>
            {/* Privacy Toggle */}
            <div className="flex items-center justify-between p-3 bg-black border border-purple-500/30 rounded-lg">
              <div>
                <P className="text-white font-mono text-sm">Private Stack</P>
                <Small className="text-gray-500 font-mono">
                  {stack.isPrivate ? "Only you can see this" : "Visible to everyone"}
                </Small>
              </div>
              <button
                type="button"
                onClick={async () => {
                  if (isTogglingPrivacy) return;
                  setIsTogglingPrivacy(true);
                  const newPrivate = !stack.isPrivate;
                  const result = await setPrivacy(newPrivate);
                  setIsTogglingPrivacy(false);
                  if (result.success && result.promptShare) {
                    // Was private, now public - prompt to share
                    setShowSharePrompt(true);

                    // Check if any items had previous stacks
                    if (result.itemsWithPreviousStacks && result.itemsWithPreviousStacks.length > 0) {
                      setRestoreItems(result.itemsWithPreviousStacks);
                      // Pre-select all stacks for restore
                      const initialSelections = new Map<string, Set<string>>();
                      result.itemsWithPreviousStacks.forEach((item) => {
                        initialSelections.set(item.contentKey, new Set(item.previousStacks.map(s => s.id)));
                      });
                      setSelectedRestores(initialSelections);
                      setShowRestorePrompt(true);
                    }
                  }
                }}
                disabled={isTogglingPrivacy}
                className={`relative w-12 h-6 rounded-full transition-colors disabled:opacity-50 ${
                  stack.isPrivate ? "bg-purple-500" : "bg-gray-600"
                }`}
              >
                <span
                  className={`absolute top-1 w-4 h-4 rounded-full bg-white transition-transform ${
                    stack.isPrivate ? "left-7" : "left-1"
                  }`}
                />
              </button>
            </div>

            {/* Privacy Info Hint */}
            {!stack.isPrivate && (
              <div className="p-2 bg-purple-500/10 border border-purple-500/30 rounded-lg">
                <Small className="text-purple-400 font-mono flex items-start gap-1">
                  <WarningIcon size={14} className="shrink-0 mt-0.5" /> Making private will hide all items from public feeds and remove them from other stacks
                </Small>
              </div>
            )}

            <div className="flex gap-2">
              <button
                onClick={() => setEditMode(false)}
                className="flex-1 py-2 bg-[#1a1a1a] border border-gray-700 rounded-lg text-gray-400 font-mono text-sm hover:bg-[#222] transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={async () => {
                  if (!editName.trim()) return;
                  setIsSavingMetadata(true);
                  try {
                    await updateMetadata(editName.trim(), editDescription.trim() || undefined);
                    await refresh();
                    setEditMode(false);
                  } catch (err) {
                    console.error("Failed to save:", err);
                  } finally {
                    setIsSavingMetadata(false);
                  }
                }}
                disabled={isSavingMetadata || !editName.trim() || (editName === stack.name && editDescription === (stack.description || ""))}
                className="flex-1 py-2 bg-[#00ff00]/20 border border-[#00ff00]/50 rounded-lg text-[#00ff00] font-mono text-sm font-bold disabled:opacity-50 hover:bg-[#00ff00]/30 transition-colors"
              >
                {isSavingMetadata ? "Saving..." : "Save"}
              </button>
            </div>

            {/* Add Items to Stack Button */}
            <button
              onClick={() => {
                setSelectedItemsToAdd(new Set());
                setShowAddItemsModal(true);
              }}
              disabled={isStackFull}
              className={`w-full py-3 rounded-lg font-mono text-sm font-bold transition-all flex items-center justify-center gap-2 ${
                isStackFull
                  ? "bg-yellow-500/10 border border-yellow-500/30 text-yellow-400"
                  : "bg-purple-500/20 border border-purple-500/50 text-purple-400 hover:bg-purple-500/30"
              }`}
            >
              {isStackFull ? (
                <><LockIcon size={14} className="inline mr-1" /> Stack Full ({currentCount}/{STACK_LIMIT})</>
              ) : (
                <><AddIcon size={14} className="inline mr-1" /> Add Items to Stack ({currentCount}/{stack?.unlocked ? "∞" : STACK_LIMIT})</>
              )}
            </button>
          </CardContent>
        </Card>
      )}

      {/* Share Prompt Modal (shown when making stack public) */}
      {showSharePrompt && stack && (
        <div
          className="fixed inset-0 bg-black/90 z-[9999] flex items-center justify-center p-4"
          onClick={() => setShowSharePrompt(false)}
        >
          <div
            className="w-full max-w-sm bg-[#0a0a0a] border border-purple-500/50 rounded-xl overflow-hidden"
            onClick={(e: React.MouseEvent) => e.stopPropagation()}
          >
            <div className="p-4 text-center space-y-4">
              <div className="w-16 h-16 mx-auto bg-purple-500/20 rounded-full flex items-center justify-center">
                <CheckCircleIcon size={32} className="text-purple-400" />
              </div>
              <div>
                <P className="text-white font-mono font-bold">Stack is now public!</P>
                <Small className="text-gray-400 font-mono block mt-1">
                  Share &ldquo;{stack.name}&rdquo; with your followers
                </Small>
              </div>
              <div className="flex gap-2">
                <button
                  onClick={() => setShowSharePrompt(false)}
                  className="flex-1 py-2 bg-[#1a1a1a] rounded-lg text-gray-400 font-mono text-sm hover:bg-[#222] transition-colors"
                >
                  Later
                </button>
                <button
                  onClick={() => {
                    setShowSharePrompt(false);
                    setShowShareMenu(true);
                  }}
                  className="flex-1 py-2 bg-purple-500 rounded-lg text-white font-mono text-sm font-bold hover:bg-purple-600 transition-colors"
                >
                  Share Now
                </button>
              </div>
            </div>
          </div>
        </div>
      )}

      {/* Restore Items Prompt Modal (shown when making stack public) */}
      {showRestorePrompt && restoreItems.length > 0 && (
        <div
          className="fixed inset-0 bg-black/90 z-[9999] flex items-center justify-center p-4"
          onClick={() => setShowRestorePrompt(false)}
        >
          <div
            className="w-full max-w-sm bg-[#0a0a0a] border border-[#00ff00]/50 rounded-xl overflow-hidden max-h-[80vh] flex flex-col"
            onClick={(e: React.MouseEvent) => e.stopPropagation()}
          >
            <div className="p-4 border-b border-[#00ff00]/20">
              <div className="flex items-center gap-3 mb-2">
                <div className="w-10 h-10 bg-[#00ff00]/20 rounded-full flex items-center justify-center">
                  <span className="text-xl text-[#00ff00]"><LibraryIcon size={20} /></span>
                </div>
                <div>
                  <P className="text-white font-mono font-bold">Restore to Previous Stacks?</P>
                  <Small className="text-gray-400 font-mono">
                    These items were in other stacks before being made private
                  </Small>
                </div>
              </div>
            </div>

            <div className="flex-1 overflow-y-auto p-4 space-y-4">
              {restoreItems.map((item) => (
                <div key={item.contentKey} className="bg-[#1a1a1a] rounded-lg p-3">
                  <P className="text-white font-mono text-sm truncate mb-2">
                    {item.title || item.contentKey.slice(0, 12) + "..."}
                  </P>
                  <Small className="text-gray-500 font-mono block mb-2">
                    Was in these stacks:
                  </Small>
                  <div className="space-y-1.5">
                    {item.previousStacks.map((prevStack) => {
                      const isSelected = selectedRestores.get(item.contentKey)?.has(prevStack.id) || false;
                      return (
                        <button
                          key={prevStack.id}
                          onClick={() => {
                            setSelectedRestores(prev => {
                              const newMap = new Map(prev);
                              const itemSet = new Set(newMap.get(item.contentKey) || []);
                              if (isSelected) {
                                itemSet.delete(prevStack.id);
                              } else {
                                itemSet.add(prevStack.id);
                              }
                              newMap.set(item.contentKey, itemSet);
                              return newMap;
                            });
                          }}
                          className={`w-full px-3 py-2 rounded text-left text-xs font-mono transition-all flex items-center gap-2 ${
                            isSelected
                              ? "bg-[#00ff00]/20 text-[#00ff00] border border-[#00ff00]/50"
                              : "bg-black text-gray-400 border border-gray-700 hover:border-[#00ff00]/30"
                          }`}
                        >
                          <span className={`w-4 h-4 rounded border flex items-center justify-center text-[10px] ${
                            isSelected ? "bg-[#00ff00] border-[#00ff00] text-black" : "border-gray-600"
                          }`}>
                            {isSelected && "✓"}
                          </span>
                          {prevStack.name}
                        </button>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>

            <div className="p-4 border-t border-[#00ff00]/20 flex gap-2">
              <button
                onClick={() => {
                  setShowRestorePrompt(false);
                  setRestoreItems([]);
                  setSelectedRestores(new Map());
                }}
                className="flex-1 py-2 bg-[#1a1a1a] rounded-lg text-gray-400 font-mono text-sm hover:bg-[#222] transition-colors"
              >
                Skip
              </button>
              <button
                onClick={async () => {
                  setIsRestoring(true);
                  // Restore each item to its selected stacks
                  for (const item of restoreItems) {
                    const stackIds = Array.from(selectedRestores.get(item.contentKey) || []);
                    if (stackIds.length > 0) {
                      await restoreToStacks(item.contentKey, stackIds);
                    }
                  }
                  setIsRestoring(false);
                  setShowRestorePrompt(false);
                  setRestoreItems([]);
                  setSelectedRestores(new Map());
                }}
                disabled={isRestoring || Array.from(selectedRestores.values()).every(s => s.size === 0)}
                className="flex-1 py-2 bg-[#00ff00] rounded-lg text-black font-mono text-sm font-bold hover:bg-[#00ff00]/90 transition-colors disabled:opacity-50"
              >
                {isRestoring ? "Restoring..." : "Restore Selected"}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Add Items Modal */}
      {showAddItemsModal && isOwner && (
        <div
          className="fixed inset-0 bg-black/90 z-[9999] flex items-center justify-center p-4"
          onClick={() => setShowAddItemsModal(false)}
        >
          <div
            className="w-full max-w-sm bg-[#0a0a0a] border border-purple-500/50 rounded-xl overflow-hidden max-h-[85vh] flex flex-col"
            onClick={(e: React.MouseEvent) => e.stopPropagation()}
          >
            {/* Header */}
            <div className="p-4 border-b border-purple-500/20">
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center gap-2">
                  <span className="text-xl text-[#00ff00]"><LibraryIcon size={20} /></span>
                  <P className="text-white font-mono font-bold">Add Items to Stack</P>
                </div>
                <button
                  onClick={() => setShowAddItemsModal(false)}
                  className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white transition-colors"
                >
                  ✕
                </button>
              </div>
              <Small className="text-gray-500 font-mono">
                Select items from your uploads to add
              </Small>
              {!stack?.unlocked && (
                <div className="mt-2 flex items-center justify-between">
                  <Small className="text-purple-400 font-mono">
                    {remainingSlots === 0 ? "Stack is full" : `${remainingSlots} slot${remainingSlots !== 1 ? "s" : ""} available`}
                  </Small>
                  <Small className="text-gray-500 font-mono">
                    {currentCount}/{STACK_LIMIT}
                  </Small>
                </div>
              )}
            </div>

            {/* Selection count and limit warning */}
            {selectedItemsToAdd.size > 0 && (
              <div className={`px-4 py-2 ${
                selectedItemsToAdd.size > remainingSlots
                  ? "bg-red-500/10 border-b border-red-500/30"
                  : "bg-purple-500/10 border-b border-purple-500/20"
              }`}>
                <div className="flex items-center justify-between">
                  <Small className={`font-mono ${selectedItemsToAdd.size > remainingSlots ? "text-red-400" : "text-purple-400"}`}>
                    {selectedItemsToAdd.size} selected
                  </Small>
                  {selectedItemsToAdd.size > remainingSlots && !stack?.unlocked && (
                    <Small className="text-red-400 font-mono flex items-center gap-1">
                      <WarningIcon size={12} /> Exceeds limit by {selectedItemsToAdd.size - remainingSlots}
                    </Small>
                  )}
                </div>
              </div>
            )}

            {/* Items list */}
            <div className="flex-1 overflow-y-auto p-4 space-y-2">
              {userUploadsNotInStack.length === 0 ? (
                <div className="text-center py-8">
                  <InboxEmptyIcon size={40} className="mx-auto text-gray-400 mb-3" />
                  <P className="text-gray-400 font-mono">No items to add</P>
                  <Small className="text-gray-500 font-mono block mt-1">
                    All your uploads are already in this stack, or you haven&apos;t uploaded anything yet.
                  </Small>
                </div>
              ) : (
                userUploadsNotInStack.map((entry) => {
                  const isSelected = selectedItemsToAdd.has(entry.contentKey);
                  const wouldExceedLimit = !isSelected && selectedItemsToAdd.size >= remainingSlots && !stack?.unlocked;

                  return (
                    <button
                      key={entry.contentKey}
                      onClick={() => {
                        setSelectedItemsToAdd(prev => {
                          const newSet = new Set(prev);
                          if (isSelected) {
                            newSet.delete(entry.contentKey);
                          } else {
                            newSet.add(entry.contentKey);
                          }
                          return newSet;
                        });
                      }}
                      className={`w-full p-3 rounded-lg text-left transition-all flex items-center gap-3 ${
                        isSelected
                          ? "bg-purple-500/20 border border-purple-500/50"
                          : wouldExceedLimit
                          ? "bg-[#1a1a1a] border border-gray-800 opacity-50"
                          : "bg-[#1a1a1a] border border-gray-800 hover:border-purple-500/30"
                      }`}
                    >
                      {/* Checkbox */}
                      <div className={`w-5 h-5 rounded border-2 flex items-center justify-center shrink-0 ${
                        isSelected
                          ? "bg-purple-500 border-purple-500"
                          : "border-gray-600"
                      }`}>
                        {isSelected && <span className="text-white text-xs font-bold">✓</span>}
                      </div>

                      {/* Cover */}
                      <div className="w-10 h-14 bg-black rounded flex items-center justify-center border border-[#222] shrink-0 overflow-hidden">
                        {getEffectiveCoverUrl(entry) ? (
                          <img src={getEffectiveCoverUrl(entry)} alt={entry.title} className="w-full h-full object-cover" />
                        ) : (
                          <img src="/app-logo.png" alt="" className="w-5 h-5 opacity-40" />
                        )}
                      </div>

                      {/* Info */}
                      <div className="flex-1 min-w-0">
                        <P className="text-white font-mono text-sm truncate">{entry.title}</P>
                        <Small className="text-gray-500 font-mono">{entry.author}</Small>
                      </div>
                    </button>
                  );
                })
              )}
            </div>

            {/* Stack limit explanation and unlock option */}
            {selectedItemsToAdd.size > remainingSlots && !stack?.unlocked && (
              <div className="px-4 py-3 bg-yellow-500/10 border-t border-yellow-500/30">
                <div className="flex items-start gap-3">
                  <LockIcon size={20} className="text-yellow-400 shrink-0 mt-0.5" />
                  <div className="flex-1">
                    <P className="text-yellow-400 font-mono text-sm font-bold">Stack limit reached</P>
                    <Small className="text-gray-400 font-mono block mt-1">
                      Free stacks hold up to {STACK_LIMIT} items. Unlock unlimited capacity for this stack to add more.
                    </Small>
                    <button
                      onClick={() => {
                        // TODO: Implement unlock payment flow
                        console.log("Unlock stack clicked");
                      }}
                      className="mt-2 px-4 py-2 bg-yellow-500/20 border border-yellow-500/50 rounded-lg text-yellow-400 font-mono text-xs font-bold hover:bg-yellow-500/30 transition-colors flex items-center gap-1"
                    >
                      <UnlockIcon size={14} /> Unlock Unlimited - $5 USDC
                    </button>
                  </div>
                </div>
              </div>
            )}

            {/* Footer actions */}
            <div className="p-4 border-t border-purple-500/20 flex gap-2">
              <button
                onClick={() => {
                  setShowAddItemsModal(false);
                  setSelectedItemsToAdd(new Set());
                }}
                className="flex-1 py-2.5 bg-[#1a1a1a] rounded-lg text-gray-400 font-mono text-sm hover:bg-[#222] transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={async () => {
                  if (selectedItemsToAdd.size === 0) return;

                  // Check if exceeds limit (and not unlocked)
                  if (selectedItemsToAdd.size > remainingSlots && !stack?.unlocked) {
                    return; // Don't proceed - they need to unlock first
                  }

                  setIsAddingItems(true);
                  try {
                    // Add each selected item to the stack
                    for (const contentKey of selectedItemsToAdd) {
                      await fetch("/api/stacks", {
                        method: "PUT",
                        headers: { "Content-Type": "application/json" },
                        body: JSON.stringify({
                          stackId,
                          action: "add-item",
                          owner: address,
                          contentKey,
                        }),
                      });
                    }
                    await refresh();
                    setShowAddItemsModal(false);
                    setSelectedItemsToAdd(new Set());
                  } catch (err) {
                    console.error("Failed to add items:", err);
                  } finally {
                    setIsAddingItems(false);
                  }
                }}
                disabled={
                  selectedItemsToAdd.size === 0 ||
                  isAddingItems ||
                  (selectedItemsToAdd.size > remainingSlots && !stack?.unlocked)
                }
                className="flex-1 py-2.5 bg-purple-500 rounded-lg text-white font-mono text-sm font-bold hover:bg-purple-600 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {isAddingItems ? "Adding..." : `Add ${selectedItemsToAdd.size} Item${selectedItemsToAdd.size !== 1 ? "s" : ""}`}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Action buttons - different layouts for filesystem vs standard stacks */}
      {!editMode && (
        <div className="flex items-center justify-end gap-2 flex-wrap">
          {/* FILESYSTEM STACKS: Single Actions dropdown for owners, CDN Links for non-owner members */}
          {stack.isFileSystem ? (
            <>
              {/* Non-owner members just see CDN Links */}
              {!isOwner && books.length > 0 && isMember && (
                <button
                  onClick={() => setShowCdnLinks(true)}
                  className="px-3 py-1.5 rounded-lg text-xs font-mono bg-[#1a1a1a] border border-[#00ff00]/30 text-gray-400 hover:text-[#00ff00] transition-all"
                  title="View CDN links for all items"
                >
                  <LinkIcon size={14} className="inline mr-1" /> CDN Links
                </button>
              )}
              {/* Owners get the consolidated Actions dropdown */}
              {isOwner && (
                <div className="relative">
                  <button
                    onClick={() => setShowActionsMenu(!showActionsMenu)}
                    className="px-3 py-1.5 rounded-lg text-xs font-mono bg-[#1a1a1a] border border-[#00ff00]/30 text-gray-400 hover:text-[#00ff00] transition-all flex items-center gap-1"
                  >
                    Actions <ChevronDownIcon size={14} />
                  </button>
                  {showActionsMenu && (
                    <>
                      {/* Backdrop to close dropdown */}
                      <div
                        className="fixed inset-0 z-40"
                        onClick={() => setShowActionsMenu(false)}
                      />
                      {/* Dropdown menu */}
                      <div className="absolute right-0 top-full mt-1 z-50 bg-[#1a1a1a] border border-[#00ff00]/30 rounded-lg shadow-xl min-w-[180px] py-1">
                        <button
                          onClick={() => {
                            setShowFolderUpload(true);
                            setShowActionsMenu(false);
                          }}
                          className="w-full px-3 py-2 text-left text-xs font-mono text-[#00ff00] hover:bg-[#00ff00]/10 transition-colors flex items-center gap-2"
                        >
                          <FolderIcon size={14} /> Add Folder
                        </button>
                        <button
                          onClick={() => {
                            setShowZipImport(true);
                            setShowActionsMenu(false);
                          }}
                          className="w-full px-3 py-2 text-left text-xs font-mono text-[#00ff00] hover:bg-[#00ff00]/10 transition-colors flex items-center gap-2"
                        >
                          <PackageIcon size={14} /> Import ZIP
                        </button>
                        <button
                          onClick={() => {
                            setShowGitHubImport(true);
                            setShowActionsMenu(false);
                          }}
                          className="w-full px-3 py-2 text-left text-xs font-mono text-[#00ff00] hover:bg-[#00ff00]/10 transition-colors flex items-center gap-2"
                        >
                          <GlobeIcon size={14} /> Import from GitHub
                        </button>
                        {books.length > 0 && (
                          <>
                            <div className="border-t border-[#00ff00]/20 my-1" />
                            <button
                              onClick={() => {
                                setShowCdnLinks(true);
                                setShowActionsMenu(false);
                              }}
                              className="w-full px-3 py-2 text-left text-xs font-mono text-gray-400 hover:text-white hover:bg-white/5 transition-colors flex items-center gap-2"
                            >
                              <LinkIcon size={14} /> CDN Links
                            </button>
                          </>
                        )}
                        <div className="border-t border-[#00ff00]/20 my-1" />
                        <button
                          onClick={() => {
                            setEditName(stack.name);
                            setEditDescription(stack.description || "");
                            setEditMode(true);
                            setShowActionsMenu(false);
                          }}
                          className="w-full px-3 py-2 text-left text-xs font-mono text-gray-400 hover:text-white hover:bg-white/5 transition-colors flex items-center gap-2"
                        >
                          <EditIcon size={14} /> Edit Stack
                        </button>
                      </div>
                    </>
                  )}
                </div>
              )}
            </>
          ) : (
            /* STANDARD STACKS: Separate CDN Links + Edit Stack buttons */
            <>
              {books.length > 0 && isMember && (
                <button
                  onClick={() => setShowCdnLinks(true)}
                  className="px-3 py-1.5 rounded-lg text-xs font-mono bg-[#1a1a1a] text-gray-400 hover:text-[#00ff00] transition-all"
                  title="View CDN links for all items"
                >
                  <LinkIcon size={14} className="inline mr-1" /> CDN Links
                </button>
              )}
              {isOwner && (
                <button
                  onClick={() => {
                    setEditName(stack.name);
                    setEditDescription(stack.description || "");
                    setEditMode(true);
                  }}
                  className="px-3 py-1.5 rounded-lg text-xs font-mono bg-[#1a1a1a] text-gray-400 hover:text-[#00ff00] transition-all"
                >
                  <EditIcon size={14} className="inline mr-1" /> Edit Stack
                </button>
              )}
            </>
          )}
        </div>
      )}

      {/* CDN Links Popup - visible to all members */}
      {showCdnLinks && isMember && (
        <div
          className="fixed inset-0 bg-black/90 z-[9999] flex items-center justify-center p-4"
          onClick={() => {
            setShowCdnLinks(false);
            setCopiedLink(null);
          }}
        >
          <div
            className="w-full max-w-md bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl overflow-hidden max-h-[80vh] flex flex-col"
            onClick={(e: React.MouseEvent) => e.stopPropagation()}
          >
            {/* Header */}
            <div className="p-4 border-b border-[#00ff00]/20 flex items-center justify-between">
              <div className="flex items-center gap-2">
                <LinkIcon size={20} className="text-[#00ff00]" />
                <div>
                  <P className="text-[#00ff00] font-mono font-bold">CDN Links</P>
                  <Small className="text-gray-500 font-mono">{cdnLinks.length} items in stack</Small>
                </div>
              </div>
              <button
                onClick={() => {
                  setShowCdnLinks(false);
                  setCopiedLink(null);
                }}
                className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white transition-colors"
              >
                ✕
              </button>
            </div>

            {/* Links list */}
            <div className="flex-1 overflow-y-auto p-3 space-y-2">
              {cdnLinks.map((link, index) => (
                <div
                  key={link.contentKey}
                  className="bg-[#1a1a1a] rounded-lg p-3 space-y-2"
                >
                  <div className="flex items-start gap-2">
                    <span className="text-[#00ff00]/50 font-mono text-xs mt-0.5">{index + 1}.</span>
                    <div className="flex-1 min-w-0">
                      <P className="text-white font-mono text-sm truncate">{link.title}</P>
                      <Small className="text-gray-500 font-mono">{link.author}</Small>
                    </div>
                  </div>
                  <div className="flex items-center gap-2">
                    <input
                      type="text"
                      value={link.cdnUrl}
                      readOnly
                      className="flex-1 px-2 py-1.5 bg-black border border-[#333] rounded text-[10px] font-mono text-gray-400 truncate focus:outline-none"
                      onClick={(e) => (e.target as HTMLInputElement).select()}
                    />
                    <button
                      onClick={async () => {
                        try {
                          await navigator.clipboard.writeText(link.cdnUrl);
                          setCopiedLink(link.contentKey);
                          setTimeout(() => setCopiedLink(null), 2000);
                        } catch (err) {
                          console.error("Failed to copy:", err);
                        }
                      }}
                      className={`px-2 py-1.5 rounded text-[10px] font-mono font-bold transition-all shrink-0 ${
                        copiedLink === link.contentKey
                          ? "bg-[#00ff00] text-black"
                          : "bg-[#00ff00]/20 text-[#00ff00] hover:bg-[#00ff00]/30"
                      }`}
                    >
                      {copiedLink === link.contentKey ? "✓" : "Copy"}
                    </button>
                  </div>
                </div>
              ))}
            </div>

            {/* Footer with copy all */}
            <div className="p-3 border-t border-[#00ff00]/20">
              <button
                onClick={async () => {
                  const allLinks = cdnLinks.map((link, i) =>
                    `${i + 1}. ${link.title}\n   ${link.cdnUrl}`
                  ).join("\n\n");
                  try {
                    await navigator.clipboard.writeText(allLinks);
                    setCopiedLink("all");
                    setTimeout(() => setCopiedLink(null), 2000);
                  } catch (err) {
                    console.error("Failed to copy all:", err);
                  }
                }}
                className={`w-full py-2.5 rounded-lg font-mono text-sm font-bold transition-all ${
                  copiedLink === "all"
                    ? "bg-[#00ff00] text-black"
                    : "bg-[#00ff00]/20 text-[#00ff00] hover:bg-[#00ff00]/30 border border-[#00ff00]/30"
                }`}
              >
                {copiedLink === "all" ? "✓ Copied All Links" : <><ClipboardIcon size={14} className="inline mr-1" /> Copy All Links</>}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Edit mode hint */}
      {editMode && isOwner && books.length > 1 && (
        <Small className="text-gray-500 font-mono text-center block">
          Use arrows to reorder • Tap ✕ to remove
        </Small>
      )}

      {/* Items List - Tree View or Card Grid */}
      {viewMode === "tree" && stack?.isFileSystem ? (
        <div className="space-y-2">
          {fileTree.length === 0 ? (
            <div className="text-center py-12">
              <div className="text-4xl mb-3 text-[#00ff00]"><FolderIcon size={48} /></div>
              <P className="text-gray-400 font-mono">This filesystem stack is empty</P>
              <Small className="text-gray-500 font-mono block mt-1">
                {isOwner ? "Add files using the import buttons above" : "The owner hasn't added any files yet"}
              </Small>
            </div>
          ) : (
            <FolderTreeView
              nodes={fileTree}
              onFileClick={(contentKey) => {
                const book = books.find(b => b.contentKey === contentKey);
                if (book) onSelectBook(book);
              }}
              expandedByDefault={items.length < 50}
            />
          )}
        </div>
      ) : (
        <div className="space-y-2">
          {books.length === 0 ? (
            <div className="text-center py-12">
              <div className="text-4xl mb-3 text-[#00ff00]"><LibraryIcon size={48} /></div>
              <P className="text-gray-400 font-mono">This stack is empty</P>
              <Small className="text-gray-500 font-mono block mt-1">
                {isOwner ? "Add items from the All Items tab" : "The owner hasn't added any items yet"}
              </Small>
            </div>
          ) : (
            books.map((book, index) => (
              <Card
                key={book.id}
                className={`bg-[#0a0a0a] border transition-all ${
                  editMode
                    ? "border-[#00ff00]/30"
                    : "border-[#1a1a1a] hover:border-[#00ff00]/50 cursor-pointer"
                }`}
                onClick={() => !editMode && onSelectBook(book)}
              >
                <CardContent className="p-3">
                  <div className="flex items-center gap-3">
                    {/* Reorder buttons (edit mode only) */}
                    {isOwner && editMode && (
                      <div className="flex flex-col gap-0.5 shrink-0">
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleMoveItem(book.contentKey!, "up");
                          }}
                          disabled={index === 0 || isReordering}
                          className="w-6 h-6 rounded bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:bg-[#00ff00]/20 hover:text-[#00ff00] transition-all disabled:opacity-30 disabled:cursor-not-allowed text-xs"
                        >
                          ↑
                        </button>
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            handleMoveItem(book.contentKey!, "down");
                          }}
                          disabled={index === books.length - 1 || isReordering}
                          className="w-6 h-6 rounded bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:bg-[#00ff00]/20 hover:text-[#00ff00] transition-all disabled:opacity-30 disabled:cursor-not-allowed text-xs"
                        >
                          ↓
                        </button>
                      </div>
                    )}

                    {/* Rank */}
                    <div className="w-6 h-6 rounded-full bg-[#00ff00]/10 flex items-center justify-center text-xs font-bold text-[#00ff00] font-mono shrink-0">
                      {index + 1}
                    </div>

                    {/* Cover */}
                    <div className="w-10 h-14 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded flex items-center justify-center border border-[#222] shrink-0 overflow-hidden">
                      <CoverImage
                        src={getEffectiveCoverUrl(book)}
                        alt={book.title}
                        className="w-full h-full object-cover"
                        fallbackLogoSize="w-6 h-6"
                      />
                    </div>

                    {/* Info */}
                    <div className="flex-1 min-w-0">
                      <P className="text-sm font-mono text-white truncate">{book.title}</P>
                      <Small className="text-gray-500 font-mono">{book.author}</Small>
                    </div>

                    {/* Remove button (owner only, edit mode) */}
                    {isOwner && editMode && (
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          handleRemoveItem(book.contentKey!);
                        }}
                        disabled={isRemoving === book.contentKey}
                        className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:bg-red-500/20 hover:text-red-400 transition-all shrink-0 disabled:opacity-50"
                        title="Remove from stack"
                      >
                        {isRemoving === book.contentKey ? (
                          <LoadingIcon size={14} className="animate-spin" />
                        ) : (
                          <CloseIcon size={14} />
                        )}
                      </button>
                    )}
                  </div>
                </CardContent>
              </Card>
            ))
          )}
        </div>
      )}

      {/* Filesystem Import Modals */}
      {showFolderUpload && stack && (
        <FolderUploadModal
          isOpen={showFolderUpload}
          onClose={() => {
            setShowFolderUpload(false);
            // Clear initial files if provided (drag-drop complete)
            if (initialFiles && onInitialFilesProcessed) {
              onInitialFilesProcessed();
            }
          }}
          isMember={isMember}
          onUploadFile={handleFsUploadFile}
          onComplete={() => {
            setShowFolderUpload(false);
            refresh();
            // Clear initial files if provided (drag-drop complete)
            if (initialFiles && onInitialFilesProcessed) {
              onInitialFilesProcessed();
            }
          }}
          initialFiles={initialFiles}
        />
      )}

      {showGitHubImport && stack && address && (
        <GitHubImportModal
          isOpen={showGitHubImport}
          onClose={() => setShowGitHubImport(false)}
          isMember={isMember}
          onUploadFile={handleFsUploadFile}
          onSetSourceMeta={handleSetSourceMeta}
          onComplete={() => {
            setShowGitHubImport(false);
            refresh();
          }}
        />
      )}

      {showZipImport && (
        <ZipImportModal
          isOpen={showZipImport}
          onClose={() => setShowZipImport(false)}
          isMember={isMember}
          onUploadFile={handleFsUploadFile}
          onComplete={() => {
            setShowZipImport(false);
            refresh();
          }}
        />
      )}

    </div>
  );
}
src/features/app/components/stack-pricing-modal.tsx
"use client";

import { useState, useEffect } from "react";
import { createPortal } from "react-dom";
import { useAccount, useBalance } from "wagmi";
import { P, Small } from "@neynar/ui";
import { LoadingIcon, WalletIcon } from "@/components/icons/net-library-icons";
import { useSponsoredTransaction } from "@/hooks/use-sponsored-transaction";
import { useWalletCapabilities } from "@/hooks/use-wallet-capabilities";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { formatUnits, type Address } from "viem";
import { base } from "viem/chains";

// USDC Contract on Base
const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" as Address;
const USDC_ABI = [
  {
    name: "transfer",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "to", type: "address" },
      { name: "value", type: "uint256" },
    ],
    outputs: [{ type: "bool" }],
  },
] as const;

// Treasury address for payments
const TREASURY_ADDRESS = "0xAcAD71e697Ef3bb148093b2DD2fCf0845e957627" as const;

// Pricing constants
const UNLOCK_STACK_COST = 5; // $5 USDC to unlock single stack
const STACK_PASS_COST = 10; // $10 USDC for Unlimited Pass

interface StackPricingModalProps {
  isOpen: boolean;
  onClose: () => void;
  mode: "unlock-stack" | "stack-pass";
  stackId?: string; // Required for unlock-stack mode
  stackName?: string;
  onSuccess?: () => void;
}

export function StackPricingModal({
  isOpen,
  onClose,
  mode,
  stackId,
  stackName,
  onSuccess,
}: StackPricingModalProps) {
  const { address } = useAccount();
  const { hasStackPass, refreshMembership } = useMembershipStatus();
  const [mounted, setMounted] = useState(false);
  const [paymentState, setPaymentState] = useState<"idle" | "paying" | "confirming" | "processing" | "complete" | "error">("idle");
  const [error, setError] = useState<string | null>(null);

  // Track client-side mount for portal
  useEffect(() => {
    setMounted(true);
  }, []);

  // Reset state when modal opens/closes
  useEffect(() => {
    if (!isOpen) {
      setPaymentState("idle");
      setError(null);
    }
  }, [isOpen]);

  // Check USDC balance
  const { data: usdcBalance } = useBalance({
    address: address as Address | undefined,
    token: USDC_ADDRESS,
    chainId: base.id,
  });

  const cost = mode === "stack-pass" ? STACK_PASS_COST : UNLOCK_STACK_COST;
  const usdcBalanceFormatted = usdcBalance ? parseFloat(formatUnits(usdcBalance.value, 6)) : 0;

  // Check if the wallet has auxiliary funds (Coinbase Smart Wallet / MagicSpend).
  // These users can pay from their Coinbase exchange balance even if onchain USDC is zero.
  const { hasAuxiliaryFunds } = useWalletCapabilities();
  const hasEnoughUsdc = usdcBalanceFormatted >= cost || hasAuxiliaryFunds;

  // Sponsored transaction hook
  const {
    sendSponsoredTransaction,
    txHash,
    isPending,
    isConfirming,
    isConfirmed,
    error: writeError,
    reset,
    isSponsored,
  } = useSponsoredTransaction();

  // Handle write errors
  useEffect(() => {
    if (writeError && paymentState === "paying") {
      const errMsg = writeError.message?.toLowerCase() || "";
      if (errMsg.includes("user rejected") || errMsg.includes("denied") || errMsg.includes("cancelled")) {
        reset();
        setPaymentState("idle");
        return;
      }
      setError(writeError.message?.slice(0, 60) || "Payment failed");
      setPaymentState("error");
    }
  }, [writeError, paymentState, reset]);

  // Handle transaction confirming
  useEffect(() => {
    if (txHash && isConfirming && paymentState === "paying") {
      setPaymentState("confirming");
    }
  }, [txHash, isConfirming, paymentState]);

  // Handle transaction confirmed
  useEffect(() => {
    if (isConfirmed && txHash && (paymentState === "paying" || paymentState === "confirming")) {
      handlePaymentComplete(txHash);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isConfirmed, txHash]);

  const handlePaymentComplete = async (hash: string) => {
    setPaymentState("processing");

    try {
      if (mode === "unlock-stack" && stackId) {
        // Unlock specific stack
        const response = await fetch("/api/stacks", {
          method: "PUT",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            stackId,
            action: "unlock",
            owner: address,
            txHash: hash,
          }),
        });

        const data = await response.json();
        if (!response.ok) {
          throw new Error(data.error || "Failed to unlock stack");
        }
      } else if (mode === "stack-pass") {
        // Purchase unlimited stack pass
        const response = await fetch("/api/membership/stack-pass", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            address,
            txHash: hash,
          }),
        });

        const data = await response.json();
        if (!response.ok) {
          throw new Error(data.error || "Failed to activate stack pass");
        }

        // Refresh membership data to reflect new pass
        refreshMembership?.();
      }

      setPaymentState("complete");
      reset();
      onSuccess?.();

      // Auto-close after success
      setTimeout(() => {
        onClose();
      }, 2000);
    } catch (err) {
      console.error("Payment processing error:", err);
      setError(err instanceof Error ? err.message : "Failed to process payment");
      setPaymentState("error");
    }
  };

  const handlePayment = async () => {
    if (!address) return;

    setError(null);
    setPaymentState("paying");

    try {
      await sendSponsoredTransaction({
        address: USDC_ADDRESS,
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        abi: USDC_ABI as any,
        functionName: "transfer",
        args: [TREASURY_ADDRESS, BigInt(cost * 1_000_000)], // USDC has 6 decimals
      });
    } catch (err) {
      console.error("Transaction failed:", err);
    }
  };

  if (!isOpen || !mounted) return null;

  // If user already has stack pass and trying to buy it again
  if (mode === "stack-pass" && hasStackPass) {
    return createPortal(
      <div
        className="fixed inset-0 bg-black/90 z-[9999] flex items-center justify-center p-4"
        onClick={onClose}
      >
        <div
          className="w-full max-w-sm bg-[#0a0a0a] border border-[#00ff00]/50 rounded-xl overflow-hidden"
          onClick={(e: React.MouseEvent) => e.stopPropagation()}
        >
          <div className="p-6 text-center">
            <div className="w-16 h-16 mx-auto mb-4 bg-[#00ff00]/20 rounded-full flex items-center justify-center">
              <span className="text-3xl">✓</span>
            </div>
            <P className="text-[#00ff00] font-mono font-bold">You already have the Unlimited Pass!</P>
            <Small className="text-gray-400 font-mono block mt-2">
              All your stacks have unlimited capacity.
            </Small>
            <button
              onClick={onClose}
              className="mt-4 px-6 py-2 bg-[#00ff00] text-black font-mono font-bold rounded-lg hover:bg-[#00ff00]/90 transition-colors"
            >
              Got it
            </button>
          </div>
        </div>
      </div>,
      document.body
    );
  }

  const modalContent = (
    <div
      className="fixed inset-0 bg-black/90 z-[9999] flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="w-full max-w-sm bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl overflow-hidden"
        onClick={(e: React.MouseEvent) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 py-3 border-b border-[#00ff00]/20 flex items-center justify-between">
          <P className="text-[#00ff00] font-mono font-medium">
            {mode === "stack-pass" ? "Unlimited Pass" : `Unlock "${stackName || "Stack"}"`}
          </P>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-lg bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors"
          >
            ✕
          </button>
        </div>

        <div className="p-4 space-y-4">
          {/* Success State */}
          {paymentState === "complete" && (
            <div className="text-center py-4">
              <div className="w-16 h-16 mx-auto mb-4 bg-[#00ff00]/20 rounded-full flex items-center justify-center animate-pulse">
                <span className="text-3xl">✓</span>
              </div>
              <P className="text-[#00ff00] font-mono font-bold">
                {mode === "stack-pass" ? "Unlimited Pass Activated!" : "Stack Unlocked!"}
              </P>
              <Small className="text-gray-400 font-mono block mt-2">
                {mode === "stack-pass"
                  ? "All your stacks now have unlimited capacity!"
                  : "This stack now has unlimited capacity!"}
              </Small>
            </div>
          )}

          {/* Error State */}
          {paymentState === "error" && (
            <div className="text-center py-4">
              <div className="w-16 h-16 mx-auto mb-4 bg-red-500/20 rounded-full flex items-center justify-center">
                <span className="text-3xl">!</span>
              </div>
              <P className="text-red-400 font-mono font-bold">Payment Failed</P>
              <Small className="text-gray-400 font-mono block mt-2">{error || "Something went wrong"}</Small>
              <button
                onClick={() => {
                  setPaymentState("idle");
                  setError(null);
                  reset();
                }}
                className="mt-4 px-6 py-2 bg-[#1a1a1a] text-white font-mono rounded-lg hover:bg-[#222] transition-colors"
              >
                Try Again
              </button>
            </div>
          )}

          {/* Processing States */}
          {(paymentState === "paying" || paymentState === "confirming" || paymentState === "processing") && (
            <div className="text-center py-4">
              <div className="w-16 h-16 mx-auto mb-4 bg-[#00ff00]/20 rounded-full flex items-center justify-center animate-pulse">
                <LoadingIcon size={28} className="text-[#00ff00] animate-spin" />
              </div>
              <P className="text-[#00ff00] font-mono font-bold">
                {paymentState === "paying" && "Confirm in wallet..."}
                {paymentState === "confirming" && "Confirming transaction..."}
                {paymentState === "processing" && "Processing..."}
              </P>
            </div>
          )}

          {/* Idle State - Show pricing info */}
          {paymentState === "idle" && (
            <>
              {/* Feature comparison */}
              {mode === "stack-pass" ? (
                <div className="space-y-3">
                  <div className="p-4 bg-gradient-to-br from-purple-500/20 to-[#00ff00]/20 border border-purple-500/40 rounded-xl">
                    <div className="flex items-center gap-3 mb-3">
                      <div className="w-12 h-12 bg-purple-500/30 rounded-xl flex items-center justify-center">
                        <span className="text-2xl">∞</span>
                      </div>
                      <div>
                        <P className="text-white font-mono font-bold">Unlimited Pass</P>
                        <Small className="text-[#00ff00] font-mono">${STACK_PASS_COST} USDC - One time</Small>
                      </div>
                    </div>
                    <div className="space-y-2 text-sm">
                      <div className="flex items-center gap-2">
                        <span className="text-[#00ff00]">✓</span>
                        <Small className="text-gray-300 font-mono">All stacks become unlimited</Small>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="text-[#00ff00]">✓</span>
                        <Small className="text-gray-300 font-mono">Create as many stacks as you want</Small>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="text-[#00ff00]">✓</span>
                        <Small className="text-gray-300 font-mono">Never hit a limit again</Small>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="text-[#00ff00]">✓</span>
                        <Small className="text-gray-300 font-mono">One purchase, forever</Small>
                      </div>
                    </div>
                  </div>

                  <div className="p-3 bg-[#1a1a1a] border border-gray-700 rounded-lg">
                    <Small className="text-gray-400 font-mono block text-center">
                      vs. $5 per individual stack unlock
                    </Small>
                    <Small className="text-gray-500 font-mono block text-center mt-1">
                      Worth it if you plan 20+ stacks!
                    </Small>
                  </div>
                </div>
              ) : (
                <div className="space-y-3">
                  <div className="p-4 bg-[#00ff00]/10 border border-[#00ff00]/30 rounded-xl">
                    <div className="flex items-center gap-3 mb-3">
                      <div className="w-12 h-12 bg-[#00ff00]/20 rounded-xl flex items-center justify-center">
                        <span className="text-2xl">🔓</span>
                      </div>
                      <div>
                        <P className="text-white font-mono font-bold">Unlock This Stack</P>
                        <Small className="text-[#00ff00] font-mono">${UNLOCK_STACK_COST} USDC</Small>
                      </div>
                    </div>
                    <div className="space-y-2 text-sm">
                      <div className="flex items-center gap-2">
                        <span className="text-[#00ff00]">✓</span>
                        <Small className="text-gray-300 font-mono">Unlimited items in this stack</Small>
                      </div>
                      <div className="flex items-center gap-2">
                        <span className="text-[#00ff00]">✓</span>
                        <Small className="text-gray-300 font-mono">Currently limited to 20 items</Small>
                      </div>
                    </div>
                  </div>

                  <div className="p-3 bg-purple-500/10 border border-purple-500/30 rounded-lg">
                    <Small className="text-purple-400 font-mono block text-center">
                      💡 Tip: Get unlimited everything for ${STACK_PASS_COST}
                    </Small>
                  </div>
                </div>
              )}

              {/* Balance warning */}
              {!hasEnoughUsdc && (
                <div className="p-3 bg-red-500/10 border border-red-500/30 rounded-lg">
                  <div className="flex items-start gap-2">
                    <WalletIcon size={20} className="text-red-400 shrink-0 mt-0.5" />
                    <div>
                      <P className="text-red-400 font-mono text-sm font-medium">Insufficient USDC</P>
                      <Small className="text-red-400/70 font-mono">
                        Need ${cost}, you have ${usdcBalanceFormatted.toFixed(2)}
                      </Small>
                    </div>
                  </div>
                </div>
              )}

              {/* Action buttons */}
              <div className="flex gap-2">
                <button
                  onClick={onClose}
                  className="flex-1 py-2.5 bg-[#1a1a1a] rounded-lg text-gray-400 font-mono text-sm hover:bg-[#222] transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={handlePayment}
                  disabled={isPending || !hasEnoughUsdc}
                  className={`flex-1 py-2.5 rounded-lg font-mono text-sm font-bold transition-colors disabled:opacity-50 ${
                    mode === "stack-pass"
                      ? "bg-purple-500 text-white hover:bg-purple-600"
                      : "bg-[#00ff00] text-black hover:bg-[#00ff00]/90"
                  }`}
                >
                  {isPending ? "Processing..." : `Pay $${cost} USDC`}
                  {isSponsored && <span className="ml-1 text-[10px] opacity-70">⛽</span>}
                </button>
              </div>
            </>
          )}
        </div>
      </div>
    </div>
  );

  return createPortal(modalContent, document.body);
}

// Compact pricing info component for embedding in other views
export function StackPricingInfo({
  onUnlockStack,
  onBuyPass,
  showPassOption = true,
}: {
  onUnlockStack?: () => void;
  onBuyPass?: () => void;
  showPassOption?: boolean;
}) {
  return (
    <div className="p-3 bg-[#0a0a0a] border border-[#00ff00]/20 rounded-lg space-y-2">
      <div className="flex items-center justify-between">
        <Small className="text-gray-400 font-mono">Stack Pricing</Small>
      </div>

      <div className="space-y-2">
        {/* Free tier */}
        <div className="flex items-center justify-between">
          <Small className="text-gray-500 font-mono">Free Stack</Small>
          <Small className="text-gray-500 font-mono">20 items max</Small>
        </div>

        {/* Per-stack unlock */}
        <div className="flex items-center justify-between">
          <Small className="text-[#00ff00] font-mono">Unlock Stack</Small>
          <div className="flex items-center gap-2">
            <Small className="text-[#00ff00] font-mono">$5 USDC</Small>
            {onUnlockStack && (
              <button
                onClick={onUnlockStack}
                className="px-2 py-0.5 text-[10px] bg-[#00ff00]/20 text-[#00ff00] rounded font-mono hover:bg-[#00ff00]/30 transition-colors"
              >
                Unlock
              </button>
            )}
          </div>
        </div>

        {/* Stack pass */}
        {showPassOption && (
          <div className="flex items-center justify-between pt-2 border-t border-[#00ff00]/10">
            <div>
              <Small className="text-purple-400 font-mono block">Unlimited Pass</Small>
              <Small className="text-gray-600 font-mono text-[10px]">All stacks, forever</Small>
            </div>
            <div className="flex items-center gap-2">
              <Small className="text-purple-400 font-mono">$10 USDC</Small>
              {onBuyPass && (
                <button
                  onClick={onBuyPass}
                  className="px-2 py-0.5 text-[10px] bg-purple-500/20 text-purple-400 rounded font-mono hover:bg-purple-500/30 transition-colors"
                >
                  Buy
                </button>
              )}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
src/features/app/components/text-editor-upload.tsx
"use client";

import { useState, useRef, useCallback, useEffect } from "react";
import { Card, CardContent, Button, Small, H4 } from "@neynar/ui";
import { LinkIcon, WarningIcon, LockIcon, CheckIcon, LibraryIcon } from "@/components/icons/net-library-icons";
import type { Category, Stack } from "@/features/app/types";

// Track current formatting state
interface FormatState {
  bold: boolean;
  italic: boolean;
  underline: boolean;
  alignLeft: boolean;
  alignCenter: boolean;
  alignRight: boolean;
  orderedList: boolean;
  unorderedList: boolean;
}

// Draft storage key and interface
const DRAFT_STORAGE_KEY = "net-library-editor-draft";
const DRAFT_SAVE_DELAY = 1000; // Save after 1 second of no typing

interface EditorDraft {
  content: string; // HTML content
  title: string;
  author: string;
  publicationYear: string;
  publisher: string;
  coverArtUrl: string;
  selectedCategories: string[];
  selectedStackIds: string[];
  savedAt: number;
}

// Load draft from localStorage
function loadDraft(): EditorDraft | null {
  if (typeof window === "undefined") return null;
  try {
    const saved = localStorage.getItem(DRAFT_STORAGE_KEY);
    if (!saved) return null;
    const draft = JSON.parse(saved) as EditorDraft;
    // Only restore drafts less than 7 days old
    const sevenDays = 7 * 24 * 60 * 60 * 1000;
    if (Date.now() - draft.savedAt > sevenDays) {
      localStorage.removeItem(DRAFT_STORAGE_KEY);
      return null;
    }
    return draft;
  } catch {
    return null;
  }
}

// Save draft to localStorage
function saveDraft(draft: EditorDraft): void {
  if (typeof window === "undefined") return;
  try {
    localStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(draft));
  } catch {
    // localStorage might be full or disabled
  }
}

// Clear draft from localStorage
function clearDraft(): void {
  if (typeof window === "undefined") return;
  try {
    localStorage.removeItem(DRAFT_STORAGE_KEY);
  } catch {
    // Ignore errors
  }
}

// Sanitize HTML to only allow safe tags
function sanitizeHtml(html: string): string {
  // Create a temporary element to parse HTML
  const div = document.createElement("div");
  div.innerHTML = html;

  // Remove script tags and event handlers
  const scripts = div.querySelectorAll("script");
  scripts.forEach(s => s.remove());

  // Remove event handlers from all elements
  const allElements = div.querySelectorAll("*");
  allElements.forEach(el => {
    // Get all attributes
    const attrs = Array.from(el.attributes);
    attrs.forEach(attr => {
      // Remove event handlers and dangerous attributes
      if (attr.name.startsWith("on") || attr.name === "href" && attr.value.startsWith("javascript:")) {
        el.removeAttribute(attr.name);
      }
    });
  });

  return div.innerHTML;
}

// Convert HTML to plain text with markdown-style links
function htmlToTextWithLinks(html: string): string {
  const div = document.createElement("div");
  div.innerHTML = html;

  // Convert <a> tags to markdown-style [text](url)
  const links = div.querySelectorAll("a");
  links.forEach(link => {
    const url = link.getAttribute("href");
    const text = link.textContent;
    if (url && text) {
      const markdown = `[${text}](${url})`;
      link.replaceWith(markdown);
    }
  });

  // Convert <br> to newlines
  div.innerHTML = div.innerHTML.replace(/<br\s*\/?>/gi, "\n");

  // Convert <p> to double newlines
  const paragraphs = div.querySelectorAll("p");
  paragraphs.forEach(p => {
    p.innerHTML = p.innerHTML + "\n\n";
  });

  return div.textContent || "";
}

interface TextEditorUploadProps {
  categories: Category[];
  stacks: Stack[];
  isLoadingStacks: boolean;
  onUpload: (data: {
    content: string;
    htmlContent: string;
    title: string;
    author: string;
    selectedCategories: string[];
    selectedStackIds: string[];
    publicationYear?: string;
    publisher?: string;
    coverArtUrl?: string;
  }) => Promise<{ success: boolean; error?: string }>;
  isUploading: boolean;
}

export function TextEditorUpload({
  categories,
  stacks,
  isLoadingStacks,
  onUpload,
  isUploading,
}: TextEditorUploadProps) {
  const editorRef = useRef<HTMLDivElement>(null);
  const saveTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  const [title, setTitle] = useState("");
  const [author, setAuthor] = useState("");
  const [publicationYear, setPublicationYear] = useState("");
  const [publisher, setPublisher] = useState("");
  const [coverArtUrl, setCoverArtUrl] = useState("");
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [selectedStackIds, setSelectedStackIds] = useState<string[]>([]);
  const [showCategoryDropdown, setShowCategoryDropdown] = useState(false);
  const [showStackDropdown, setShowStackDropdown] = useState(false);
  const [showLinkModal, setShowLinkModal] = useState(false);
  const [linkUrl, setLinkUrl] = useState("");
  const [linkText, setLinkText] = useState("");
  const [selectionRange, setSelectionRange] = useState<Range | null>(null);
  const [wordCount, setWordCount] = useState(0);
  const [draftStatus, setDraftStatus] = useState<"idle" | "saving" | "saved" | "recovered">("idle");
  const [hasDraft, setHasDraft] = useState(false);
  const [showDraftInfo, setShowDraftInfo] = useState(false);
  const [formatState, setFormatState] = useState<FormatState>({
    bold: false,
    italic: false,
    underline: false,
    alignLeft: true,
    alignCenter: false,
    alignRight: false,
    orderedList: false,
    unorderedList: false,
  });

  // Load draft on mount
  useEffect(() => {
    const draft = loadDraft();
    if (draft && (draft.content || draft.title)) {
      setHasDraft(true);
    }
  }, []);

  // Restore draft
  const restoreDraft = useCallback(() => {
    const draft = loadDraft();
    if (!draft) return;

    if (editorRef.current && draft.content) {
      editorRef.current.innerHTML = draft.content;
    }
    setTitle(draft.title || "");
    setAuthor(draft.author || "");
    setPublicationYear(draft.publicationYear || "");
    setPublisher(draft.publisher || "");
    setCoverArtUrl(draft.coverArtUrl || "");
    setSelectedCategories(draft.selectedCategories || []);
    setSelectedStackIds(draft.selectedStackIds || []);
    setHasDraft(false);
    setDraftStatus("recovered");

    // Update word count after restoring
    setTimeout(() => {
      if (editorRef.current) {
        const text = editorRef.current.textContent || "";
        const words = text.trim().split(/\s+/).filter(w => w.length > 0);
        setWordCount(words.length);
      }
    }, 0);

    // Clear recovered status after a moment
    setTimeout(() => setDraftStatus("idle"), 2000);
  }, []);

  // Discard draft
  const discardDraft = useCallback(() => {
    clearDraft();
    setHasDraft(false);
  }, []);

  // Save draft (debounced)
  const scheduleSaveDraft = useCallback(() => {
    // Clear any pending save
    if (saveTimeoutRef.current) {
      clearTimeout(saveTimeoutRef.current);
    }

    setDraftStatus("saving");

    saveTimeoutRef.current = setTimeout(() => {
      const content = editorRef.current?.innerHTML || "";

      // Only save if there's actual content
      if (!content && !title) {
        setDraftStatus("idle");
        return;
      }

      saveDraft({
        content,
        title,
        author,
        publicationYear,
        publisher,
        coverArtUrl,
        selectedCategories,
        selectedStackIds,
        savedAt: Date.now(),
      });

      setDraftStatus("saved");

      // Reset status after a moment
      setTimeout(() => setDraftStatus("idle"), 2000);
    }, DRAFT_SAVE_DELAY);
  }, [title, author, publicationYear, publisher, coverArtUrl, selectedCategories, selectedStackIds]);

  // Cleanup timeout on unmount
  useEffect(() => {
    return () => {
      if (saveTimeoutRef.current) {
        clearTimeout(saveTimeoutRef.current);
      }
    };
  }, []);

  // Auto-save when form fields change (scheduleSaveDraft already depends on these,
  // but we need this effect to trigger saves when user edits form fields directly)
  const formFieldsChanged = `${title}|${author}|${publicationYear}|${publisher}|${coverArtUrl}|${selectedCategories.join(",")}|${selectedStackIds.join(",")}`;
  const prevFormFields = useRef(formFieldsChanged);

  useEffect(() => {
    // Skip if nothing actually changed (prevents double-saves)
    if (prevFormFields.current === formFieldsChanged) return;
    prevFormFields.current = formFieldsChanged;

    // Skip initial render (all empty)
    if (!title && !author && !publicationYear && !publisher && !coverArtUrl &&
        selectedCategories.length === 0 && selectedStackIds.length === 0) return;

    scheduleSaveDraft();
  }, [formFieldsChanged, scheduleSaveDraft, title, author, publicationYear, publisher, coverArtUrl, selectedCategories, selectedStackIds]);

  // Update formatting state based on current selection
  const updateFormatState = useCallback(() => {
    setFormatState({
      bold: document.queryCommandState("bold"),
      italic: document.queryCommandState("italic"),
      underline: document.queryCommandState("underline"),
      alignLeft: document.queryCommandState("justifyLeft"),
      alignCenter: document.queryCommandState("justifyCenter"),
      alignRight: document.queryCommandState("justifyRight"),
      orderedList: document.queryCommandState("insertOrderedList"),
      unorderedList: document.queryCommandState("insertUnorderedList"),
    });
  }, []);

  // Update word count
  const updateWordCount = useCallback(() => {
    if (editorRef.current) {
      const text = editorRef.current.textContent || "";
      const words = text.trim().split(/\s+/).filter(w => w.length > 0);
      setWordCount(words.length);
    }
  }, []);

  // Handle content change
  const handleInput = useCallback(() => {
    updateWordCount();
    updateFormatState();
    scheduleSaveDraft();
  }, [updateWordCount, updateFormatState, scheduleSaveDraft]);

  // Handle selection change to update toolbar state
  const handleSelectionChange = useCallback(() => {
    // Only update if editor is focused
    if (editorRef.current?.contains(document.activeElement) ||
        document.activeElement === editorRef.current) {
      updateFormatState();
    }
  }, [updateFormatState]);

  // Listen for selection changes
  useEffect(() => {
    document.addEventListener("selectionchange", handleSelectionChange);
    return () => document.removeEventListener("selectionchange", handleSelectionChange);
  }, [handleSelectionChange]);

  // Execute format command and update state
  const execFormat = useCallback((command: string, value?: string) => {
    document.execCommand(command, false, value);
    updateFormatState();
    editorRef.current?.focus();
  }, [updateFormatState]);

  // Handle paste - strip color styles so text inherits editor's white color
  const handlePaste = useCallback((e: React.ClipboardEvent) => {
    e.preventDefault();

    const html = e.clipboardData.getData("text/html");
    const plainText = e.clipboardData.getData("text/plain");

    if (html) {
      // Parse HTML and strip color-related styles
      const div = document.createElement("div");
      div.innerHTML = html;

      // Remove color and background-color from all elements
      const allElements = div.querySelectorAll("*");
      allElements.forEach(el => {
        if (el instanceof HTMLElement) {
          // Remove inline color styles
          el.style.color = "";
          el.style.backgroundColor = "";
          el.style.background = "";

          // Also check for style attribute containing color
          const style = el.getAttribute("style");
          if (style) {
            const cleanedStyle = style
              .replace(/color\s*:\s*[^;]+;?/gi, "")
              .replace(/background(-color)?\s*:\s*[^;]+;?/gi, "")
              .trim();
            if (cleanedStyle) {
              el.setAttribute("style", cleanedStyle);
            } else {
              el.removeAttribute("style");
            }
          }
        }
      });

      // Insert the cleaned HTML
      const selection = window.getSelection();
      if (selection && selection.rangeCount > 0) {
        const range = selection.getRangeAt(0);
        range.deleteContents();

        // Create a document fragment from the cleaned HTML
        const fragment = document.createRange().createContextualFragment(div.innerHTML);
        range.insertNode(fragment);

        // Move cursor to end
        range.collapse(false);
        selection.removeAllRanges();
        selection.addRange(range);
      }
    } else if (plainText) {
      // Plain text paste
      document.execCommand("insertText", false, plainText);
    }

    updateWordCount();
  }, [updateWordCount]);

  // Toggle category selection
  const toggleCategory = (categoryId: string) => {
    setSelectedCategories(prev => {
      if (prev.includes(categoryId)) {
        return prev.filter(id => id !== categoryId);
      }
      if (prev.length >= 3) return prev; // Max 3
      return [...prev, categoryId];
    });
  };

  // Toggle stack selection
  const toggleStack = (stackId: string) => {
    setSelectedStackIds(prev =>
      prev.includes(stackId)
        ? prev.filter(id => id !== stackId)
        : [...prev, stackId]
    );
  };

  // Insert link
  const handleInsertLink = () => {
    // Save current selection before opening modal
    const selection = window.getSelection();
    if (selection && selection.rangeCount > 0) {
      const range = selection.getRangeAt(0);
      setSelectionRange(range);
      // Pre-fill link text with selection
      setLinkText(selection.toString());
    }
    setShowLinkModal(true);
  };

  // Confirm link insertion
  const confirmInsertLink = () => {
    if (!linkUrl) return;

    const url = linkUrl.startsWith("http") ? linkUrl : `https://${linkUrl}`;
    const text = linkText || url;

    const link = document.createElement("a");
    link.href = url;
    link.textContent = text;
    link.target = "_blank";
    link.rel = "noopener noreferrer";
    link.className = "text-[#00ff00] underline hover:text-[#00ff00]/80";

    if (selectionRange && editorRef.current?.contains(selectionRange.commonAncestorContainer)) {
      // Replace selection with link
      selectionRange.deleteContents();
      selectionRange.insertNode(link);
    } else {
      // Insert at end
      editorRef.current?.appendChild(link);
    }

    // Reset
    setShowLinkModal(false);
    setLinkUrl("");
    setLinkText("");
    setSelectionRange(null);
    updateWordCount();
  };

  // Handle upload
  const [uploadError, setUploadError] = useState<string | null>(null);

  const handleUpload = async () => {
    if (!editorRef.current || !title.trim()) return;

    const htmlContent = sanitizeHtml(editorRef.current.innerHTML);
    const textContent = htmlToTextWithLinks(htmlContent);

    if (!textContent.trim()) return;

    // Clear any previous error
    setUploadError(null);

    const result = await onUpload({
      content: textContent,
      htmlContent,
      title: title.trim(),
      author: author.trim() || "Anonymous",
      selectedCategories,
      selectedStackIds,
      publicationYear: publicationYear.trim() || undefined,
      publisher: publisher.trim() || undefined,
      coverArtUrl: coverArtUrl.trim() || undefined,
    });

    // Only clear state if upload was successful
    if (result.success) {
      // Clear draft after successful upload
      clearDraft();
      setDraftStatus("idle");

      // Clear editor state
      if (editorRef.current) {
        editorRef.current.innerHTML = "";
      }
      setTitle("");
      setAuthor("");
      setPublicationYear("");
      setPublisher("");
      setCoverArtUrl("");
      setSelectedCategories([]);
      setSelectedStackIds([]);
      setWordCount(0);
    } else {
      // Show error message
      setUploadError(result.error || "Upload failed. Please try again.");
    }
  };

  const hasContent = wordCount > 0 && title.trim().length > 0;

  return (
    <div className="space-y-4">
      {/* Draft Recovery Banner */}
      {hasDraft && (
        <Card className="bg-yellow-500/10 border border-yellow-500/30">
          <CardContent className="p-3">
            <div className="flex items-center justify-between gap-3">
              <div className="flex items-center gap-2 min-w-0">
                <span className="text-yellow-500">📝</span>
                <Small className="text-yellow-400 font-mono">You have an unsaved draft</Small>
              </div>
              <div className="flex items-center gap-2 shrink-0">
                <button
                  onClick={restoreDraft}
                  className="px-3 py-1.5 rounded bg-yellow-500/20 text-yellow-400 text-xs font-mono hover:bg-yellow-500/30 transition-colors"
                >
                  Restore
                </button>
                <button
                  onClick={discardDraft}
                  className="px-3 py-1.5 rounded bg-gray-800 text-gray-400 text-xs font-mono hover:bg-gray-700 transition-colors"
                >
                  Discard
                </button>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Editor Header */}
      <Card className="bg-[#0a0a0a] border border-[#00ff00]/30">
        <CardContent className="p-4">
          <div className="flex items-center justify-between mb-3">
            <H4 className="text-[#00ff00] font-mono">Write Something</H4>
            <div className="flex items-center gap-2">
              {/* Draft status indicator */}
              {draftStatus !== "idle" && (
                <Small className={`font-mono text-xs flex items-center gap-1 ${
                  draftStatus === "saving" ? "text-gray-500" :
                  draftStatus === "saved" ? "text-green-500" :
                  "text-yellow-500"
                }`}>
                  {draftStatus === "saving" && (
                    <>
                      <span className="w-1.5 h-1.5 bg-gray-500 rounded-full animate-pulse" />
                      Saving...
                    </>
                  )}
                  {draftStatus === "saved" && (
                    <>
                      <span className="text-green-500">✓</span>
                      Draft saved
                    </>
                  )}
                  {draftStatus === "recovered" && (
                    <>
                      <span className="text-yellow-500">↩</span>
                      Draft restored
                    </>
                  )}
                </Small>
              )}
              {/* Draft info button */}
              <div className="relative">
                <button
                  onClick={() => setShowDraftInfo(!showDraftInfo)}
                  className="w-5 h-5 rounded-full bg-gray-800 text-gray-500 text-[10px] font-mono hover:bg-gray-700 hover:text-gray-400 transition-colors flex items-center justify-center"
                  title="Draft info"
                >
                  i
                </button>
                {showDraftInfo && (
                  <>
                    {/* Backdrop to close on click outside */}
                    <div
                      className="fixed inset-0 z-40"
                      onClick={() => setShowDraftInfo(false)}
                    />
                    {/* Info tooltip */}
                    <div className="absolute right-0 top-full mt-2 w-56 bg-[#1a1a1a] border border-gray-700 rounded-lg p-3 z-50 shadow-xl">
                      <div className="text-xs font-mono space-y-2">
                        <div className="flex items-center gap-2 text-[#00ff00]">
                          <span>💾</span>
                          <span className="font-medium">Auto-Save</span>
                        </div>
                        <p className="text-gray-400 leading-relaxed">
                          Your work is saved automatically as you type.
                        </p>
                        <div className="pt-2 border-t border-gray-700">
                          <p className="text-gray-500 text-[10px]">
                            Drafts are stored locally and expire after 7 days. Upload to save permanently.
                          </p>
                        </div>
                      </div>
                    </div>
                  </>
                )}
              </div>
              <div className="w-px h-4 bg-gray-700" />
              <Small className="text-gray-500 font-mono">{wordCount} words</Small>
            </div>
          </div>

          {/* Toolbar */}
          <div className="flex items-center gap-1 mb-3 pb-3 border-b border-[#00ff00]/20 flex-wrap">
            {/* Text Style */}
            <button
              onClick={() => execFormat("bold")}
              className={`w-8 h-8 rounded font-bold transition-all ${
                formatState.bold
                  ? "bg-[#00ff00] text-black border border-[#00ff00]"
                  : "bg-black border border-[#00ff00]/30 text-white hover:bg-[#00ff00]/10"
              }`}
              title="Bold (Ctrl+B)"
            >
              B
            </button>
            <button
              onClick={() => execFormat("italic")}
              className={`w-8 h-8 rounded italic transition-all ${
                formatState.italic
                  ? "bg-[#00ff00] text-black border border-[#00ff00]"
                  : "bg-black border border-[#00ff00]/30 text-white hover:bg-[#00ff00]/10"
              }`}
              title="Italic (Ctrl+I)"
            >
              I
            </button>
            <button
              onClick={() => execFormat("underline")}
              className={`w-8 h-8 rounded underline transition-all ${
                formatState.underline
                  ? "bg-[#00ff00] text-black border border-[#00ff00]"
                  : "bg-black border border-[#00ff00]/30 text-white hover:bg-[#00ff00]/10"
              }`}
              title="Underline (Ctrl+U)"
            >
              U
            </button>

            <div className="w-px h-6 bg-[#00ff00]/20 mx-1" />

            {/* Font Size */}
            <button
              onClick={() => execFormat("fontSize", "2")}
              className="w-8 h-8 rounded bg-black border border-[#00ff00]/30 text-white text-xs hover:bg-[#00ff00]/10 transition-colors"
              title="Small Text"
            >
              A
            </button>
            <button
              onClick={() => execFormat("fontSize", "4")}
              className="w-8 h-8 rounded bg-black border border-[#00ff00]/30 text-white text-sm hover:bg-[#00ff00]/10 transition-colors"
              title="Normal Text"
            >
              A
            </button>
            <button
              onClick={() => execFormat("fontSize", "6")}
              className="w-8 h-8 rounded bg-black border border-[#00ff00]/30 text-white text-lg hover:bg-[#00ff00]/10 transition-colors"
              title="Large Text"
            >
              A
            </button>

            <div className="w-px h-6 bg-[#00ff00]/20 mx-1" />

            {/* Alignment */}
            <button
              onClick={() => execFormat("justifyLeft")}
              className={`w-8 h-8 rounded transition-all flex items-center justify-center ${
                formatState.alignLeft
                  ? "bg-[#00ff00] text-black border border-[#00ff00]"
                  : "bg-black border border-[#00ff00]/30 text-white hover:bg-[#00ff00]/10"
              }`}
              title="Align Left"
            >
              <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                <path d="M2 4.5A.5.5 0 012.5 4h15a.5.5 0 010 1h-15a.5.5 0 01-.5-.5zm0 4A.5.5 0 012.5 8h10a.5.5 0 010 1h-10a.5.5 0 01-.5-.5zm0 4a.5.5 0 01.5-.5h15a.5.5 0 010 1h-15a.5.5 0 01-.5-.5zm0 4a.5.5 0 01.5-.5h10a.5.5 0 010 1h-10a.5.5 0 01-.5-.5z"/>
              </svg>
            </button>
            <button
              onClick={() => execFormat("justifyCenter")}
              className={`w-8 h-8 rounded transition-all flex items-center justify-center ${
                formatState.alignCenter
                  ? "bg-[#00ff00] text-black border border-[#00ff00]"
                  : "bg-black border border-[#00ff00]/30 text-white hover:bg-[#00ff00]/10"
              }`}
              title="Align Center"
            >
              <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                <path d="M2 4.5A.5.5 0 012.5 4h15a.5.5 0 010 1h-15a.5.5 0 01-.5-.5zm2.5 4a.5.5 0 01.5-.5h10a.5.5 0 010 1h-10a.5.5 0 01-.5-.5zm-2.5 4a.5.5 0 01.5-.5h15a.5.5 0 010 1h-15a.5.5 0 01-.5-.5zm2.5 4a.5.5 0 01.5-.5h10a.5.5 0 010 1h-10a.5.5 0 01-.5-.5z"/>
              </svg>
            </button>
            <button
              onClick={() => execFormat("justifyRight")}
              className={`w-8 h-8 rounded transition-all flex items-center justify-center ${
                formatState.alignRight
                  ? "bg-[#00ff00] text-black border border-[#00ff00]"
                  : "bg-black border border-[#00ff00]/30 text-white hover:bg-[#00ff00]/10"
              }`}
              title="Align Right"
            >
              <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                <path d="M2 4.5A.5.5 0 012.5 4h15a.5.5 0 010 1h-15a.5.5 0 01-.5-.5zm5 4a.5.5 0 01.5-.5h10a.5.5 0 010 1h-10a.5.5 0 01-.5-.5zm-5 4a.5.5 0 01.5-.5h15a.5.5 0 010 1h-15a.5.5 0 01-.5-.5zm5 4a.5.5 0 01.5-.5h10a.5.5 0 010 1h-10a.5.5 0 01-.5-.5z"/>
              </svg>
            </button>

            <div className="w-px h-6 bg-[#00ff00]/20 mx-1" />

            {/* Lists */}
            <button
              onClick={() => execFormat("insertUnorderedList")}
              className={`w-8 h-8 rounded transition-all flex items-center justify-center ${
                formatState.unorderedList
                  ? "bg-[#00ff00] text-black border border-[#00ff00]"
                  : "bg-black border border-[#00ff00]/30 text-white hover:bg-[#00ff00]/10"
              }`}
              title="Bullet List"
            >
              <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                <path d="M3 4a1 1 0 100 2 1 1 0 000-2zm3.5.5a.5.5 0 01.5-.5h10a.5.5 0 010 1h-10a.5.5 0 01-.5-.5zM3 9a1 1 0 100 2 1 1 0 000-2zm3.5.5a.5.5 0 01.5-.5h10a.5.5 0 010 1h-10a.5.5 0 01-.5-.5zM3 14a1 1 0 100 2 1 1 0 000-2zm3.5.5a.5.5 0 01.5-.5h10a.5.5 0 010 1h-10a.5.5 0 01-.5-.5z"/>
              </svg>
            </button>
            <button
              onClick={() => execFormat("insertOrderedList")}
              className={`w-8 h-8 rounded transition-all flex items-center justify-center ${
                formatState.orderedList
                  ? "bg-[#00ff00] text-black border border-[#00ff00]"
                  : "bg-black border border-[#00ff00]/30 text-white hover:bg-[#00ff00]/10"
              }`}
              title="Numbered List"
            >
              <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                <path d="M2.5 3.5a.5.5 0 01.5.5v1h.5a.5.5 0 010 1H2a.5.5 0 010-1h.5V4.5H2a.5.5 0 010-1h.5zm4 .5a.5.5 0 01.5-.5h10a.5.5 0 010 1h-10a.5.5 0 01-.5-.5zm-4 5v-.5a.5.5 0 011 0v.5a.5.5 0 01-.5.5H2a.5.5 0 010-1h.5zm4 0a.5.5 0 01.5-.5h10a.5.5 0 010 1h-10a.5.5 0 01-.5-.5zm-4 5v-.5a.5.5 0 011 0v.5H4a.5.5 0 010 1H2a.5.5 0 010-1h.5zm4 0a.5.5 0 01.5-.5h10a.5.5 0 010 1h-10a.5.5 0 01-.5-.5z"/>
              </svg>
            </button>

            <div className="w-px h-6 bg-[#00ff00]/20 mx-1" />

            {/* Link */}
            <button
              onClick={handleInsertLink}
              className="h-8 px-2 rounded bg-black border border-[#00ff00]/30 text-[#00ff00] text-sm font-mono hover:bg-[#00ff00]/10 transition-colors flex items-center gap-1"
              title="Insert Link"
            >
              <LinkIcon size={16} />
            </button>
          </div>

          {/* Editor */}
          <div
            ref={editorRef}
            contentEditable
            onInput={handleInput}
            onPaste={handlePaste}
            onKeyUp={updateFormatState}
            onMouseUp={updateFormatState}
            className="min-h-[200px] max-h-[400px] overflow-y-auto p-4 bg-black border border-[#00ff00]/20 rounded-lg font-mono text-sm leading-relaxed focus:outline-none focus:border-[#00ff00]/50 transition-colors"
            style={{ whiteSpace: "pre-wrap", color: "#ffffff", caretColor: "#00ff00" }}
            data-placeholder="Start writing... Use the toolbar above to add formatting and links."
          />

          <style jsx>{`
            [contenteditable]:empty:before {
              content: attr(data-placeholder);
              color: #666;
              pointer-events: none;
            }
          `}</style>
        </CardContent>
      </Card>

      {/* Metadata */}
      <Card className="bg-[#0a0a0a] border border-[#00ff00]/20">
        <CardContent className="p-4 space-y-3">
          <H4 className="text-[#00ff00] font-mono text-sm">Details</H4>

          {/* Title */}
          <div>
            <Small className="text-gray-400 font-mono mb-1 block">Title *</Small>
            <input
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="Give your writing a title"
              className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00] transition-colors"
            />
          </div>

          {/* Author */}
          <div>
            <Small className="text-gray-400 font-mono mb-1 block">Author</Small>
            <input
              type="text"
              value={author}
              onChange={(e) => setAuthor(e.target.value)}
              placeholder="Your name (optional)"
              className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00] transition-colors"
            />
          </div>

          {/* Publication Year & Publisher */}
          <div className="grid grid-cols-2 gap-3">
            <div>
              <Small className="text-gray-400 font-mono mb-1 block">Year</Small>
              <input
                type="text"
                value={publicationYear}
                onChange={(e) => setPublicationYear(e.target.value)}
                placeholder="2024"
                className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00] transition-colors"
              />
            </div>
            <div>
              <Small className="text-gray-400 font-mono mb-1 block">Publisher</Small>
              <input
                type="text"
                value={publisher}
                onChange={(e) => setPublisher(e.target.value)}
                placeholder="Self-published"
                className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00] transition-colors"
              />
            </div>
          </div>

          {/* Cover Art URL */}
          <div>
            <Small className="text-gray-400 font-mono mb-1 block">Cover Art URL (optional)</Small>
            <div className="flex gap-3">
              <input
                type="url"
                value={coverArtUrl}
                onChange={(e) => setCoverArtUrl(e.target.value)}
                placeholder="https://... (image URL for thumbnail)"
                className="flex-1 px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00] transition-colors"
              />
              {coverArtUrl && (
                <div className="w-12 h-16 rounded border border-[#00ff00]/20 overflow-hidden shrink-0">
                  <img
                    src={coverArtUrl}
                    alt="Cover preview"
                    className="w-full h-full object-cover"
                    onError={(e) => {
                      (e.target as HTMLImageElement).style.display = "none";
                    }}
                  />
                </div>
              )}
            </div>
          </div>

          {/* Categories */}
          <div className="relative">
            <Small className="text-gray-400 font-mono mb-1 block">Categories (up to 3)</Small>
            <button
              onClick={() => setShowCategoryDropdown(!showCategoryDropdown)}
              className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-left font-mono text-sm flex items-center justify-between hover:border-[#00ff00]/50 transition-colors"
            >
              {selectedCategories.length === 0 ? (
                <span className="text-gray-500">Select categories...</span>
              ) : (
                <span className="text-white">
                  {selectedCategories.map(id => {
                    const cat = categories.find(c => c.id === id);
                    return cat ? `${cat.emoji} ${cat.label}` : id;
                  }).join(", ")}
                </span>
              )}
              <span className="text-[#00ff00]">▾</span>
            </button>

            {showCategoryDropdown && (
              <div className="absolute top-full left-0 right-0 mt-1 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg max-h-48 overflow-y-auto z-20">
                {categories.map(cat => (
                  <button
                    key={cat.id}
                    onClick={() => toggleCategory(cat.id)}
                    className={`w-full px-3 py-2 text-left font-mono text-sm flex items-center gap-2 transition-colors ${
                      selectedCategories.includes(cat.id)
                        ? "bg-[#00ff00]/10 text-[#00ff00]"
                        : "text-gray-300 hover:bg-[#1a1a1a]"
                    }`}
                  >
                    <span>{cat.emoji}</span>
                    <span>{cat.label}</span>
                    {selectedCategories.includes(cat.id) && <span className="ml-auto">✓</span>}
                  </button>
                ))}
              </div>
            )}
          </div>

          {/* Stacks */}
          <div className="relative">
            <Small className="text-gray-400 font-mono mb-1 block">Add to Stacks</Small>
            <button
              onClick={() => setShowStackDropdown(!showStackDropdown)}
              disabled={isLoadingStacks || stacks.length === 0}
              className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-left font-mono text-sm flex items-center justify-between hover:border-[#00ff00]/50 transition-colors disabled:opacity-50"
            >
              {isLoadingStacks ? (
                <span className="text-gray-500">Loading stacks...</span>
              ) : stacks.length === 0 ? (
                <span className="text-gray-500">No stacks yet</span>
              ) : selectedStackIds.length === 0 ? (
                <span className="text-gray-500">Select stacks (optional)...</span>
              ) : (
                <span className="text-white">
                  {selectedStackIds.length} stack{selectedStackIds.length !== 1 ? "s" : ""} selected
                </span>
              )}
              <span className="text-[#00ff00]">▾</span>
            </button>

            {showStackDropdown && stacks.length > 0 && (
              <>
                {/* Backdrop to close on click outside */}
                <div
                  className="fixed inset-0 z-10"
                  onClick={() => setShowStackDropdown(false)}
                />
                <div className="absolute top-full left-0 right-0 mt-1 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg overflow-hidden z-20">
                  <div className="max-h-40 overflow-y-auto">
                    {stacks.map(stack => (
                      <button
                        key={stack.id}
                        onClick={() => toggleStack(stack.id)}
                        className={`w-full px-3 py-2 text-left font-mono text-sm flex items-center gap-2 transition-colors ${
                          selectedStackIds.includes(stack.id)
                            ? "bg-purple-500/10 text-purple-400"
                            : "text-gray-300 hover:bg-[#1a1a1a]"
                        }`}
                      >
                        <LibraryIcon size={14} className="text-purple-400" />
                        <span className="truncate">{stack.name}</span>
                        {selectedStackIds.includes(stack.id) && <CheckIcon size={14} className="ml-auto text-[#00ff00]" />}
                        {stack.isPrivate && <LockIcon size={12} className="text-gray-500" />}
                      </button>
                    ))}
                  </div>
                  {/* Done button for mobile */}
                  <button
                    type="button"
                    onClick={() => setShowStackDropdown(false)}
                    className="w-full px-3 py-2 text-center font-mono text-sm text-[#00ff00] bg-[#00ff00]/10 border-t border-[#00ff00]/20 hover:bg-[#00ff00]/20 transition-colors"
                  >
                    Done
                  </button>
                </div>
              </>
            )}
          </div>
        </CardContent>
      </Card>

      {/* Error Message */}
      {uploadError && (
        <Card className="bg-red-500/10 border border-red-500/30">
          <CardContent className="p-3">
            <div className="flex items-start gap-2">
              <WarningIcon size={16} className="text-red-500 shrink-0 mt-0.5" />
              <Small className="text-red-400 font-mono">{uploadError}</Small>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Upload Button */}
      <Button
        onClick={handleUpload}
        disabled={!hasContent || isUploading}
        className="w-full bg-[#00ff00] text-black font-mono font-bold py-3 hover:bg-[#00ff00]/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all"
      >
        {isUploading ? "Uploading to Net Protocol..." : "Upload to Net Protocol"}
      </Button>

      {/* Link Modal */}
      {showLinkModal && (
        <div className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4" onClick={() => setShowLinkModal(false)}>
          <div className="bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl p-4 w-full max-w-sm" onClick={e => e.stopPropagation()}>
            <H4 className="text-[#00ff00] font-mono mb-4">Insert Link</H4>

            <div className="space-y-3">
              <div>
                <Small className="text-gray-400 font-mono mb-1 block">Link Text</Small>
                <input
                  type="text"
                  value={linkText}
                  onChange={(e) => setLinkText(e.target.value)}
                  placeholder="Display text"
                  className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00]"
                />
              </div>

              <div>
                <Small className="text-gray-400 font-mono mb-1 block">URL *</Small>
                <input
                  type="url"
                  value={linkUrl}
                  onChange={(e) => setLinkUrl(e.target.value)}
                  placeholder="https://example.com"
                  className="w-full px-3 py-2 bg-black border border-[#00ff00]/30 rounded-lg text-white font-mono text-sm focus:outline-none focus:border-[#00ff00]"
                  autoFocus
                />
              </div>
            </div>

            <div className="flex gap-2 mt-4">
              <button
                onClick={() => setShowLinkModal(false)}
                className="flex-1 py-2 rounded-lg border border-gray-700 text-gray-400 font-mono text-sm hover:bg-gray-800 transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={confirmInsertLink}
                disabled={!linkUrl}
                className="flex-1 py-2 rounded-lg bg-[#00ff00] text-black font-mono text-sm font-bold hover:bg-[#00ff00]/90 disabled:opacity-50 transition-colors"
              >
                Insert
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
src/features/app/components/trending-share.tsx
"use client";

import { useState } from "react";
import { Small } from "@neynar/ui";
import { safeComposeCast, safeOpenUrl, useAppMode } from "@/lib/app-mode";
import { useIsTrending } from "@/hooks/use-trending";
import { FlameIcon, ShareIcon } from "@/components/icons/net-library-icons";

// Time-based trending: 100+ upvotes in the last hour
// The actual check is done by the useTrending hook via the API

interface TrendingShareButtonProps {
  title: string;
  upvotes: number; // Total upvotes (for display)
  contentKey?: string; // Content key for time-based trending check
  showBadge?: boolean;
}

export function TrendingShareButton({ title, upvotes: _upvotes, contentKey, showBadge = true }: TrendingShareButtonProps) {
  const [showShareMenu, setShowShareMenu] = useState(false);
  const appMode = useAppMode();
  const isBaseApp = appMode === "base-app";

  // Use time-based trending check (100+ upvotes in last hour)
  const { isTrending, upvotesInLastHour } = useIsTrending(contentKey);

  if (!isTrending) return null;

  const baseUrl = typeof window !== "undefined" ? window.location.origin : "";
  // Include source so users land in the correct app version
  const source = isBaseApp ? "base" : "farcaster";
  // Deep link to the specific book if we have a contentKey
  const shareUrl = contentKey
    ? `${baseUrl}/?book=${encodeURIComponent(contentKey)}&source=${source}`
    : `${baseUrl}/?source=${source}`;
  // X share URL always uses source=web for browser experience
  const xShareUrl = contentKey
    ? `${baseUrl}/?book=${encodeURIComponent(contentKey)}&source=web`
    : `${baseUrl}/?source=web`;
  const castText = `📈 My upload "${title}" is trending on Net Library!\n\n🔥 ${upvotesInLastHour} upvotes in the last hour!\n\nDecentralized onchain media powered by @netprotocol`;
  const xText = castText.replace("@netprotocol", "@netprotocolapp");

  const handleShareToFeed = async () => {
    setShowShareMenu(false);
    try {
      await safeComposeCast({
        text: castText,
        embeds: [shareUrl],
      });
    } catch (err) {
      console.error("Failed to share:", err);
    }
  };

  const handleShareToX = async () => {
    setShowShareMenu(false);
    try {
      const xIntentParams = new URLSearchParams({
        text: xText,
        url: xShareUrl,
      });
      const xIntentUrl = `https://twitter.com/intent/tweet?${xIntentParams.toString()}`;
      // For Base App, open in system browser to avoid in-app interception
      if (isBaseApp) {
        window.open(xIntentUrl, "_blank", "noopener,noreferrer");
      } else {
        await safeOpenUrl(xIntentUrl);
      }
    } catch (err) {
      console.error("Failed to share to X:", err);
    }
  };

  return (
    <div className="mt-3 space-y-2">
      {showBadge && (
        <div className="flex items-center gap-2">
          <span className="inline-flex items-center gap-1 px-2 py-0.5 rounded bg-[#00ff00]/20 border border-[#00ff00]/40 animate-pulse">
            <FlameIcon size={12} className="text-orange-400" />
            <Small className="text-[10px] font-mono text-[#00ff00] font-bold">TRENDING</Small>
          </span>
          <Small className="text-gray-400 font-mono text-[10px] flex items-center gap-1"><FlameIcon size={10} className="text-orange-400" /> {upvotesInLastHour}/hr</Small>
        </div>
      )}
      <div className="relative">
        <button
          onClick={() => setShowShareMenu(!showShareMenu)}
          className="w-full py-2 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] text-xs font-mono uppercase tracking-wider hover:bg-[#00ff00]/20 hover:shadow-[0_0_15px_rgba(0,255,0,0.3)] transition-all flex items-center justify-center gap-1.5"
        >
          <ShareIcon size={12} /> Share Achievement ▾
        </button>

        {showShareMenu && (
          <>
            <div className="fixed inset-0 z-40" onClick={() => setShowShareMenu(false)} />
            <div className="absolute bottom-full left-0 right-0 mb-1 bg-black border border-[#00ff00]/30 rounded-lg overflow-hidden z-50 shadow-lg">
              <button
                onClick={handleShareToFeed}
                className={`w-full px-3 py-2.5 text-left text-xs font-mono flex items-center gap-2 transition-colors ${
                  isBaseApp
                    ? "hover:bg-[#0052FF]/20 text-[#0052FF]"
                    : "hover:bg-[#8A63D2]/20 text-[#8A63D2]"
                }`}
              >
                {isBaseApp ? (
                  <svg width="14" height="14" viewBox="0 0 111 111" fill="none">
                    <path d="M54.921 110.034C85.359 110.034 110.034 85.402 110.034 55.017C110.034 24.6319 85.359 0 54.921 0C26.0432 0 2.35281 22.1714 0 50.3923H72.8467V59.6416H0C2.35281 87.8625 26.0432 110.034 54.921 110.034Z" fill="#0052FF"/>
                  </svg>
                ) : (
                  <svg width="14" height="14" viewBox="0 0 1000 1000" fill="#8A63D2">
                    <path d="M257.778 155.556H742.222V844.445H671.111V528.889H670.414C662.554 441.677 589.258 373.333 500 373.333C410.742 373.333 337.446 441.677 329.586 528.889H328.889V844.445H257.778V155.556Z"/>
                    <path d="M128.889 253.333L157.778 351.111H182.222V746.667C169.949 746.667 160 756.616 160 768.889V795.556H155.556C143.283 795.556 133.333 805.505 133.333 817.778V844.445H382.222V817.778C382.222 805.505 372.273 795.556 360 795.556H355.556V768.889C355.556 756.616 345.606 746.667 333.333 746.667H306.667V253.333H128.889Z"/>
                    <path d="M675.556 746.667C663.283 746.667 653.333 756.616 653.333 768.889V795.556H648.889C636.616 795.556 626.667 805.505 626.667 817.778V844.445H875.556V817.778C875.556 805.505 865.606 795.556 853.333 795.556H848.889V768.889C848.889 756.616 838.94 746.667 826.667 746.667V351.111H851.111L880 253.333H702.222V746.667H675.556Z"/>
                  </svg>
                )}
                {isBaseApp ? "Share to Feed" : "Share to Farcaster"}
              </button>
              <button
                onClick={handleShareToX}
                className="w-full px-3 py-2.5 text-left text-xs font-mono flex items-center gap-2 hover:bg-white/10 text-white transition-colors border-t border-gray-800"
              >
                <svg width="12" height="12" viewBox="0 0 24 24" fill="white">
                  <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
                </svg>
                Share to X
              </button>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// Compact trending indicator (no share button)
// Now uses time-based trending: 100+ upvotes in last hour
export function TrendingBadge({ contentKey }: { contentKey?: string }) {
  const { isTrending } = useIsTrending(contentKey);

  if (!isTrending) return null;

  return (
    <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-[#00ff00]/20 border border-[#00ff00]/40 animate-pulse">
      <FlameIcon size={10} className="text-orange-400" />
      <Small className="text-[9px] font-mono text-[#00ff00] font-bold">TRENDING</Small>
    </span>
  );
}
src/features/app/components/unlimited-storage-pass-modal.tsx
"use client";

import {
  useState,
  useEffect,
  createContext,
  useContext,
  useCallback,
  type ReactNode,
} from "react";
import { createPortal } from "react-dom";
import {
  useAccount,
  useBalance,
  useWriteContract,
  useWaitForTransactionReceipt,
  usePublicClient,
  useCapabilities,
  useSendCalls,
  useCallsStatus,
} from "wagmi";
import { encodeFunctionData, type Address } from "viem";
import { base } from "viem/chains";
import { H4, P, Small } from "@neynar/ui";

// =============================================================================
// CONSTANTS
// =============================================================================

// eslint-disable-next-line @neynar/no-process-env
const PAYMASTER_URL = process.env.NEXT_PUBLIC_PAYMASTER_URL;

export const STORAGE_PASS_PRICE_USD = 10;
const PRICE_RAW = BigInt(10_000_000); // $10 USDC (6 decimals)

const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" as Address;
const PASS_CONTRACT = "0xCe559A2A6b64504bE00aa7aA85C5C31EA93a16BB" as Address;

// NFT art URLs — served via CF Worker image proxy which correctly handles binary PNGs.
// The raw storedon.net CDN URL is not used here because it can corrupt binary files.
const EARLY_ART_URL = "https://netlibrary.app/img/ulp-early";
const EARLY_ISH_ART_URL = "https://netlibrary.app/img/ulp-earlyish";

// Minted event topic (keccak256("Minted(address,uint256,string)"))
const MINTED_TOPIC =
  "0xe7cd4ce7f2a465edc730269a1305e8a48bad821e8fb7e152ec413829c01a53c4";

// =============================================================================
// ABIs
// =============================================================================

const USDC_ABI = [
  {
    name: "approve",
    type: "function",
    stateMutability: "nonpayable",
    inputs: [
      { name: "spender", type: "address" },
      { name: "amount", type: "uint256" },
    ],
    outputs: [{ type: "bool" }],
  },
] as const;

const PASS_ABI = [
  {
    name: "mint",
    type: "function",
    inputs: [],
    outputs: [],
    stateMutability: "nonpayable",
  },
  {
    name: "hasUnlimitedPass",
    type: "function",
    inputs: [{ name: "wallet", type: "address" }],
    outputs: [{ type: "bool" }],
    stateMutability: "view",
  },
  {
    name: "earlyRemaining",
    type: "function",
    inputs: [],
    outputs: [{ type: "uint256" }],
    stateMutability: "view",
  },
  {
    name: "totalSupply",
    type: "function",
    inputs: [],
    outputs: [{ type: "uint256" }],
    stateMutability: "view",
  },
  {
    name: "mintActive",
    type: "function",
    inputs: [],
    outputs: [{ type: "bool" }],
    stateMutability: "view",
  },
] as const;

// =============================================================================
// TYPES
// =============================================================================

interface UnlimitedPassModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

type MintStep =
  | "idle"           // pre-mint checks loading
  | "load-failed"    // contract read failed — show retry prompt
  | "ready"          // contract state loaded, ready to show UI
  | "approving"      // step 1: user approving USDC (EOA only)
  | "wallet-pending" // Smart Wallet: sendCalls dispatched, waiting for user to confirm in wallet
  | "minting"        // step 2: wallet confirmed — tx broadcast, waiting for on-chain confirmation
  | "confirming"     // tx confirmed, parsing receipt + notifying backend
  | "success"        // mint confirmed
  | "error";

interface ContractState {
  hasPass: boolean;
  mintActive: boolean;
  earlyRemaining: bigint;
  totalSupply: bigint;
}

interface MintResult {
  tokenId: number;
  tier: "we are so early" | "early-ish";
  txHash: string;
  membershipGranted?: boolean;
  memberId?: number;
  ensSubname?: string;
}

// =============================================================================
// MODAL COMPONENT
// =============================================================================

export function UnlimitedStoragePassModal({
  isOpen,
  onClose,
  onSuccess,
}: UnlimitedPassModalProps) {
  const { address, isConnected } = useAccount();
  const publicClient = usePublicClient();
  const [mounted, setMounted] = useState(false);

  // Contract state
  const [contractState, setContractState] = useState<ContractState | null>(null);
  const [contractLoading, setContractLoading] = useState(false);

  // Mint flow state
  const [step, setStep] = useState<MintStep>("idle");
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [mintResult, setMintResult] = useState<MintResult | null>(null);
  const [copiedLink, setCopiedLink] = useState(false);
  // Smart Wallet: true once the wallet has confirmed the batch (tx submitted to mempool)
  const [walletSubmitted, setWalletSubmitted] = useState(false);

  // USDC balance
  const { data: usdcBalance } = useBalance({
    address,
    token: USDC_ADDRESS,
    chainId: base.id,
  });

  // EIP-5792 capabilities — detect Smart Wallet / atomic batch support
  const { data: caps } = useCapabilities();
  const hasAtomicBatch = (() => {
    if (!caps) return false;
    const hexKey = `0x${base.id.toString(16)}` as unknown as number;
    const decKey = String(base.id) as unknown as number;
    const baseCaps =
      (caps[base.id] as Record<string, unknown> | undefined) ||
      (caps[hexKey] as Record<string, unknown> | undefined) ||
      (caps[decKey] as Record<string, unknown> | undefined);
    const atomic = baseCaps?.atomic as string | undefined;
    return atomic === "supported" || atomic === "ready";
  })();

  // --- Smart Wallet path: batched sendCalls ---
  const { sendCalls, data: callsId, error: sendCallsError } = useSendCalls();
  const callsIdStr = typeof callsId === "string" ? callsId : callsId?.id;
  const { data: callsStatus } = useCallsStatus({
    id: callsIdStr as string,
    query: {
      enabled: !!callsIdStr,
      refetchInterval: (data) =>
        data.state.data?.status === "success" ? false : 1000,
    },
  });

  // --- EOA path: sequential writeContract ---
  const {
    writeContract: writeApprove,
    data: approveTxHash,
    error: approveError,
    reset: resetApprove,
  } = useWriteContract();
  const {
    writeContract: writeMint,
    data: mintTxHash,
    error: mintError,
    reset: resetMint,
  } = useWriteContract();
  const { isSuccess: approveConfirmed } = useWaitForTransactionReceipt({
    hash: approveTxHash,
  });
  const { isSuccess: mintConfirmed } = useWaitForTransactionReceipt({
    hash: mintTxHash,
  });

  // ---------------------------------------------------------------------------
  // Mount guard (portal)
  // ---------------------------------------------------------------------------
  useEffect(() => {
    setMounted(true);
  }, []);

  // ---------------------------------------------------------------------------
  // Reset on open
  // ---------------------------------------------------------------------------
  useEffect(() => {
    if (isOpen) {
      setStep("idle");
      setErrorMessage(null);
      setMintResult(null);
      setCopiedLink(false);
      setWalletSubmitted(false);
    }
  }, [isOpen]);

  // ---------------------------------------------------------------------------
  // Load contract state when modal opens
  // ---------------------------------------------------------------------------
  const loadContractState = useCallback(async () => {
    if (!publicClient || !address) return;
    setContractLoading(true);
    try {
      const [hasPass, mintActive, earlyRemaining, totalSupply] =
        await Promise.all([
          publicClient.readContract({
            address: PASS_CONTRACT,
            abi: PASS_ABI,
            functionName: "hasUnlimitedPass",
            args: [address],
          }),
          publicClient.readContract({
            address: PASS_CONTRACT,
            abi: PASS_ABI,
            functionName: "mintActive",
          }),
          publicClient.readContract({
            address: PASS_CONTRACT,
            abi: PASS_ABI,
            functionName: "earlyRemaining",
          }),
          publicClient.readContract({
            address: PASS_CONTRACT,
            abi: PASS_ABI,
            functionName: "totalSupply",
          }),
        ]);
      setContractState({ hasPass, mintActive, earlyRemaining, totalSupply });
      setStep("ready");
    } catch (err) {
      console.error("[UnlimitedPassModal] Contract read failed:", err);
      // Do NOT fall back to fake defaults — user's pass ownership is unknown.
      // Show a retry prompt instead of the mint button.
      setContractState(null);
      setStep("load-failed");
    } finally {
      setContractLoading(false);
    }
  }, [publicClient, address]);

  useEffect(() => {
    if (isOpen && address && step === "idle") {
      loadContractState();
    }
  }, [isOpen, address, step, loadContractState]);

  // ---------------------------------------------------------------------------
  // Error handlers
  // ---------------------------------------------------------------------------
  useEffect(() => {
    const err = sendCallsError || approveError || mintError;
    if (!err) return;
    const msg = err.message?.toLowerCase() || "";
    if (
      msg.includes("user rejected") ||
      msg.includes("denied") ||
      msg.includes("cancelled")
    ) {
      // User cancelled — go back to ready
      resetApprove();
      resetMint();
      setStep("ready");
      return;
    }
    setErrorMessage(err.message?.slice(0, 120) || "Transaction failed");
    setStep("error");
  }, [sendCallsError, approveError, mintError, resetApprove, resetMint]);

  // ---------------------------------------------------------------------------
  // EOA flow: approve confirmed → send mint tx
  // ---------------------------------------------------------------------------
  useEffect(() => {
    if (approveConfirmed && approveTxHash && step === "approving") {
      setStep("minting");
      writeMint({
        address: PASS_CONTRACT,
        abi: PASS_ABI,
        functionName: "mint",
        args: [],
      });
    }
  }, [approveConfirmed, approveTxHash, step, writeMint]);

  // ---------------------------------------------------------------------------
  // EOA flow: mint confirmed → parse receipt
  // ---------------------------------------------------------------------------
  useEffect(() => {
    if (mintConfirmed && mintTxHash && step === "minting") {
      setStep("confirming");
      handleMintConfirmed(mintTxHash);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [mintConfirmed, mintTxHash]);

  // ---------------------------------------------------------------------------
  // Smart Wallet flow: walletSubmitted → transition to "minting"
  // isSendCallsPending is true as soon as sendCalls() is called, which is BEFORE
  // the user sees the wallet dialog. We only transition to "minting" after the
  // wallet has confirmed and the tx is in the mempool (walletSubmitted=true).
  // ---------------------------------------------------------------------------
  useEffect(() => {
    if (walletSubmitted && step === "wallet-pending") {
      setStep("minting");
    }
  }, [walletSubmitted, step]);

  // ---------------------------------------------------------------------------
  // Smart Wallet flow: callsStatus success → parse receipt
  // ---------------------------------------------------------------------------
  useEffect(() => {
    if (callsStatus?.status === "success" && callsStatus.receipts?.[0]) {
      const hash = callsStatus.receipts[callsStatus.receipts.length - 1]
        ?.transactionHash as string | undefined;
      if (hash && (step === "wallet-pending" || step === "minting" || step === "confirming")) {
        setWalletSubmitted(true);
        setStep("confirming");
        handleMintConfirmed(hash);
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [callsStatus]);

  // ---------------------------------------------------------------------------
  // Parse Minted event and notify backend
  // ---------------------------------------------------------------------------
  const handleMintConfirmed = useCallback(
    async (txHash: string) => {
      if (!address || !publicClient) return;
      setStep("confirming");

      try {
        const receipt = await publicClient.getTransactionReceipt({
          hash: txHash as `0x${string}`,
        });

        // Find the Minted(address indexed to, uint256 indexed tokenId, string tier) log
        // topic[1] is the recipient address left-padded to 32 bytes — use exact match
        const expectedTopic =
          "0x" + address.slice(2).toLowerCase().padStart(64, "0");
        const mintLog = receipt.logs.find(
          (log) =>
            log.address.toLowerCase() === PASS_CONTRACT.toLowerCase() &&
            log.topics[0] === MINTED_TOPIC &&
            log.topics[1]?.toLowerCase() === expectedTopic
        );

        const tokenId = mintLog?.topics[2]
          ? parseInt(mintLog.topics[2], 16)
          : null;
        const tier: "we are so early" | "early-ish" =
          tokenId && tokenId <= 1000 ? "we are so early" : "early-ish";

        // Notify backend — record the purchase and auto-grant membership if early tier
        const backendResp = await fetch("/api/membership/stack-pass", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            address,
            txHash,
            nftMint: true,
            tokenId,
            tier,
          }),
        });

        const backendData = await backendResp.json();

        const result: MintResult = {
          tokenId: tokenId ?? 0,
          tier,
          txHash,
          membershipGranted: backendData.membershipGranted ?? false,
          memberId: backendData.memberId,
          ensSubname: backendData.ensSubname,
        };

        setMintResult(result);
        setStep("success");
        onSuccess?.();
        // Refresh contract state so hasPass flips to true and stats update.
        // Fire-and-forget — success screen is already shown.
        loadContractState().catch(() => {/* non-fatal */});
      } catch (err) {
        console.error("[UnlimitedPassModal] Post-mint processing error:", err);
        // Still show success — the mint happened on-chain
        setMintResult({
          tokenId: 0,
          tier: "early-ish",
          txHash,
        });
        setStep("success");
        onSuccess?.();
        loadContractState().catch(() => {/* non-fatal */});
      }
    },
    [address, publicClient, onSuccess, loadContractState]
  );

  // ---------------------------------------------------------------------------
  // Mint handlers
  // ---------------------------------------------------------------------------
  const handleMintSmartWallet = async () => {
    if (!address) return;
    setErrorMessage(null);
    setWalletSubmitted(false);
    // Show "Waiting for wallet..." — not the full loading spinner yet
    setStep("wallet-pending");

    const approveFn = encodeFunctionData({
      abi: USDC_ABI,
      functionName: "approve",
      args: [PASS_CONTRACT, PRICE_RAW],
    });
    const mintFn = encodeFunctionData({
      abi: PASS_ABI,
      functionName: "mint",
      args: [],
    });

    try {
      sendCalls(
        {
          calls: [
            { to: USDC_ADDRESS, data: approveFn },
            { to: PASS_CONTRACT, data: mintFn },
          ],
          chainId: base.id,
          capabilities: PAYMASTER_URL
            ? { paymasterService: { url: PAYMASTER_URL } }
            : undefined,
        },
        {
          // Wallet has confirmed — tx is now in the mempool
          onSuccess: () => setWalletSubmitted(true),
        }
      );
    } catch (err) {
      console.error("[UnlimitedPassModal] sendCalls error:", err);
    }
  };

  const handleMintEOA = async () => {
    if (!address) return;
    setErrorMessage(null);
    setStep("approving");
    writeApprove({
      address: USDC_ADDRESS,
      abi: USDC_ABI,
      functionName: "approve",
      args: [PASS_CONTRACT, PRICE_RAW],
    });
  };

  const handleMint = () => {
    if (hasAtomicBatch) {
      handleMintSmartWallet();
    } else {
      handleMintEOA();
    }
  };

  // ---------------------------------------------------------------------------
  // Derived UI values
  // ---------------------------------------------------------------------------
  if (!isOpen || !mounted) return null;

  const isEarlyTier = contractState
    ? contractState.earlyRemaining > BigInt(0)
    : true;
  const artUrl = isEarlyTier ? EARLY_ART_URL : EARLY_ISH_ART_URL;
  const earlyRemainingNum = contractState
    ? Number(contractState.earlyRemaining)
    : null;
  const totalSupplyNum = contractState
    ? Number(contractState.totalSupply)
    : null;
  const usdcBal = usdcBalance ? parseFloat(usdcBalance.formatted) : 0;
  const hasEnoughUsdc = usdcBal >= STORAGE_PASS_PRICE_USD;

  const isBusy =
    step === "approving" ||
    step === "wallet-pending" ||
    step === "minting" ||
    step === "confirming";

  const busyLabel =
    step === "approving"
      ? "Step 1/2: Approve USDC..."
      : step === "wallet-pending"
      ? "Waiting for wallet..."
      : step === "minting"
      ? hasAtomicBatch
        ? "Confirming on Base..."
        : "Step 2/2: Minting..."
      : "Confirming on Base...";

  // Copy CDN link
  const copyLink = async (url: string) => {
    try {
      await navigator.clipboard.writeText(url);
    } catch {
      const ta = document.createElement("textarea");
      ta.value = url;
      document.body.appendChild(ta);
      ta.select();
      document.execCommand("copy");
      document.body.removeChild(ta);
    }
    setCopiedLink(true);
    setTimeout(() => setCopiedLink(false), 2000);
  };

  // ---------------------------------------------------------------------------
  // Render
  // ---------------------------------------------------------------------------
  const modalContent = (
    <div className="fixed inset-0 z-[9999] flex items-start justify-center pt-16 pb-20 px-4 overflow-y-auto">
      {/* Backdrop */}
      <div
        className="absolute inset-0 bg-black/85 backdrop-blur-sm"
        onClick={isBusy ? undefined : onClose}
      />

      {/* Modal */}
      <div className="relative w-full max-w-md bg-[#0a0a0a] border border-[#1a1a1a] rounded-2xl overflow-hidden shadow-2xl">
        {/* Header */}
        <div className="flex items-center justify-between p-4 border-b border-[#1a1a1a]">
          <div className="flex items-center gap-2">
            <span className="text-xl">♾️</span>
            <H4 className="text-[#00ff00] font-mono">Unlimited Pass</H4>
          </div>
          {!isBusy && (
            <button
              onClick={onClose}
              className="w-7 h-7 rounded-lg bg-[#1a1a1a] flex items-center justify-center text-gray-500 hover:text-white transition-colors text-sm"
            >
              ✕
            </button>
          )}
        </div>

        {/* Body */}
        <div className="p-4 space-y-4">
          {/* ── Loading contract state ── */}
          {(step === "idle" || contractLoading) && (
            <div className="py-10 text-center">
              <div className="w-8 h-8 mx-auto border-2 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
              <P className="text-gray-400 font-mono text-sm mt-3">
                Checking contract...
              </P>
            </div>
          )}

          {/* ── Contract load failed — show retry prompt ── */}
          {step === "load-failed" && (
            <div className="py-8 text-center space-y-4">
              <div className="w-16 h-16 mx-auto rounded-full bg-yellow-500/10 border border-yellow-500/30 flex items-center justify-center">
                <span className="text-3xl">⚠</span>
              </div>
              <H4 className="text-yellow-400 font-mono">Unable to load mint status</H4>
              <P className="text-gray-400 font-mono text-sm">
                Could not reach the contract. Your pass ownership status is unknown.
              </P>
              <Small className="text-gray-500 font-mono block">
                Please retry in a moment.
              </Small>
            </div>
          )}

          {/* ── Already owns the pass ── */}
          {step === "ready" && contractState?.hasPass && (
            <div className="py-6 text-center space-y-4">
              <div className="w-16 h-16 mx-auto rounded-full bg-[#00ff00]/10 border border-[#00ff00]/30 flex items-center justify-center">
                <span className="text-3xl">✓</span>
              </div>
              <H4 className="text-[#00ff00] font-mono">
                You already have an Unlimited Pass
              </H4>
              <P className="text-gray-400 font-mono text-sm">
                All unlimited features are active on your account.
              </P>
            </div>
          )}

          {/* ── Minting paused ── */}
          {step === "ready" && contractState && !contractState.mintActive && !contractState.hasPass && (
            <div className="py-6 text-center space-y-3">
              <span className="text-4xl block">⏸</span>
              <H4 className="text-yellow-400 font-mono">Minting is paused</H4>
              <P className="text-gray-400 font-mono text-sm">
                The contract owner has paused minting. Check back soon.
              </P>
            </div>
          )}

          {/* ── Ready to mint ── */}
          {step === "ready" && contractState?.mintActive && !contractState.hasPass && (
            <>
              {/* NFT Art */}
              <div className="rounded-xl overflow-hidden border border-[#2a2a2a] bg-[#111]">
                <img
                  src={artUrl}
                  alt={isEarlyTier ? "we are so early — Unlimited Pass NFT" : "early-ish — Unlimited Pass NFT"}
                  className="w-full object-cover"
                  style={{ maxHeight: 260 }}
                />
                <div className="px-3 py-2 flex items-center justify-between">
                  <Small className="text-white font-mono font-bold">
                    {isEarlyTier ? '"we are so early"' : '"early-ish"'}
                  </Small>
                  <Small className="text-[#00ff00] font-mono">
                    $10 USDC
                  </Small>
                </div>
              </div>

              {/* Live stats */}
              {earlyRemainingNum !== null && totalSupplyNum !== null && (
                <div className="flex gap-2">
                  <div className="flex-1 p-2 rounded-lg bg-[#1a1a1a] border border-[#2a2a2a] text-center">
                    <Small className="text-[#00ff00] font-mono font-bold block">
                      {earlyRemainingNum}/1000
                    </Small>
                    <Small className="text-gray-500 font-mono text-[9px]">
                      early slots left
                    </Small>
                  </div>
                  <div className="flex-1 p-2 rounded-lg bg-[#1a1a1a] border border-[#2a2a2a] text-center">
                    <Small className="text-[#00ff00] font-mono font-bold block">
                      {totalSupplyNum}
                    </Small>
                    <Small className="text-gray-500 font-mono text-[9px]">
                      total minted
                    </Small>
                  </div>
                </div>
              )}

              {/* Perks */}
              <div className="space-y-2">
                <Small className="text-gray-500 font-mono text-[9px] uppercase tracking-wider block">
                  What&apos;s included
                </Small>
                <div className="space-y-1.5">
                  <div className="flex items-start gap-2">
                    <span className="text-[#00ff00] text-xs mt-0.5 shrink-0">✓</span>
                    <Small className="text-gray-300 font-mono">
                      Upload unlimited items to stacks and grids
                    </Small>
                  </div>
                  <div className="flex items-start gap-2">
                    <span className="text-[#00ff00] text-xs mt-0.5 shrink-0">✓</span>
                    <Small className="text-gray-300 font-mono">
                      Bypass the 7-day warm-up period
                    </Small>
                  </div>
                  <div className="flex items-start gap-2">
                    <span className="text-[#00ff00] text-xs mt-0.5 shrink-0">✓</span>
                    <Small className="text-gray-300 font-mono">
                      1 free name registration on{" "}
                      <a
                        href="https://hazza.name"
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-[#00ff00] underline"
                      >
                        hazza.name
                      </a>
                    </Small>
                  </div>
                  <div className="flex items-start gap-2">
                    <span className="text-[#00ff00] text-xs mt-0.5 shrink-0">✓</span>
                    <Small className="text-gray-300 font-mono">
                      Unlimited items in any stack
                    </Small>
                  </div>
                  <div className="flex items-start gap-2">
                    <span className="text-[#00ff00] text-xs mt-0.5 shrink-0">✓</span>
                    <Small className="text-gray-300 font-mono">
                      Unlimited large grids (6×6 and larger)
                    </Small>
                  </div>
                  {isEarlyTier && (
                    <div className="flex items-start gap-2 p-2 rounded-lg bg-purple-500/10 border border-purple-500/20">
                      <span className="text-purple-400 text-xs mt-0.5 shrink-0">★</span>
                      <Small className="text-purple-300 font-mono font-semibold">
                        FREE Net Library membership (first 1000 minters only)
                      </Small>
                    </div>
                  )}
                </div>
              </div>

              {/* Balance */}
              <div className="p-2.5 rounded-lg bg-black border border-[#1a1a1a] flex items-center justify-between">
                <Small className="text-gray-400 font-mono">Your USDC</Small>
                <Small
                  className={`font-mono ${
                    hasEnoughUsdc ? "text-[#00ff00]" : "text-red-400"
                  }`}
                >
                  ${usdcBal.toFixed(2)}
                </Small>
              </div>
              {!hasEnoughUsdc && (
                <Small className="text-red-400 font-mono block text-center">
                  Need $10 USDC to mint
                </Small>
              )}

              {/* EOA two-step note */}
              {!hasAtomicBatch && (
                <div className="p-2 rounded-lg bg-yellow-500/5 border border-yellow-500/20">
                  <Small className="text-yellow-400/70 font-mono text-[10px]">
                    Two steps required: first approve USDC, then mint.
                  </Small>
                </div>
              )}

              {/* Contract link */}
              <div className="text-center">
                <a
                  href={`https://basescan.org/token/${PASS_CONTRACT}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-gray-600 hover:text-gray-400 font-mono text-[10px] underline"
                >
                  View contract on Basescan ↗
                </a>
              </div>
            </>
          )}

          {/* ── Transaction in progress ── */}
          {isBusy && (
            <div className="py-10 text-center space-y-3">
              <div className="w-12 h-12 mx-auto rounded-full border-4 border-[#1a1a1a] border-t-[#00ff00] animate-spin" />
              <P className="text-[#00ff00] font-mono">{busyLabel}</P>
              <Small className="text-gray-500 font-mono block">
                Don&apos;t close this window
              </Small>
            </div>
          )}

          {/* ── Success ── */}
          {step === "success" && mintResult && (
            <div className="space-y-4">
              {/* Art */}
              <div className="rounded-xl overflow-hidden border border-[#00ff00]/30 bg-[#111]">
                <img
                  src={
                    mintResult.tokenId <= 1000
                      ? EARLY_ART_URL
                      : EARLY_ISH_ART_URL
                  }
                  alt={`Unlimited Pass #${mintResult.tokenId}`}
                  className="w-full object-cover"
                  style={{ maxHeight: 240 }}
                  // allow long-press save on mobile
                  draggable
                />
                <div className="px-3 py-2 text-center">
                  <Small className="text-[#00ff00] font-mono font-bold block">
                    Unlimited Pass #{mintResult.tokenId}
                  </Small>
                  <Small className="text-gray-500 font-mono text-[10px]">
                    {mintResult.tier === "we are so early"
                      ? '"we are so early"'
                      : '"early-ish"'}
                  </Small>
                </div>
              </div>

              {/* Confirmed header */}
              <div className="text-center space-y-1">
                <H4 className="text-[#00ff00] font-mono">
                  Unlimited Pass Activated!
                </H4>
                <P className="text-gray-400 font-mono text-sm">
                  Your Unlimited Pass is now active.
                </P>
              </div>

              {/* Perks unlocked */}
              <div className="space-y-2 p-3 rounded-xl bg-[#00ff00]/5 border border-[#00ff00]/20">
                <div className="flex items-center gap-2">
                  <span className="text-[#00ff00] text-xs">✓</span>
                  <Small className="text-gray-300 font-mono">
                    Upload unlimited items to stacks and grids
                  </Small>
                </div>
                <div className="flex items-center gap-2">
                  <span className="text-[#00ff00] text-xs">✓</span>
                  <Small className="text-gray-300 font-mono">
                    1 free{" "}
                    <a
                      href="https://hazza.name"
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-[#00ff00] underline"
                    >
                      hazza.name
                    </a>{" "}
                    registration included
                  </Small>
                </div>
                {mintResult.membershipGranted && mintResult.ensSubname && (
                  <div className="flex items-center gap-2 p-2 rounded-lg bg-purple-500/10 border border-purple-500/20">
                    <span className="text-purple-400 text-xs">★</span>
                    <Small className="text-purple-300 font-mono">
                      Free membership granted:{" "}
                      <strong>{mintResult.ensSubname}</strong>
                    </Small>
                  </div>
                )}
              </div>

              {/* CDN link */}
              <div className="p-2.5 rounded-lg bg-[#111] border border-[#2a2a2a] space-y-1">
                <Small className="text-gray-500 font-mono text-[9px] uppercase block">
                  Art CDN
                </Small>
                <div className="flex gap-2 items-center">
                  <code className="flex-1 text-[9px] font-mono text-[#00ff00]/70 break-all leading-relaxed">
                    {mintResult.tokenId <= 1000 ? EARLY_ART_URL : EARLY_ISH_ART_URL}
                  </code>
                  <button
                    onClick={() =>
                      copyLink(
                        mintResult.tokenId <= 1000
                          ? EARLY_ART_URL
                          : EARLY_ISH_ART_URL
                      )
                    }
                    className="shrink-0 px-2 py-1 rounded bg-[#00ff00]/10 text-[#00ff00] text-[10px] font-mono hover:bg-[#00ff00]/20 transition-colors"
                  >
                    {copiedLink ? "✓" : "Copy"}
                  </button>
                </div>
              </div>

              {/* Links */}
              <div className="flex gap-3 justify-center text-[10px] font-mono">
                <a
                  href={`https://basescan.org/tx/${mintResult.txHash}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-gray-500 hover:text-gray-300 underline"
                >
                  View Tx ↗
                </a>
                <a
                  href={`https://basescan.org/token/${PASS_CONTRACT}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-gray-500 hover:text-gray-300 underline"
                >
                  Contract ↗
                </a>
                <a
                  href="https://hazza.name"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-[#00ff00] hover:text-[#00ff00]/70 underline"
                >
                  Claim hazza.name →
                </a>
              </div>
            </div>
          )}

          {/* ── Error ── */}
          {step === "error" && (
            <div className="py-6 text-center space-y-4">
              <div className="w-16 h-16 mx-auto rounded-full bg-red-500/10 border border-red-500/30 flex items-center justify-center">
                <span className="text-3xl">✕</span>
              </div>
              <H4 className="text-red-400 font-mono">Transaction Failed</H4>
              <P className="text-gray-400 font-mono text-sm">
                {errorMessage || "Something went wrong. Please try again."}
              </P>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-4 border-t border-[#1a1a1a]">
          {step === "load-failed" ? (
            <button
              onClick={() => {
                setStep("idle");
                loadContractState();
              }}
              className="w-full py-3 rounded-lg font-mono text-sm bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/20 transition-all"
            >
              Retry
            </button>
          ) : (step === "ready" && contractState?.mintActive && !contractState.hasPass) ? (
            <div className="flex gap-2">
              <button
                onClick={onClose}
                className="flex-1 py-3 rounded-lg font-mono text-sm bg-[#1a1a1a] text-gray-400 hover:text-white transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleMint}
                disabled={!isConnected || !hasEnoughUsdc}
                className="flex-1 py-3 rounded-lg font-mono text-sm bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/20 transition-all disabled:opacity-50 disabled:cursor-not-allowed"
              >
                Mint — $10 USDC
              </button>
            </div>
          ) : (step === "success" || (step === "ready" && contractState?.hasPass)) ? (
            <button
              onClick={onClose}
              className="w-full py-3 rounded-lg font-mono text-sm bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/20 transition-all"
            >
              Done
            </button>
          ) : step === "error" ? (
            <div className="flex gap-2">
              <button
                onClick={onClose}
                className="flex-1 py-3 rounded-lg font-mono text-sm bg-[#1a1a1a] text-gray-400 hover:text-white transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={() => {
                  resetApprove();
                  resetMint();
                  setErrorMessage(null);
                  setStep("ready");
                }}
                className="flex-1 py-3 rounded-lg font-mono text-sm bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/20 transition-all"
              >
                Try Again
              </button>
            </div>
          ) : null}
        </div>
      </div>
    </div>
  );

  return createPortal(modalContent, document.body);
}

// =============================================================================
// CONTEXT — global modal state so any component can open the modal
// =============================================================================

interface StoragePassContextType {
  isOpen: boolean;
  openStoragePassModal: () => void;
  closeStoragePassModal: () => void;
}

const StoragePassContext = createContext<StoragePassContextType>({
  isOpen: false,
  openStoragePassModal: () => {},
  closeStoragePassModal: () => {},
});

export function useStoragePassModal() {
  return useContext(StoragePassContext);
}

export function StoragePassProvider({ children }: { children: ReactNode }) {
  const [isOpen, setIsOpen] = useState(false);

  const openStoragePassModal = () => setIsOpen(true);
  const closeStoragePassModal = () => setIsOpen(false);

  return (
    <StoragePassContext.Provider
      value={{ isOpen, openStoragePassModal, closeStoragePassModal }}
    >
      {children}
      <UnlimitedStoragePassModal
        isOpen={isOpen}
        onClose={closeStoragePassModal}
      />
    </StoragePassContext.Provider>
  );
}
src/features/app/components/upload-tab.tsx
"use client";

import { useState, useRef, useEffect, useCallback } from "react";
import { encryptContent } from "@/lib/crypto";
import { Card, CardContent, Button, P, Small, H4 } from "@neynar/ui";
import type { Book, UploadState, Category, Stack } from "@/features/app/types";
import { useRelayUploadV2 as useRelayUpload } from "@/hooks/use-relay-upload-v2";
import { getRecoveryInfo } from "@/lib/upload-recovery";
import type { UploadRecoveryState } from "@/lib/upload-recovery";
import { AddFundsModal } from "./add-funds-modal";
import { MultiFileUpload } from "./multi-file-upload";
import { TextEditorUpload } from "./text-editor-upload";
import { CreateImageUpload } from "./create-image-upload";
import { CdnLinkUpload, type ContentType } from "./cdn-link-upload";
import { BatchCdnImport } from "./batch-cdn-import";
import { SocialReceiptUpload, type SocialPlatform, type SocialContent } from "./social-receipt-upload";
import { SocialReceiptShareModal } from "./social-receipt-share-modal";
import { UploadWalletBalance } from "./upload-wallet-balance";
import { usePdfCover } from "@/hooks/use-pdf-cover";
import { useCoverUpload } from "@/hooks/use-cover-upload";
import { saveFailedDrafts, clearDraftForFile, type QueuedUpload } from "@/lib/upload-queue";
import { usePostToNetLibraryFeed } from "@/hooks/use-netlibrary-feed";
import { useUserProfile } from "@/hooks/use-user-profile";
import {
  MAX_FILE_SIZE,
  requiresPremiumUpload,
  requiresMembership,
  calculatePremiumFee,
  WARMUP_DAILY_LIMIT,
  REGULAR_DAILY_LIMIT,
  type DuplicateCheckResult,
} from "@/lib/net-protocol";
import { PremiumUploadModal } from "./premium-upload-modal";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { useUploadReputation } from "@/hooks/use-upload-reputation";
import { useAppMode, safeOpenUrl, triggerHaptic } from "@/lib/app-mode";
import { createAppError } from "@/lib/error-codes";
import { useUserStacks } from "@/hooks/use-stacks";
import { FilePreviewModal } from "./file-preview-modal";
import { MultimediaViewer } from "./multimedia-viewer";
import { LibraryIcon, DocumentIcon, LinkIcon, SettingsIcon, LockIcon, UploadIcon, PencilIcon, PaletteIcon, ImageIcon, WarningIcon, PartyIcon, LoadingIcon, FolderIcon, CheckIcon, CheckCircleIcon, CloseIcon, XCircleIcon, BanIcon, SeedlingIcon, ClipboardIcon, RefreshIcon, ClockIcon, DollarBillIcon, PackageIcon, SignalIcon, PhoneIcon, TrafficLightIcon, LightbulbIcon, ReceiptIcon, TagIcon, StarIcon, MoneyIcon, ShareIcon } from "@/components/icons/net-library-icons";
// Lazy load EPUB converter to avoid build-time bundling issues with jspdf/jszip
import type { EpubConversionProgress } from "@/lib/epub-to-pdf";

const loadEpubConverter = () => import("@/lib/epub-to-pdf");

// Helper to detect ContentType from file MIME type
function detectContentTypeFromMime(mimeType: string): ContentType {
  if (mimeType === "application/pdf") return "pdf";
  if (mimeType.startsWith("image/")) return "image";
  if (mimeType.startsWith("audio/")) return "audio";
  if (mimeType.startsWith("video/")) return "video";
  if (mimeType.startsWith("text/") || mimeType === "application/json") return "text";
  return "unknown";
}

// Stack selection dropdown component for upload
function StackSelectionDropdown({
  stacks,
  selectedStackIds,
  onToggle,
  isLoading,
}: {
  stacks: Stack[];
  selectedStackIds: string[];
  onToggle: (stackId: string) => void;
  isLoading: boolean;
}) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      return () => document.removeEventListener("mousedown", handleClickOutside);
    }
  }, [isOpen]);

  const selectedStacks = stacks.filter(s => selectedStackIds.includes(s.id));

  if (isLoading) {
    return (
      <div className="w-full px-3 py-2.5 rounded-lg bg-black border border-[#00ff00]/30 text-gray-500 font-mono text-sm">
        Loading your stacks...
      </div>
    );
  }

  if (stacks.length === 0) {
    return (
      <div className="w-full px-3 py-2.5 rounded-lg bg-black border border-[#00ff00]/20 text-gray-500 font-mono text-sm">
        No stacks yet - create one in the Stacks tab!
      </div>
    );
  }

  return (
    <div className="relative" ref={dropdownRef}>
      {/* Dropdown trigger */}
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="w-full px-3 py-2.5 rounded-lg bg-black border border-[#00ff00]/30 text-left font-mono focus:outline-none focus:border-[#00ff00] transition-colors flex items-center justify-between"
      >
        <div className="flex-1 min-w-0">
          {selectedStacks.length === 0 ? (
            <span className="text-gray-500 text-sm">Select stacks (optional)...</span>
          ) : (
            <div className="flex flex-wrap gap-1">
              {selectedStacks.map(stack => (
                <span
                  key={stack.id}
                  className="inline-flex items-center gap-1 px-2 py-0.5 bg-purple-500/20 text-purple-400 rounded text-xs"
                >
                  <LibraryIcon size={12} /> {stack.name}
                </span>
              ))}
            </div>
          )}
        </div>
        <svg
          className={`w-5 h-5 text-[#00ff00] transition-transform shrink-0 ml-2 ${isOpen ? "rotate-180" : ""}`}
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {/* Dropdown menu */}
      {isOpen && (
        <div className="absolute top-full left-0 right-0 mt-1 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg overflow-hidden z-20">
          <div className="max-h-40 overflow-y-auto">
            {stacks.map((stack) => {
              const isSelected = selectedStackIds.includes(stack.id);
              const isFull = !stack.unlocked && (stack.itemCount || 0) >= 20;
              return (
                <button
                  key={stack.id}
                  type="button"
                  onClick={() => !isFull && onToggle(stack.id)}
                  disabled={isFull}
                  className={`w-full px-3 py-2.5 text-left font-mono text-sm flex items-center gap-2 transition-colors ${
                    isFull
                      ? "opacity-50 cursor-not-allowed text-gray-500"
                      : isSelected
                      ? "bg-purple-500/20 text-purple-400"
                      : "text-gray-300 hover:bg-[#1a1a1a] hover:text-white"
                  }`}
                >
                  <span className={`w-5 h-5 rounded border-2 flex items-center justify-center shrink-0 ${
                    isFull ? 'border-gray-600 bg-gray-800' : isSelected ? 'border-purple-500 bg-purple-500' : 'border-gray-600'
                  }`}>
                    {isSelected && !isFull && <span className="text-white text-xs font-bold">✓</span>}
                    {isFull && <span className="text-gray-500 text-[8px]">✕</span>}
                  </span>
                  <LibraryIcon size={14} />
                  <span className="truncate">{stack.name}</span>
                  {stack.isPrivate && <span className="text-gray-500 text-xs"><LockIcon size={12} /></span>}
                  <span className={`text-[10px] ml-auto shrink-0 ${
                    isFull
                      ? "text-red-400 font-bold"
                      : !stack.unlocked && (stack.itemCount || 0) >= 15
                      ? "text-yellow-400"
                      : "text-gray-500"
                  }`}>
                    {isFull ? "FULL" : `${stack.itemCount || 0}/${stack.unlocked ? "∞" : "20"}`}
                  </span>
                </button>
              );
            })}
          </div>
          {/* Done button for mobile */}
          <button
            type="button"
            onClick={() => setIsOpen(false)}
            className="w-full px-3 py-2 text-center font-mono text-sm text-[#00ff00] bg-[#00ff00]/10 border-t border-[#00ff00]/20 hover:bg-[#00ff00]/20 transition-colors"
          >
            Done
          </button>
        </div>
      )}
    </div>
  );
}

// Upload log entry type
interface UploadLogEntry {
  id: string;
  timestamp: number;
  fileName: string;
  fileSize: number;
  status: "success" | "failed" | "cancelled";
  error?: string;
  contentKey?: string;
  countedAgainstLimit: boolean;
  totalChunks?: number; // Number of chunks used for storage
  // Debug info for failed uploads (Base App debugging)
  debugInfo?: {
    connectorId: string;
    connectorName: string;
    isBaseAppMode: boolean;
    walletDeployed: boolean | null;
    balance: string;
    lastErrorRaw: string | null;
    txAttempts: string[];
  };
}

// Debug Details Panel - expandable debug info with copy button
function DebugDetailsPanel({ entry }: { entry: UploadLogEntry }) {
  const [copied, setCopied] = useState(false);
  const debug = entry.debugInfo;
  if (!debug) return null;

  const formatDebugText = () => {
    const lines = [
      `=== Upload Debug Info ===`,
      `File: ${entry.fileName}`,
      `Time: ${new Date(entry.timestamp).toISOString()}`,
      `Error: ${entry.error || "Unknown"}`,
      ``,
      `--- Wallet Info ---`,
      `Connector: ${debug.connectorId} (${debug.connectorName})`,
      `Base App Mode: ${debug.isBaseAppMode}`,
      `Wallet Deployed: ${debug.walletDeployed === null ? "not checked" : debug.walletDeployed}`,
      `Balance: ${debug.balance} ETH`,
    ];

    if (debug.txAttempts.length > 0) {
      lines.push(``, `--- TX Attempts (${debug.txAttempts.length}) ---`);
      debug.txAttempts.forEach((attempt, idx) => {
        lines.push(`${idx + 1}. ${attempt}`);
      });
    }

    if (debug.lastErrorRaw) {
      lines.push(``, `--- Raw Error ---`, debug.lastErrorRaw);
    }

    return lines.join("\n");
  };

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(formatDebugText());
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      // Fallback for older browsers
      const textarea = document.createElement("textarea");
      textarea.value = formatDebugText();
      document.body.appendChild(textarea);
      textarea.select();
      document.execCommand("copy");
      document.body.removeChild(textarea);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    }
  };

  return (
    <details className="mt-2 group">
      <summary className="text-[9px] text-red-400/70 cursor-pointer hover:text-red-400 list-none flex items-center gap-1">
        <span className="transition-transform group-open:rotate-90">▶</span>
        🐛 Debug Details
      </summary>
      <div className="mt-1 p-2 bg-black/50 border border-red-500/20 rounded text-[9px] space-y-1">
        {/* Copy button */}
        <div className="flex justify-end mb-1">
          <button
            onClick={handleCopy}
            className={`flex items-center gap-1 px-1.5 py-0.5 rounded text-[8px] transition-colors ${
              copied
                ? "bg-green-500/20 text-green-400"
                : "bg-gray-800 text-gray-400 hover:text-white hover:bg-gray-700"
            }`}
            title="Copy debug info"
          >
            {copied ? (
              <>✓ Copied</>
            ) : (
              <>
                {/* Double square copy icon */}
                <svg width="10" height="10" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5">
                  <rect x="5" y="5" width="9" height="9" rx="1" />
                  <path d="M3 11V3a1 1 0 0 1 1-1h8" />
                </svg>
                Copy
              </>
            )}
          </button>
        </div>

        <div className="flex justify-between">
          <span className="text-gray-500">Connector:</span>
          <span className="text-white">{debug.connectorId} ({debug.connectorName})</span>
        </div>
        <div className="flex justify-between">
          <span className="text-gray-500">Base App Mode:</span>
          <span className={debug.isBaseAppMode ? "text-green-400" : "text-gray-400"}>
            {String(debug.isBaseAppMode)}
          </span>
        </div>
        <div className="flex justify-between">
          <span className="text-gray-500">Wallet Deployed:</span>
          <span className={
            debug.walletDeployed === true ? "text-green-400" :
            debug.walletDeployed === false ? "text-red-400" : "text-yellow-400"
          }>
            {debug.walletDeployed === null ? "not checked" : String(debug.walletDeployed)}
          </span>
        </div>
        <div className="flex justify-between">
          <span className="text-gray-500">Balance:</span>
          <span className="text-white">{debug.balance} ETH</span>
        </div>
        {debug.txAttempts.length > 0 && (
          <div className="mt-1 pt-1 border-t border-red-500/10">
            <div className="text-gray-500 mb-1">TX Attempts ({debug.txAttempts.length}):</div>
            <div className="max-h-20 overflow-auto space-y-0.5">
              {debug.txAttempts.map((attempt, idx) => (
                <div
                  key={idx}
                  className={`text-[8px] ${
                    attempt.includes("SUCCESS") ? "text-green-400" :
                    attempt.includes("FAILED") ? "text-red-400" :
                    "text-gray-300"
                  }`}
                >
                  {attempt}
                </div>
              ))}
            </div>
          </div>
        )}
        {debug.lastErrorRaw && (
          <div className="mt-1 pt-1 border-t border-red-500/10">
            <div className="text-gray-500 mb-1">Raw Error:</div>
            <div className="text-red-300 text-[8px] break-words whitespace-pre-wrap max-h-16 overflow-auto">
              {debug.lastErrorRaw}
            </div>
          </div>
        )}
      </div>
    </details>
  );
}

// Upload Log Component - scrollable window showing upload history
function UploadLog({ entries, onClear }: { entries: UploadLogEntry[]; onClear: () => void }) {
  const logRef = useRef<HTMLDivElement>(null);

  // Auto-scroll to bottom when new entries are added
  useEffect(() => {
    if (logRef.current) {
      logRef.current.scrollTop = logRef.current.scrollHeight;
    }
  }, [entries.length]);

  if (entries.length === 0) {
    return null;
  }

  const formatTime = (timestamp: number) => {
    return new Date(timestamp).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" });
  };

  const formatSize = (bytes: number) => {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
  };

  return (
    <Card className="bg-[#0a0a0a] border border-[#00ff00]/20 mt-4">
      <CardContent className="p-3">
        <div className="flex items-center justify-between mb-2">
          <Small className="text-[#00ff00] font-mono uppercase tracking-wider text-[10px] flex items-center gap-1">
            <ClipboardIcon size={12} /> Upload Log
          </Small>
          <button
            onClick={onClear}
            className="text-[10px] text-gray-500 hover:text-gray-300 font-mono transition-colors"
          >
            Clear
          </button>
        </div>

        {/* Scrollable log window - increased height for debug details */}
        <div
          ref={logRef}
          className="max-h-64 overflow-y-auto border border-gray-800 rounded bg-black/50 font-mono text-[11px]"
        >
          {entries.map((entry) => (
            <div
              key={entry.id}
              className={`px-2 py-1.5 border-b border-gray-800/50 last:border-b-0 ${
                entry.status === "success"
                  ? "bg-green-500/5"
                  : entry.status === "cancelled"
                  ? "bg-yellow-500/5"
                  : "bg-red-500/5"
              }`}
            >
              <div className="flex items-start gap-2">
                {/* Status icon */}
                <span className="shrink-0 mt-0.5">
                  {entry.status === "success" ? <CheckCircleIcon size={14} className="text-green-400" /> : entry.status === "cancelled" ? <CloseIcon size={14} className="text-yellow-400" /> : <XCircleIcon size={14} className="text-red-400" />}
                </span>

                {/* Details */}
                <div className="flex-1 min-w-0">
                  <div className="flex items-center justify-between gap-2">
                    <span className="text-white truncate">{entry.fileName}</span>
                    <span className="text-gray-500 shrink-0">{formatTime(entry.timestamp)}</span>
                  </div>

                  <div className="text-gray-400 text-[10px] mt-0.5">
                    {formatSize(entry.fileSize)}
                    {entry.totalChunks ? (
                      <span className="text-[#00ff00]/70 ml-2">• {entry.totalChunks} chunks</span>
                    ) : null}
                    {entry.status === "success" ? (
                      <span className="text-green-400 ml-2">• Uploaded successfully</span>
                    ) : entry.status === "cancelled" ? (
                      <span className="text-yellow-400 ml-2">• Cancelled by user</span>
                    ) : (
                      <span className="text-red-400 ml-2">• {entry.error || "Upload failed"}</span>
                    )}
                  </div>

                  {/* Count feedback */}
                  <div className={`text-[10px] mt-1 ${entry.countedAgainstLimit ? "text-orange-400" : "text-blue-400"}`}>
                    {entry.countedAgainstLimit
                      ? "⚠️ Counted against daily limit"
                      : "ℹ️ Did NOT count against daily limit"}
                  </div>

                  {/* Debug info for failed/cancelled uploads - expandable */}
                  {(entry.status === "failed" || entry.status === "cancelled") && entry.debugInfo && (
                    <DebugDetailsPanel entry={entry} />
                  )}
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Summary */}
        <div className="mt-2 pt-2 border-t border-gray-800 flex items-center justify-between">
          <Small className="text-gray-500 font-mono text-[10px]">
            {entries.filter(e => e.status === "success").length} successful, {" "}
            {entries.filter(e => e.status !== "success").length} failed/cancelled
          </Small>
          <Small className="text-blue-400 font-mono text-[10px]">
            {entries.filter(e => e.countedAgainstLimit).length} counted toward limit
          </Small>
        </div>
      </CardContent>
    </Card>
  );
}

// Category dropdown component
function CategoryDropdown({
  categories,
  selectedCategories,
  onToggle,
  maxSelections = 3,
}: {
  categories: Category[];
  selectedCategories: string[];
  onToggle: (categoryId: string) => void;
  maxSelections?: number;
}) {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Close dropdown when clicking outside
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener("mousedown", handleClickOutside);
      return () => document.removeEventListener("mousedown", handleClickOutside);
    }
  }, [isOpen]);

  const filteredCategories = categories.filter(c => c.id !== "all");
  const selectedCats = filteredCategories.filter(c => selectedCategories.includes(c.id));

  return (
    <div className="relative" ref={dropdownRef}>
      {/* Dropdown trigger */}
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="w-full px-3 py-2.5 rounded-lg bg-black border border-[#00ff00]/30 text-left font-mono focus:outline-none focus:border-[#00ff00] transition-colors flex items-center justify-between"
      >
        <div className="flex-1 min-w-0">
          {selectedCats.length === 0 ? (
            <span className="text-gray-500 text-sm">Select categories...</span>
          ) : (
            <div className="flex flex-wrap gap-1">
              {selectedCats.map(cat => (
                <span
                  key={cat.id}
                  className="inline-flex items-center gap-1 px-2 py-0.5 bg-[#00ff00]/20 text-[#00ff00] rounded text-xs"
                >
                  {cat.emoji} {cat.label}
                </span>
              ))}
            </div>
          )}
        </div>
        <svg
          className={`w-5 h-5 text-[#00ff00] transition-transform shrink-0 ml-2 ${isOpen ? "rotate-180" : ""}`}
          fill="none"
          viewBox="0 0 24 24"
          stroke="currentColor"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {/* Dropdown menu */}
      {isOpen && (
        <div className="absolute top-full left-0 right-0 mt-1 bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg overflow-hidden z-20 max-h-64 overflow-y-auto">
          {filteredCategories.map((cat) => {
            const isSelected = selectedCategories.includes(cat.id);
            const isDisabled = !isSelected && selectedCategories.length >= maxSelections;
            return (
              <button
                key={cat.id}
                type="button"
                onClick={() => {
                  if (!isDisabled) {
                    onToggle(cat.id);
                  }
                }}
                disabled={isDisabled}
                className={`w-full px-3 py-2.5 text-left font-mono text-sm flex items-center gap-2 transition-colors ${
                  isSelected
                    ? "bg-[#00ff00]/20 text-[#00ff00]"
                    : isDisabled
                    ? "text-gray-600 cursor-not-allowed"
                    : "text-gray-300 hover:bg-[#1a1a1a] hover:text-white"
                }`}
              >
                <span className={`w-5 h-5 rounded border-2 flex items-center justify-center shrink-0 ${
                  isSelected ? 'border-[#00ff00] bg-[#00ff00]' : 'border-gray-600'
                }`}>
                  {isSelected && <span className="text-black text-xs font-bold">✓</span>}
                </span>
                <span>{cat.emoji}</span>
                <span>{cat.label}</span>
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

interface UploadTabProps {
  categories: Category[];
  books: Book[];
  onUploadComplete?: () => void;
  onNavigateToProfile?: () => void;
  /** Whether this tab is currently active - triggers balance refresh */
  isActive?: boolean;
}

// Helper to check for duplicate/similar titles
function checkForDuplicates(title: string, existingBooks: Book[]) {
  const normalizedTitle = title.toLowerCase().trim().replace(/\.pdf$/i, "");

  const exactMatches = existingBooks.filter(
    (book) => (book.title || '').toLowerCase() === normalizedTitle
  );

  if (exactMatches.length > 0) {
    return { type: "exact" as const, matchedBooks: exactMatches };
  }

  const similarMatches = existingBooks.filter((book) => {
    const bookTitle = (book.title || '').toLowerCase();
    if (
      bookTitle.includes(normalizedTitle) ||
      normalizedTitle.includes(bookTitle)
    ) {
      return true;
    }
    const titleWords = normalizedTitle.split(/\s+/).filter((w) => w.length > 2);
    const bookWords = bookTitle.split(/\s+/).filter((w) => w.length > 2);
    const matchingWords = titleWords.filter((w) =>
      bookWords.some((bw) => bw.includes(w) || w.includes(bw))
    );
    return matchingWords.length >= Math.min(2, titleWords.length);
  });

  if (similarMatches.length > 0) {
    return { type: "similar" as const, matchedBooks: similarMatches };
  }

  return null;
}

export function UploadTab({ categories, books, onUploadComplete, onNavigateToProfile, isActive }: UploadTabProps) {
  // Upload mode: "file" (default), "create" (write/draw), "link" (CDN import), or "receipt" (social posts)
  const [uploadMode, setUploadMode] = useState<"file" | "create" | "link" | "receipt">("file");
  const [isUploadingText, setIsUploadingText] = useState(false);
  const [isUploadingImage, setIsUploadingImage] = useState(false);
  // Which create section is expanded: "write" or "draw" or null
  const [createSection, setCreateSection] = useState<"write" | "draw" | null>(null);
  const [isUploadingLink, setIsUploadingLink] = useState(false);
  const [isUploadingReceipt, setIsUploadingReceipt] = useState(false);

  const [bookTitle, setBookTitle] = useState("");
  const [authorName, setAuthorName] = useState("");
  const [publicationYear, setPublicationYear] = useState("");
  const [publisher, setPublisher] = useState("");
  const [isbn, setIsbn] = useState("");
  const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
  const [coverArtUrl, setCoverArtUrl] = useState<string | null>(null);
  const [isUserSelectedCover, setIsUserSelectedCover] = useState(false); // Track if user manually picked cover
  const isUserSelectedCoverRef = useRef(false); // Ref for async race condition handling
  const [showCoverUpload, setShowCoverUpload] = useState(false);
  const [showConfirmUpload, setShowConfirmUpload] = useState(false);
  const [isPreparingUpload, setIsPreparingUpload] = useState(false); // Loading state for "Yes, Upload" button
  const [isDragging, setIsDragging] = useState(false);
  const [selectedFile, setSelectedFile] = useState<File | null>(null);
  const [previewFile, setPreviewFile] = useState<File | null>(null); // File to preview before metadata form
  const [showPreviewModal, setShowPreviewModal] = useState(false);
  const [uploadState, setUploadState] = useState<UploadState>({
    status: "idle",
    fileName: "",
    fileSize: 0,
    totalChunks: 0,
    completedChunks: 0,
    currentChunkStatus: "pending",
    isFunding: false,
  });

  // Funding success state - shows brief success message before closing
  const [fundingSuccess, setFundingSuccess] = useState<{ show: boolean; amount?: string }>({ show: false });

  // EPUB to PDF conversion state
  const [epubConversion, setEpubConversion] = useState<EpubConversionProgress | null>(null);
  const [originalEpubName, setOriginalEpubName] = useState<string | null>(null);

  // Activity feed posting
  const { postUpload } = usePostToNetLibraryFeed();
  const { profile: userProfile } = useUserProfile();
  const [showShareToFeed, setShowShareToFeed] = useState(false);
  const [isPostingToFeed, setIsPostingToFeed] = useState(false);
  const [feedPostResult, setFeedPostResult] = useState<"success" | "error" | null>(null);
  const [lastUploadedContentKey, setLastUploadedContentKey] = useState<string | null>(null);

  // Track last uploaded content type for "View Content" button on completion
  const [lastUploadedContentType, setLastUploadedContentType] = useState<ContentType | null>(null);
  const [showMultimediaViewer, setShowMultimediaViewer] = useState(false);

  // Track social receipt upload metadata for sharing
  const [lastSocialReceiptData, setLastSocialReceiptData] = useState<{
    platform: SocialPlatform;
    author: string;
    contentKey: string;
  } | null>(null);
  const [showSocialShareModal, setShowSocialShareModal] = useState(false);

  // Upload log - tracks all upload attempts with their status
  const [uploadLog, setUploadLog] = useState<UploadLogEntry[]>([]);

  // Add entry to upload log
  const addLogEntry = (entry: Omit<UploadLogEntry, "id" | "timestamp">) => {
    setUploadLog(prev => [...prev, {
      ...entry,
      id: `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      timestamp: Date.now(),
    }]);
  };

  // Clear upload log
  const clearUploadLog = () => setUploadLog([]);

  // Premium upload state
  const [showPremiumModal, setShowPremiumModal] = useState(false);
  const [premiumPaid, setPremiumPaid] = useState(false);

  // Stack selection for upload
  const { stacks: userStacks, isLoading: isLoadingStacks } = useUserStacks();
  const [selectedStackIds, setSelectedStackIds] = useState<string[]>([]);

  const toggleStackSelection = (stackId: string) => {
    setSelectedStackIds(prev =>
      prev.includes(stackId)
        ? prev.filter(id => id !== stackId)
        : [...prev, stackId]
    );
  };

  // Encryption state (member-only feature)
  const [encryptEnabled, setEncryptEnabled] = useState(false);
  const [encryptPassword, setEncryptPassword] = useState("");
  const [encryptSavePassword, setEncryptSavePassword] = useState(true);
  const [encryptPasswordLabel, setEncryptPasswordLabel] = useState("");
  // Saved passwords loaded from /api/passwords (populated on first toggle-on)
  const [savedPasswords, setSavedPasswords] = useState<{ id: string; label: string }[]>([]);
  const [isFetchingPasswords, setIsFetchingPasswords] = useState(false);
  const [selectedSavedPasswordId, setSelectedSavedPasswordId] = useState<string | null>(null);
  // 'new'   → user will type a password into encryptPassword
  // 'saved' → user selected an entry from savedPasswords (selectedSavedPasswordId is set)
  const [passwordSource, setPasswordSource] = useState<"new" | "saved">("new");
  // Tracks whether we are mid-encryption (before the relay upload starts)
  const [isEncryptingFile, setIsEncryptingFile] = useState(false);

  // App mode (farcaster or base-app)
  const appMode = useAppMode();

  // Membership status for tiered pricing
  const { isMember } = useMembershipStatus();

  // Upload limits (warm-up period system)
  const {
    stats: _uploadStats,
    uploadsRemaining,
    maxFileSizeAllowed: _maxFileSizeAllowed,
    isInWarmupPeriod,
    daysRemainingInWarmup,
    hasUploadPass,
    checkUpload: checkUploadEligibility,
    // recordUpload removed — server-side upload routes (v1/library/upload,
    // register-cdn-link, v1/library/write) now call recordServerUpload() directly,
    // so the client no longer needs to PUT /api/upload-check after each upload.
    // Using the server count as source of truth avoids double-counting.
    recordUploadPassPurchase: _recordUploadPassPurchase,
    refresh: refreshUploadCount,
    isLoading: isUploadLimitsLoading,
  } = useUploadReputation();

  // Calculate current daily limit based on warmup period and upload pass
  const dailyLimit = isInWarmupPeriod && !hasUploadPass ? WARMUP_DAILY_LIMIT : REGULAR_DAILY_LIMIT;

  // Content hash for deduplication
  const [contentHash, setContentHash] = useState<string | null>(null);
  const [duplicateWarning, setDuplicateWarning] = useState<DuplicateCheckResult | null>(null);
  const [isCheckingDuplicate, setIsCheckingDuplicate] = useState(false);
  const [uploadWarning, setUploadWarning] = useState<string | null>(null);
  // Upload Pass purchase option - shown when in warm-up and hit daily limit
  const [canPurchaseUploadPass, setCanPurchaseUploadPass] = useState(false);

  // Draft persistence - save form data to localStorage so it survives upload failures/refreshes
  const DRAFT_KEY = "net-library-upload-draft";

  // Clean up invalid draft data on mount (e.g., old blob URLs that no longer work)
  useEffect(() => {
    try {
      const savedDraft = localStorage.getItem(DRAFT_KEY);
      if (savedDraft) {
        const draft = JSON.parse(savedDraft);
        // If draft has a blob URL for cover (from old code), clear the cover field
        if (draft.coverArtUrl && draft.coverArtUrl.startsWith("blob:")) {
          console.log("[UploadTab] Cleaning invalid blob URL from draft");
          draft.coverArtUrl = null;
          draft.isUserSelectedCover = false;
          localStorage.setItem(DRAFT_KEY, JSON.stringify(draft));
        }
      }
    } catch {
      // Ignore errors during cleanup
    }
  }, []);

  // Save draft whenever form fields change (debounced)
  // NOTE: Blob URLs (blob:...) are NOT persisted - they become invalid after session ends
  useEffect(() => {
    // Only save if we have a file selected
    if (uploadState.status !== "selected" || !selectedFile) return;

    const timeoutId = setTimeout(() => {
      // Don't save blob URLs - they won't work after page refresh
      // Only save data URLs (data:...) or external URLs (http/https)
      const persistableCoverUrl = coverArtUrl && !coverArtUrl.startsWith("blob:")
        ? coverArtUrl
        : null;

      const draft = {
        fileName: selectedFile.name,
        fileSize: selectedFile.size,
        bookTitle,
        authorName,
        publicationYear,
        publisher,
        isbn,
        selectedCategories,
        coverArtUrl: persistableCoverUrl,
        isUserSelectedCover: persistableCoverUrl ? isUserSelectedCover : false,
        savedAt: Date.now(),
      };
      try {
        localStorage.setItem(DRAFT_KEY, JSON.stringify(draft));
        if (coverArtUrl && coverArtUrl.startsWith("blob:")) {
          console.log("[UploadTab] Draft saved (cover art excluded - blob URL not persistable)");
        }
      } catch (e) {
        console.warn("[UploadTab] Failed to save draft:", e);
      }
    }, 500); // Debounce 500ms

    return () => clearTimeout(timeoutId);
  }, [uploadState.status, selectedFile, bookTitle, authorName, publicationYear, publisher, isbn, selectedCategories, coverArtUrl, isUserSelectedCover]);

  // Restore draft on file selection if same file
  const restoreDraftIfMatching = (file: File) => {
    try {
      const savedDraft = localStorage.getItem(DRAFT_KEY);
      if (!savedDraft) return false;

      const draft = JSON.parse(savedDraft);
      // Only restore if same file (by name and size) and not too old (24 hours)
      const maxAge = 24 * 60 * 60 * 1000;
      if (draft.fileName === file.name && draft.fileSize === file.size && Date.now() - draft.savedAt < maxAge) {
        // Restore form fields
        if (draft.bookTitle) setBookTitle(draft.bookTitle);
        if (draft.authorName) setAuthorName(draft.authorName);
        if (draft.publicationYear) setPublicationYear(draft.publicationYear);
        if (draft.publisher) setPublisher(draft.publisher);
        if (draft.isbn) setIsbn(draft.isbn);
        if (draft.selectedCategories?.length > 0) setSelectedCategories(draft.selectedCategories);
        // Only restore cover if it's a valid persistable URL (data: or http/https)
        // Blob URLs would have been filtered out during save, but double-check here
        if (draft.coverArtUrl && !draft.coverArtUrl.startsWith("blob:")) {
          setCoverArtUrl(draft.coverArtUrl);
          setIsUserSelectedCover(draft.isUserSelectedCover || false);
          isUserSelectedCoverRef.current = draft.isUserSelectedCover || false;
        }
        console.log("[UploadTab] Draft restored for file:", file.name, draft.coverArtUrl ? "(with cover)" : "(cover will be re-extracted)");
        return true;
      }
    } catch (e) {
      console.warn("[UploadTab] Failed to restore draft:", e);
    }
    return false;
  };

  // Clear draft on successful upload
  const clearDraft = () => {
    try {
      localStorage.removeItem(DRAFT_KEY);
    } catch {
      // ignore
    }
  };

  // Net upload hook - must be declared before useEffect that uses walletAddress
  const fileInputRef = useRef<HTMLInputElement>(null);
  // TODO: Re-enable isSponsored after Feb 1st when paymaster is funded
  const {
    uploadFile,
    progress,
    reset: resetUpload,
    isConnected,
    address: walletAddress,
    estimateUploadCost,
    getRelayBalance,
    fundWallet,
    recoverUnverifiedPayments,
    recoverPendingPayments, // Fast recovery from localStorage (for Base App wallet quick dismiss)
    cancelUpload,
  } = useRelayUpload();

  // Track cancellation state for UI feedback
  const [isCancelling, setIsCancelling] = useState(false);

  // Handle cancel with UI feedback
  const handleCancelUpload = () => {
    setIsCancelling(true);
    cancelUpload();
    // Reset after a short delay to show "Cancelling..." state
    setTimeout(() => {
      setIsCancelling(false);
    }, 1500);
  };


  // Re-check duplicates when author or ISBN changes (debounced)
  useEffect(() => {
    if (!selectedFile || !contentHash || uploadState.status !== "selected") return;

    // Only re-check if author or ISBN have meaningful values
    const hasAuthor = authorName.trim().length > 2;
    const hasIsbn = isbn.trim().length >= 8;
    const hasTitle = bookTitle.trim().length > 2;

    if (!hasAuthor && !hasIsbn) return; // No new data to check against

    const timeoutId = setTimeout(async () => {
      setIsCheckingDuplicate(true);
      try {
        // Re-run check with updated metadata
        const response = await fetch("/api/upload-check", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            address: walletAddress,
            isMember,
            contentHash,
            title: hasTitle ? bookTitle.trim() : selectedFile.name,
            author: hasAuthor ? authorName.trim() : undefined,
            isbn: hasIsbn ? isbn.trim() : undefined,
            fileSize: selectedFile.size,
          }),
        });

        if (response.ok) {
          const data = await response.json();
          if (data.duplicateCheck) {
            setDuplicateWarning(data.duplicateCheck);
          }
        }
      } catch (e) {
        console.error("[UploadTab] Re-check failed:", e);
      }
      setIsCheckingDuplicate(false);
    }, 500); // Debounce 500ms

    return () => clearTimeout(timeoutId);
  }, [authorName, isbn, bookTitle, contentHash, selectedFile, uploadState.status, walletAddress, isMember]);

  // Multi-file upload mode
  const [showMultiUpload, setShowMultiUpload] = useState(false);
  const [showBatchCdnImport, setShowBatchCdnImport] = useState(false);
  const [isBatchCdnImporting, setIsBatchCdnImporting] = useState(false);
  const [uploadQueue, setUploadQueue] = useState<QueuedUpload[]>([]);
  const [isProcessingQueue, setIsProcessingQueue] = useState(false);
  const [queueProgress, setQueueProgress] = useState<{ current: number; total: number }>({ current: 0, total: 0 });

  // PDF cover extraction
  const { extractCover, isExtracting: isExtractingCover } = usePdfCover();

  // Cover upload (converts base64 to hosted URL for share images)
  const { uploadCover, needsUpload: coverNeedsUpload } = useCoverUpload();

  // x402 Relay cost estimation state (ETH with USD display)
  const [gasEstimate, setGasEstimate] = useState<{
    estimatedCostEth: string; // ETH amount (actual cost)
    estimatedCostUsdc: string; // USD amount (display only)
    balanceEth: string; // Relay balance in ETH (actual)
    balanceUsdc: string; // Relay balance in USD (display only)
    sufficient: boolean;
    lowBalance?: boolean; // Below minimum threshold
  } | null>(null);
  const [isEstimatingGas, setIsEstimatingGas] = useState(false);
  const [showAddFundsModal, setShowAddFundsModal] = useState(false);
  const [isStandaloneAddFunds, setIsStandaloneAddFunds] = useState(false); // True when adding funds from header, not during upload
  const [balanceRefreshTrigger, setBalanceRefreshTrigger] = useState(0); // Increment to trigger UploadWalletBalance refresh

  // Batch upload cost state (ETH with USD display)
  const [batchGasEstimate, setBatchGasEstimate] = useState<{
    estimatedCostEth: string; // ETH amount (actual)
    estimatedCostUsdc: string; // USD amount (display)
    balanceEth: string; // Relay balance in ETH
    balanceUsdc: string; // Relay balance in USD (display)
    sufficient: boolean;
    shortfall: string;
    lowBalance?: boolean;
  } | null>(null);
  const [_batchPaused, setBatchPaused] = useState(false);
  const [_pausedFileId, setPausedFileId] = useState<string | null>(null);
  const [showBatchAddFundsModal, setShowBatchAddFundsModal] = useState(false);
  const [batchFundingState, setBatchFundingState] = useState<{ loading: boolean; error: string | null }>({ loading: false, error: null });
  const [fundingAmount, setFundingAmount] = useState<number>(0.10); // User-selected funding amount (Net Protocol presets: 0.10, 0.25, 5.00)

  // Refresh balance when tab becomes active
  useEffect(() => {
    if (isActive) {
      setBalanceRefreshTrigger(prev => prev + 1);
    }
  }, [isActive]);

  // Sync relay hook progress with local state
  useEffect(() => {
    // x402 Relay status mapping
    if (progress.status === "estimating" || progress.status === "checking-balance") {
      setUploadState(prev => ({ ...prev, status: "uploading", currentChunkStatus: "pending" }));
    } else if (progress.status === "needs-funding" || progress.status === "funding") {
      setUploadState(prev => ({
        ...prev,
        status: "uploading",
        currentChunkStatus: "signing", // Funding requires wallet signature
        totalChunks: progress.totalTransactions,
        completedChunks: progress.completedTransactions,
        isFunding: true, // Mark as funding in progress
      }));
    } else if (progress.status === "creating-session" || progress.status === "preparing") {
      setUploadState(prev => ({
        ...prev,
        status: "uploading",
        currentChunkStatus: "pending",
        totalChunks: progress.totalTransactions,
        completedChunks: progress.completedTransactions,
        isFunding: false, // No longer funding
      }));
    } else if (progress.status === "submitting") {
      setUploadState(prev => ({
        ...prev,
        status: "uploading",
        currentChunkStatus: "confirming",
        totalChunks: progress.totalTransactions,
        completedChunks: progress.completedTransactions,
        isFunding: false, // No longer funding
      }));
    } else if (progress.status === "confirming" || progress.status === "updating-index") {
      setUploadState(prev => ({
        ...prev,
        status: "uploading",
        currentChunkStatus: "waiting-onchain",
        totalChunks: progress.totalTransactions,
        completedChunks: progress.completedTransactions,
        isFunding: false, // No longer funding
      }));
    } else if (progress.status === "complete") {
      setUploadState(prev => ({
        ...prev,
        status: "complete",
        cdnUrl: progress.cdnUrl,
      }));
    } else if (progress.status === "error") {
      setUploadState(prev => ({
        ...prev,
        status: "idle",
        error: progress.error,
        isFunding: false, // Clear funding state on error
      }));
    } else if (progress.status === "fallback-prompt") {
      // User can choose to fallback to direct wallet
      setUploadState(prev => ({
        ...prev,
        status: "idle",
        isFunding: false, // Clear funding state
        error: progress.fallbackReason || "Relay unavailable. You can retry with direct wallet.",
      }));
    } else if (progress.status === "idle") {
      // Check if this is a funding success (currentStep contains "Funded")
      const wasFunding = uploadState.isFunding;
      const fundedMatch = progress.currentStep?.match(/Funded \$?([\d.]+)/i);

      if (wasFunding && fundedMatch) {
        // Show success message briefly
        setFundingSuccess({ show: true, amount: fundedMatch[1] });
        // Auto-hide after 2 seconds
        setTimeout(() => {
          setFundingSuccess({ show: false });
        }, 2000);
      }

      // Only reset to idle if we were in a transient state (uploading/funding)
      // Don't reset if user has selected a file - that would lose their selection!
      setUploadState(prev => {
        if (prev.status === "selected" || prev.status === "complete") {
          // Keep current status, just clear funding flag
          return { ...prev, isFunding: false };
        }
        // Reset to idle for other states (uploading that got cancelled, etc.)
        return { ...prev, status: "idle", isFunding: false };
      });
    }
  }, [progress, uploadState.isFunding]);

  // Recovery state - relay handles recovery internally via chunk idempotency
  const [recoveryState, setRecoveryState] = useState<UploadRecoveryState | null>(null);
  // Track recovery data for actual upload (separate from display state)
  const [pendingRecovery, setPendingRecovery] = useState<{
    completedChunkKeys: string[];
    allChunkKeys: string[];
    storageKey: string;
  } | null>(null);

  // Check for recoverable uploads on mount (using local storage)
  // Note: x402 relay handles recovery via chunk idempotency, so this is mainly for display
  useEffect(() => {
    // Recovery info is simplified with relay - just check if there's pending state
    // The relay will automatically skip already-stored chunks
  }, [walletAddress]);

  const dismissRecovery = () => {
    // Recovery is now handled by relay's chunk idempotency
    setRecoveryState(null);
    setPendingRecovery(null);
  };

  const toggleCategory = (categoryId: string) => {
    setSelectedCategories((prev) => {
      if (prev.includes(categoryId)) {
        return prev.filter((id) => id !== categoryId);
      }
      if (prev.length >= 3) {
        return prev; // max 3 categories
      }
      return [...prev, categoryId];
    });
  };

  const handleFileSelect = async (file: File) => {
    console.log("[UploadTab] handleFileSelect called:", file.name, file.size);

    // Reset warnings and EPUB state
    setDuplicateWarning(null);
    setUploadWarning(null);
    setCanPurchaseUploadPass(false);
    setContentHash(null);
    setEpubConversion(null);
    setOriginalEpubName(null);

    // ── Microsoft Office / legacy format conversions ──────────────────────────
    // All conversions happen client-side (no server needed) and produce HTML or
    // plain text that the viewer can render as mediaType "text".
    const fname = file.name.toLowerCase();

    // .docx → HTML via mammoth
    if (fname.endsWith(".docx") || file.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") {
      console.log("[UploadTab] .docx detected, converting to HTML via mammoth...");
      try {
        const mammoth = await import("mammoth");
        const arrayBuffer = await file.arrayBuffer();
        const result = await mammoth.convertToHtml({ arrayBuffer });
        if (!result.value) throw new Error("Empty conversion result");
        const htmlBlob = new Blob([result.value], { type: "text/html" });
        file = new File([htmlBlob], `${file.name.replace(/\.docx$/i, "")}.html`, { type: "text/html" });
        console.log("[UploadTab] .docx → HTML ok");
      } catch (err) {
        setUploadState({ status: "idle", fileName: "", fileSize: 0, totalChunks: 0, completedChunks: 0, currentChunkStatus: "pending",
          error: `Word document conversion failed: ${err instanceof Error ? err.message : "Unknown error"}. Try saving as PDF instead.` });
        return;
      }
    }

    // .doc (old binary) — mammoth can't parse it; ask user to resave
    else if (fname.endsWith(".doc") || file.type === "application/msword") {
      setUploadState({ status: "idle", fileName: "", fileSize: 0, totalChunks: 0, completedChunks: 0, currentChunkStatus: "pending",
        error: "Legacy .doc files are not supported. Open in Word and save as .docx or PDF, then re-upload." });
      return;
    }

    // .xlsx / .xls → HTML table via SheetJS
    else if (fname.endsWith(".xlsx") || fname.endsWith(".xls") ||
      file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
      file.type === "application/vnd.ms-excel") {
      console.log("[UploadTab] Spreadsheet detected, converting via SheetJS...");
      try {
        const XLSX = await import("xlsx");
        const arrayBuffer = await file.arrayBuffer();
        const workbook = XLSX.read(arrayBuffer, { type: "array" });
        // Convert every sheet to an HTML table, separated by headings
        const htmlParts: string[] = [];
        for (const sheetName of workbook.SheetNames) {
          const sheet = workbook.Sheets[sheetName];
          const sheetHtml = XLSX.utils.sheet_to_html(sheet);
          htmlParts.push(`<h2>${sheetName}</h2>${sheetHtml}`);
        }
        const fullHtml = `<!DOCTYPE html><html><body>${htmlParts.join("<hr/>")}</body></html>`;
        const htmlBlob = new Blob([fullHtml], { type: "text/html" });
        const ext = fname.endsWith(".xlsx") ? ".xlsx" : ".xls";
        file = new File([htmlBlob], `${file.name.replace(new RegExp(`\\${ext}$`, "i"), "")}.html`, { type: "text/html" });
        console.log("[UploadTab] Spreadsheet → HTML ok");
      } catch (err) {
        setUploadState({ status: "idle", fileName: "", fileSize: 0, totalChunks: 0, completedChunks: 0, currentChunkStatus: "pending",
          error: `Spreadsheet conversion failed: ${err instanceof Error ? err.message : "Unknown error"}. Try saving as PDF instead.` });
        return;
      }
    }

    // .pptx → plain text (slide text extraction) via JSZip
    else if (fname.endsWith(".pptx") || file.type === "application/vnd.openxmlformats-officedocument.presentationml.presentation") {
      console.log("[UploadTab] .pptx detected, extracting slide text via JSZip...");
      try {
        const JSZip = (await import("jszip")).default;
        const arrayBuffer = await file.arrayBuffer();
        const zip = await JSZip.loadAsync(arrayBuffer);
        // Slides live at ppt/slides/slide*.xml
        const slideFiles = Object.keys(zip.files)
          .filter(f => f.match(/^ppt\/slides\/slide\d+\.xml$/))
          .sort((a, b) => {
            const numA = parseInt(a.match(/\d+/)?.[0] || "0");
            const numB = parseInt(b.match(/\d+/)?.[0] || "0");
            return numA - numB;
          });
        const slideTexts: string[] = [];
        for (const slidePath of slideFiles) {
          const xml = await zip.files[slidePath].async("string");
          // Strip XML tags and extract text nodes
          const text = xml.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
          if (text) slideTexts.push(`--- Slide ${slideFiles.indexOf(slidePath) + 1} ---\n${text}`);
        }
        if (!slideTexts.length) throw new Error("No slide text found");
        const plainText = slideTexts.join("\n\n");
        const txtBlob = new Blob([plainText], { type: "text/plain" });
        file = new File([txtBlob], `${file.name.replace(/\.pptx$/i, "")}.txt`, { type: "text/plain" });
        console.log("[UploadTab] .pptx → text ok, slides:", slideFiles.length);
      } catch (err) {
        setUploadState({ status: "idle", fileName: "", fileSize: 0, totalChunks: 0, completedChunks: 0, currentChunkStatus: "pending",
          error: `PowerPoint conversion failed: ${err instanceof Error ? err.message : "Unknown error"}. Try exporting as PDF instead.` });
        return;
      }
    }

    // .ppt (old binary) — can't parse without server; ask user to resave
    else if (fname.endsWith(".ppt") || file.type === "application/vnd.ms-powerpoint") {
      setUploadState({ status: "idle", fileName: "", fileSize: 0, totalChunks: 0, completedChunks: 0, currentChunkStatus: "pending",
        error: "Legacy .ppt files are not supported. Open in PowerPoint and save as .pptx or PDF, then re-upload." });
      return;
    }

    // .rtf → plain text (strip RTF control words)
    else if (fname.endsWith(".rtf") || file.type === "application/rtf" || file.type === "text/rtf") {
      console.log("[UploadTab] .rtf detected, stripping RTF formatting...");
      try {
        const rtfText = await file.text();
        // Strip RTF control words, groups, and binary data — keep visible text
        const plain = rtfText
          .replace(/\\bin\d+ ?[^\\}]*/g, "") // binary blobs
          .replace(/\{[^{}]*\}/g, " ")        // groups
          .replace(/\\[a-z]+\d* ?/g, "")      // control words
          .replace(/[\\{}]/g, "")             // remaining special chars
          .replace(/\s+/g, " ").trim();
        if (!plain) throw new Error("No text content found");
        const txtBlob = new Blob([plain], { type: "text/plain" });
        file = new File([txtBlob], `${file.name.replace(/\.rtf$/i, "")}.txt`, { type: "text/plain" });
        console.log("[UploadTab] .rtf → text ok");
      } catch (err) {
        setUploadState({ status: "idle", fileName: "", fileSize: 0, totalChunks: 0, completedChunks: 0, currentChunkStatus: "pending",
          error: `RTF conversion failed: ${err instanceof Error ? err.message : "Unknown error"}.` });
        return;
      }
    }

    // Adobe formats — can't render without server-side tools
    else if ([".ai", ".psd", ".indd", ".xd"].some(ext => fname.endsWith(ext))) {
      setUploadState({ status: "idle", fileName: "", fileSize: 0, totalChunks: 0, completedChunks: 0, currentChunkStatus: "pending",
        error: `Adobe ${fname.split(".").pop()?.toUpperCase()} files cannot be displayed in the browser. Export as PDF or image (PNG/JPG) and re-upload.` });
      return;
    }

    // Check if this is an EPUB file - convert to PDF first
    const isEpub = file.name.toLowerCase().endsWith(".epub") || file.type === "application/epub+zip";
    if (isEpub) {
      console.log("[UploadTab] EPUB detected, starting conversion to PDF...");
      setOriginalEpubName(file.name);

      // Lazy load the converter to avoid build-time bundling issues
      const { convertEpubToPdf } = await loadEpubConverter();
      const result = await convertEpubToPdf(file, (progress) => {
        setEpubConversion(progress);
      });

      if (!result.success || !result.pdfFile) {
        setUploadState({
          status: "idle",
          fileName: "",
          fileSize: 0,
          totalChunks: 0,
          completedChunks: 0,
          currentChunkStatus: "pending",
          error: `EPUB conversion failed: ${result.error || "Unknown error"}`,
        });
        setEpubConversion(null);
        return;
      }

      // Use the converted PDF file instead
      console.log("[UploadTab] EPUB converted successfully:", result.pdfFile.name, result.pageCount, "pages");
      file = result.pdfFile;

      // Clear conversion progress after a short delay to show "complete"
      setTimeout(() => setEpubConversion(null), 2000);
    }

    // Check file size limit
    if (file.size > MAX_FILE_SIZE) {
      setUploadState({
        status: "idle",
        fileName: "",
        fileSize: 0,
        totalChunks: 0,
        completedChunks: 0,
        currentChunkStatus: "pending",
        error: `File too large. Maximum size is ${MAX_FILE_SIZE / 1024 / 1024}MB. Your file is ${(file.size / 1024 / 1024).toFixed(1)}MB.`,
      });
      return;
    }

    // Check reputation-based limits
    setIsCheckingDuplicate(true);
    try {
      const { eligible, duplicate, contentHash: hash } = await checkUploadEligibility(file);
      setContentHash(hash);

      // If resuming, verify file matches - we can only check by size since we clear localStorage
      // on "Re-upload Same File" click. The original file hash was stored in localStorage but
      // we now have it only in pendingRecovery which doesn't include hash.
      // At minimum, verify the file produces the same number of chunks.
      if (pendingRecovery && pendingRecovery.allChunkKeys.length > 0) {
        // Calculate expected chunks for this file size to verify compatibility
        const base64Size = file.size * 1.33;
        const XML_CHUNK_SIZE = 80000; // Must match net-protocol.ts (Net Protocol spec: 80KB)
        const expectedChunks = Math.ceil(base64Size / XML_CHUNK_SIZE);
        const recoveryChunkCount = pendingRecovery.allChunkKeys.length;

        if (expectedChunks !== recoveryChunkCount) {
          console.warn(`[UploadTab] Chunk count mismatch! Expected: ${expectedChunks}, Recovery has: ${recoveryChunkCount}`);
          // Clear recovery - this is probably a different file
          setPendingRecovery(null);
          setUploadWarning("This file produces a different number of chunks than the original. Uploading as a new file instead.");
        } else {
          console.log(`[UploadTab] File verified for resume: ${file.name} (${file.size} bytes, ${expectedChunks} chunks)`);
          console.log(`[UploadTab] Will skip ${pendingRecovery.completedChunkKeys.length} already-uploaded chunks`);
        }
      }

      // Check upload limits
      if (!eligible.canUpload) {
        // Check if user can purchase Upload Pass (warm-up period, hit daily limit)
        if (eligible.canPurchaseUploadPass && eligible.dailyLimitExceeded) {
          // Daily limit exceeded during warm-up - can purchase Upload Pass
          setCanPurchaseUploadPass(true);
          setUploadWarning(eligible.reason || "Daily limit reached");
          // Don't return - allow file selection to continue so user can choose to buy pass
        } else {
          // Hard block - file too large or other restriction
          setUploadWarning(eligible.reason || "Upload not allowed");
          setUploadState({
            status: "idle",
            fileName: "",
            fileSize: 0,
            totalChunks: 0,
            completedChunks: 0,
            currentChunkStatus: "pending",
            error: eligible.reason,
          });
          setIsCheckingDuplicate(false);
          return;
        }
      }

      // Check for duplicate content
      if (duplicate?.isDuplicate) {
        setDuplicateWarning(duplicate);
      }
    } catch (e) {
      console.error("[UploadTab] Eligibility check failed:", e);
      // Continue anyway if check fails - don't block upload
    }
    setIsCheckingDuplicate(false);

    // Estimate transactions based on file size (per Net Protocol spec)
    // < 20KB: regular storage (1 tx)
    // 20-80KB: chunked storage (1 tx) - compressed + split into 20KB chunks
    // > 80KB: XML storage - split into 80KB pieces, each compressed & split into 20KB sub-chunks
    let chunks: number;
    if (file.size < 20000) {
      chunks = 1; // Regular storage - single transaction
    } else if (file.size < 80000) {
      chunks = 1; // Chunked storage - single transaction
    } else {
      // XML storage: Each 80KB XML chunk → compressed → split into ~20KB sub-chunks
      // PDF/binary files compress poorly (0.7-1.0 ratio), so 80KB → ~56-80KB → 3-4 sub-chunks
      // Text files compress better (~0.3-0.5 ratio), so 80KB → ~24-40KB → 2 sub-chunks
      // Use 4 sub-chunks as conservative estimate (matches actual behavior for PDFs)
      const base64Size = file.size * 1.33;
      const xmlChunkCount = Math.ceil(base64Size / 80000);
      const subChunksPerXmlChunk = 4; // Conservative: each 80KB chunk → 4 x ~20KB sub-chunks
      chunks = (xmlChunkCount * subChunksPerXmlChunk) + 1; // +1 for metadata
    }
    const duplicateCheck = checkForDuplicates(file.name, books);

    console.log("[UploadTab] Setting file as selected:", file.name);
    setSelectedFile(file);
    // Track content type for "View Content" button after upload
    setLastUploadedContentType(detectContentTypeFromMime(file.type));
    setUploadState({
      status: "selected",
      fileName: file.name,
      fileSize: file.size,
      totalChunks: chunks,
      completedChunks: 0,
      currentChunkStatus: "pending",
      duplicateWarning: duplicateCheck || undefined,
    });
    console.log("[UploadTab] Upload state set to 'selected'");

    // Try to restore draft for this file (if user is re-selecting after failure/refresh)
    const draftRestored = restoreDraftIfMatching(file);

    // Auto-fill title from filename if empty AND no draft was restored
    if (!bookTitle && !draftRestored) {
      const nameWithoutExt = file.name.replace(/\.[^/.]+$/, "").replace(/[-_]/g, " ");
      setBookTitle(nameWithoutExt);
    }

    // Auto-extract cover from PDF (check both MIME type and file extension)
    // Skip if user has manually selected a cover, or if draft restored a cover
    const isPdf = file.type.includes("pdf") || file.name.toLowerCase().endsWith(".pdf");
    if (isPdf && !coverArtUrl && !isUserSelectedCoverRef.current && !draftRestored) {
      console.log("[UploadTab] Attempting to extract cover from PDF:", file.name);
      try {
        const cover = await extractCover(file, 300);
        // Double-check user hasn't selected a cover while we were extracting (use ref for real-time check)
        if (cover && !isUserSelectedCoverRef.current) {
          console.log("[UploadTab] Cover extracted successfully");
          setCoverArtUrl(cover.dataUrl);
        } else {
          console.log("[UploadTab] Cover extraction returned null or user selected cover during extraction");
        }
      } catch (e) {
        console.log("[UploadTab] Cover extraction failed, will use default:", e);
      }
    }
  };

  const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    console.log("[UploadTab] handleFileInputChange called, files:", e.target.files?.length);
    const file = e.target.files?.[0];
    if (file) {
      console.log("[UploadTab] File detected from input:", file.name);
      // Show preview modal first
      setPreviewFile(file);
      setShowPreviewModal(true);
    } else {
      console.log("[UploadTab] No file in input event");
    }
    // Clear the input so the same file can be selected again if needed
    e.target.value = "";
  };

  // Extract cover from a CDN PDF URL and save it to our cover storage
  // This runs in the background after CDN import - lightweight, non-blocking
  const extractAndSaveCover = async (cdnUrl: string, contentKey: string, operator: string) => {
    try {
      console.log("[CDNLink] Extracting cover from:", cdnUrl);

      // Fetch the PDF
      const response = await fetch(cdnUrl);
      if (!response.ok) {
        throw new Error(`Failed to fetch PDF: ${response.status}`);
      }

      // Convert to blob/file for the extract function
      const blob = await response.blob();
      const file = new File([blob], "document.pdf", { type: "application/pdf" });

      // Extract cover using existing hook (runs in browser, uses PDF.js)
      const cover = await extractCover(file, 300);
      if (!cover?.dataUrl) {
        console.log("[CDNLink] No cover could be extracted");
        return;
      }

      console.log("[CDNLink] Cover extracted, saving to storage...");

      // Save the cover to our KV-based cover storage
      const safeKey = contentKey.replace(/[^a-zA-Z0-9]/g, "").slice(0, 32);
      const saveResponse = await fetch(`/api/covers/${safeKey}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          dataUrl: cover.dataUrl,
          contentKey,
        }),
      });

      if (!saveResponse.ok) {
        throw new Error(`Failed to save cover: ${saveResponse.status}`);
      }

      const saveResult = await saveResponse.json();
      console.log("[CDNLink] Cover saved:", saveResult.url);

      // Update the discovery entry with the cover URL
      // Use operator (importer's wallet address) to authorize the update
      await fetch("/api/discovery", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          contentKey,
          operator, // The importer's wallet address
          coverUrl: saveResult.url,
        }),
      });

      console.log("[CDNLink] Discovery entry updated with cover URL");
    } catch (err) {
      // Don't throw - this is background work, failure is acceptable
      console.log("[CDNLink] Cover extraction/save failed:", err);
    }
  };

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    setIsDragging(false);
    const file = e.dataTransfer.files?.[0];
    if (file) {
      // Show preview modal first
      setPreviewFile(file);
      setShowPreviewModal(true);
    }
  };

  // Called when user confirms preview and wants to continue to metadata form
  const handlePreviewContinue = async () => {
    if (previewFile) {
      // Capture file reference before clearing state
      const fileToSelect = previewFile;
      setShowPreviewModal(false);
      setPreviewFile(null);
      // Now process the file (async)
      await handleFileSelect(fileToSelect);
    }
  };

  // Called when user cancels preview
  const handlePreviewClose = () => {
    setShowPreviewModal(false);
    setPreviewFile(null);
  };

  const handleUpload = async () => {
    if (!selectedFile || !isConnected) return;

    setUploadState((prev) => ({
      ...prev,
      status: "uploading",
      currentChunkStatus: "signing",
    }));

    // Upload cover image to get a hosted URL (if it's a base64 data URL)
    // This is required for share images to work - base64 URLs are too large for OG image params
    let finalCoverUrl = coverArtUrl || undefined;
    if (coverArtUrl && coverNeedsUpload(coverArtUrl)) {
      console.log("[Upload] Uploading cover art to get hosted URL...");
      const coverResult = await uploadCover(coverArtUrl);
      if (coverResult.success && coverResult.url) {
        console.log("[Upload] Cover uploaded:", coverResult.url);
        finalCoverUrl = coverResult.url;
      } else {
        // Cover upload to Vercel Blob failed - keep the base64 data URL
        // This will still show the cover in the app, just not in share images
        console.warn("[Upload] Cover upload to hosted storage failed, using base64 fallback:", coverResult.error);
        // Keep finalCoverUrl as the base64 data URL for display in app
        // Share images will use app logo fallback since base64 URLs are too long
      }
    }

    // x402 relay handles recovery via chunk idempotency - no explicit resume needed
    if (pendingRecovery) {
      console.log(`[Upload] Resuming upload via relay chunk idempotency...`);
    }

    // Client-side AES-256-GCM encryption (members only, optional)
    let fileToUpload: File = selectedFile;
    if (encryptEnabled) {
      setIsEncryptingFile(true);
      try {
        // Resolve the actual password string based on passwordSource
        let resolvedPassword: string;
        if (passwordSource === "saved" && selectedSavedPasswordId) {
          // Fetch plaintext password — pass identity as query params (web users have no body on GET)
          const pwParams = new URLSearchParams();
          if (userProfile?.fid) pwParams.set("fid", String(userProfile.fid));
          if (walletAddress) pwParams.set("address", walletAddress);
          const pwQs = pwParams.toString() ? `?${pwParams.toString()}` : "";
          const pwRes = await fetch(`/api/passwords/${selectedSavedPasswordId}${pwQs}`);
          if (!pwRes.ok) {
            throw new Error("Failed to load saved password");
          }
          const pwData = await pwRes.json();
          resolvedPassword = pwData.password as string;
        } else {
          resolvedPassword = encryptPassword.trim();
        }

        if (!resolvedPassword) {
          setUploadState(prev => ({ ...prev, status: "selected", error: "Encryption is enabled but no password was provided." }));
          setIsEncryptingFile(false);
          return;
        }

        const rawBuffer = await selectedFile.arrayBuffer();
        const encryptedBase64 = await encryptContent(rawBuffer, resolvedPassword);
        const encryptedBlob = new Blob([encryptedBase64], { type: "application/octet-stream" });
        fileToUpload = new File([encryptedBlob], selectedFile.name, { type: "application/octet-stream" });
        console.log("[Upload] File encrypted client-side, size:", encryptedBlob.size);

        // Optionally save password to /api/passwords (only for newly typed passwords)
        if (encryptSavePassword && passwordSource === "new") {
          try {
            await fetch("/api/passwords", {
              method: "POST",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                password: resolvedPassword,
                label: encryptPasswordLabel.trim() || (bookTitle || selectedFile.name),
              }),
            });
          } catch {
            // Non-fatal — proceed even if saving the password fails
          }
        }
      } catch (err) {
        console.error("[Upload] Encryption failed:", err);
        setUploadState(prev => ({ ...prev, status: "selected", error: "Encryption failed. Please try again." }));
        setIsEncryptingFile(false);
        return;
      }
      setIsEncryptingFile(false);
    }

    const result = await uploadFile(
      fileToUpload,
      {
        title: bookTitle || selectedFile.name,
        author: authorName || "Unknown",
        categories: selectedCategories,
        coverUrl: finalCoverUrl,
        publicationYear: publicationYear ? parseInt(publicationYear, 10) : undefined,
        publisher: publisher || undefined,
        isbn: isbn || undefined,
        uploaderFid: userProfile?.fid,
        uploaderUsername: userProfile?.username,
        uploaderMemberId: userProfile?.memberId,
        uploaderEnsSubname: userProfile?.ensSubname,
        uploaderStoredUsername: userProfile?.storedFarcasterUsername, // Social identity - Farcaster username
        contentHash: contentHash || undefined, // For deduplication
        encrypted: encryptEnabled || undefined,
      }
    );

    if (result.success) {
      setUploadState((prev) => ({
        ...prev,
        status: "complete",
        cdnUrl: result.cdnUrl,
      }));
      // Haptic feedback on successful upload
      triggerHaptic("success");
      // Clear pending recovery on success
      setPendingRecovery(null);
      // Clear draft on success
      clearDraft();
      // Store contentKey for activity feed posting
      if (result.contentKey) {
        setLastUploadedContentKey(result.contentKey);
        setShowShareToFeed(true);
        // Refresh upload count — the server already incremented via recordServerUpload.
        // Calling recordUpload here would double-count; just re-fetch to sync UI.
        refreshUploadCount();
      }
      // Log successful upload
      addLogEntry({
        fileName: bookTitle || selectedFile.name,
        fileSize: selectedFile.size,
        status: "success",
        contentKey: result.contentKey,
        countedAgainstLimit: true, // Successful uploads count
        totalChunks: progress.totalTransactions, // From relay progress
      });
      // Add to selected stacks (if any were selected)
      if (result.contentKey && selectedStackIds.length > 0) {
        console.log(`[Upload] Adding item to ${selectedStackIds.length} stack(s)...`);
        for (const stackId of selectedStackIds) {
          try {
            const response = await fetch("/api/stacks", {
              method: "PUT",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                stackId,
                action: "add-item",
                owner: walletAddress,
                contentKey: result.contentKey,
              }),
            });
            const stackResult = await response.json();
            if (stackResult.success) {
              console.log(`[Upload] Added to stack ${stackId}`);
            } else {
              console.warn(`[Upload] Failed to add to stack ${stackId}:`, stackResult.error);
            }
          } catch (e) {
            console.error(`[Upload] Error adding to stack ${stackId}:`, e);
          }
        }
      }
      // Refresh the discovery index to show the new upload
      onUploadComplete?.();
    } else {
      // Determine if this was a user cancellation or an actual error
      // Be very specific - only classify as cancelled if it's explicitly a user rejection
      // Timeouts and other errors should NOT be classified as user cancellation
      const errorLower = result.error?.toLowerCase() || "";
      const isCancelled = (
        (errorLower.includes("user rejected") && !errorLower.includes("timeout")) ||
        (errorLower.includes("user denied") && !errorLower.includes("timeout")) ||
        errorLower.includes("user refused") ||
        errorLower.includes("user dismissed") ||
        (errorLower.includes("rejected by user") && !errorLower.includes("timeout")) ||
        errorLower.includes("cancelled by user")
      );

      // IMPORTANT: Do NOT reset form data on failure!
      // User should be able to retry with same metadata.
      // Only reset the upload state, not the form fields.
      setUploadState((prev) => ({
        ...prev,
        status: "selected", // Go back to "selected" so user can retry, not "idle"
        error: result.error,
      }));

      // Log failed/cancelled upload - these do NOT count against daily limit
      addLogEntry({
        fileName: bookTitle || selectedFile.name,
        fileSize: selectedFile.size,
        status: isCancelled ? "cancelled" : "failed",
        error: result.error,
        countedAgainstLimit: false, // Failed uploads don't count!
        totalChunks: progress.totalTransactions, // From relay progress
      });
    }
  };

  const handleReset = () => {
    resetUpload();
    setUploadState({
      status: "idle",
      fileName: "",
      fileSize: 0,
      totalChunks: 0,
      completedChunks: 0,
      currentChunkStatus: "pending",
    });
    setSelectedFile(null);
    setBookTitle("");
    setAuthorName("");
    setPublicationYear("");
    setPublisher("");
    setIsbn("");
    setSelectedCategories([]);
    setCoverArtUrl(null);
    setIsUserSelectedCover(false);
    isUserSelectedCoverRef.current = false;
    setShowCoverUpload(false);
    setShowConfirmUpload(false);
    setIsPreparingUpload(false);
    // Reset feed posting state
    setShowShareToFeed(false);
    setIsPostingToFeed(false);
    setFeedPostResult(null);
    setLastUploadedContentKey(null);
    // Reset premium state
    setShowPremiumModal(false);
    // Reset deduplication state
    setContentHash(null);
    setDuplicateWarning(null);
    setUploadWarning(null);
    setCanPurchaseUploadPass(false);
    setPremiumPaid(false);
    // Reset stack selection
    setSelectedStackIds([]);
    // Reset recovery state
    setPendingRecovery(null);
    // Reset content type tracking
    setLastUploadedContentType(null);
    setShowMultimediaViewer(false);
    // Reset social receipt data
    setLastSocialReceiptData(null);
    setShowSocialShareModal(false);
    // Reset encryption state
    setEncryptEnabled(false);
    setEncryptPassword("");
    setEncryptSavePassword(true);
    setEncryptPasswordLabel("");
    setSelectedSavedPasswordId(null);
    setPasswordSource("new");
    setIsEncryptingFile(false);
  };

  // Fetch saved passwords from /api/passwords when encryption toggle is turned on.
  // Web users pass identity via query params (same pattern as /api/membership, etc.)
  const fetchSavedPasswords = useCallback(async () => {
    setIsFetchingPasswords(true);
    try {
      const params = new URLSearchParams();
      if (userProfile?.fid) params.set("fid", String(userProfile.fid));
      if (walletAddress) params.set("address", walletAddress);
      const qs = params.toString() ? `?${params.toString()}` : "";
      const res = await fetch(`/api/passwords${qs}`);
      if (res.ok) {
        const data = await res.json();
        setSavedPasswords(data.passwords || []);
      }
    } catch {
      // Non-fatal — user can still type a new password
    } finally {
      setIsFetchingPasswords(false);
    }
  }, [userProfile?.fid, walletAddress]);

  // Handle text editor upload - creates a .txt file and uploads it
  const handleTextEditorUpload = async (data: {
    content: string;
    htmlContent: string;
    title: string;
    author: string;
    selectedCategories: string[];
    selectedStackIds: string[];
    publicationYear?: string;
    publisher?: string;
    coverArtUrl?: string;
  }): Promise<{ success: boolean; error?: string }> => {
    // Check upload limits before allowing text upload.
    // Upload Pass bypasses the warm-up tier (10/day → 100/day) but does NOT grant
    // unlimited daily uploads — pass holders are still subject to the 100/day cap.
    if (uploadsRemaining <= 0) {
      setUploadState(prev => ({
        ...prev,
        error: `Daily upload limit reached (${dailyLimit}/day). ${isInWarmupPeriod && !hasUploadPass ? "Purchase an Upload Pass to bypass the warm-up limit." : "Try again tomorrow."}`,
      }));
      return { success: false, error: "Daily upload limit reached" };
    }

    setIsUploadingText(true);

    try {
      // Prefer HTML content when available (preserves bold, italic, links, headings, etc.)
      // Fall back to plain text when the user has typed unformatted content.
      let file: File;
      let fileName: string;
      const safeTitle = data.title.replace(/[^a-zA-Z0-9]/g, "_");
      const hasFormatting =
        data.htmlContent &&
        data.htmlContent.trim() !== "" &&
        data.htmlContent.trim() !== data.content.trim();

      if (hasFormatting) {
        const htmlBlob = new Blob([data.htmlContent], { type: "text/html" });
        fileName = `${safeTitle}.html`;
        file = new File([htmlBlob], fileName, { type: "text/html" });
      } else {
        const plainBlob = new Blob([data.content], { type: "text/plain" });
        fileName = `${safeTitle}.txt`;
        file = new File([plainBlob], fileName, { type: "text/plain" });
      }

      // Upload cover to KV if it's a data URL (user-provided URLs are already hosted)
      let finalCoverUrl = data.coverArtUrl;
      if (data.coverArtUrl && coverNeedsUpload(data.coverArtUrl)) {
        console.log("[TextEditor] Uploading cover art to KV...");
        const coverResult = await uploadCover(data.coverArtUrl, `text-${Date.now()}`);
        if (coverResult.success && coverResult.url) {
          console.log("[TextEditor] Cover uploaded:", coverResult.url);
          finalCoverUrl = coverResult.url;
        } else {
          console.warn("[TextEditor] Cover upload failed, thumbnails will use fallback:", coverResult.error);
          finalCoverUrl = undefined;
        }
      }

      // Use the existing upload hook
      const result = await uploadFile(file, {
        title: data.title,
        author: data.author,
        categories: data.selectedCategories,
        uploaderFid: userProfile?.fid,
        uploaderUsername: userProfile?.username,
        uploaderMemberId: userProfile?.memberId,
        uploaderEnsSubname: userProfile?.ensSubname,
        uploaderStoredUsername: userProfile?.storedFarcasterUsername, // Social identity
        coverUrl: finalCoverUrl,
      });

      if (result.success) {
        // Store contentKey for activity feed posting
        if (result.contentKey) {
          setLastUploadedContentKey(result.contentKey);
          setShowShareToFeed(true);
          // Server already incremented count via recordServerUpload — just refresh.
          refreshUploadCount();
        }

        // Add to selected stacks
        if (result.contentKey && data.selectedStackIds.length > 0) {
          for (const stackId of data.selectedStackIds) {
            try {
              await fetch("/api/stacks", {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                  stackId,
                  action: "add-item",
                  owner: walletAddress,
                  contentKey: result.contentKey,
                }),
              });
            } catch (e) {
              console.error(`[TextUpload] Error adding to stack ${stackId}:`, e);
            }
          }
        }

        // Set upload state to complete
        setUploadState({
          status: "complete",
          fileName: fileName,
          fileSize: file.size,
          totalChunks: progress.totalTransactions || 1,
          completedChunks: progress.completedTransactions || 1,
          currentChunkStatus: "done",
          cdnUrl: result.cdnUrl,
        });
        setBookTitle(data.title);
        setAuthorName(data.author);
        // Text editor creates plain text (or HTML) content
        setLastUploadedContentType("text");

        onUploadComplete?.();
        return { success: true };
      } else {
        setUploadState({
          status: "idle",
          fileName: "",
          fileSize: 0,
          totalChunks: 0,
          completedChunks: 0,
          currentChunkStatus: "pending",
          error: result.error,
        });
        return { success: false, error: result.error || "Upload failed" };
      }
    } catch (err) {
      console.error("[TextUpload] Error:", err);
      const errorMessage = err instanceof Error ? err.message : "Upload failed";
      setUploadState(prev => ({
        ...prev,
        error: errorMessage,
      }));
      return { success: false, error: errorMessage };
    } finally {
      setIsUploadingText(false);
    }
  };

  // Handle created image upload - uploads image created in the image editor
  const handleCreatedImageUpload = async (data: {
    dataUrl: string;
    format: string;
    title: string;
    category: string;
    stackIds: string[];
  }): Promise<void> => {
    // Check upload limits.
    // Upload Pass bypasses the warm-up tier but does NOT grant unlimited daily uploads.
    if (uploadsRemaining <= 0) {
      setUploadState(prev => ({
        ...prev,
        error: `Daily upload limit reached (${dailyLimit}/day). ${isInWarmupPeriod && !hasUploadPass ? "Purchase an Upload Pass to bypass the warm-up limit." : "Try again tomorrow."}`,
      }));
      return;
    }

    setIsUploadingImage(true);

    try {
      // Convert data URL to blob/file
      // NOTE: We use manual base64 decoding instead of fetch() because Safari/iOS/Base App
      // can throw "Load failed" when fetch() is called on data: URLs due to WebKit security policies.
      let blob: Blob;
      try {
        const [header, base64Data] = data.dataUrl.split(",");
        const mimeMatch = header.match(/data:([^;]+)/);
        const detectedMime = mimeMatch ? mimeMatch[1] : (data.format === "jpeg" ? "image/jpeg" : `image/${data.format}`);
        const binaryString = atob(base64Data);
        const bytes = new Uint8Array(binaryString.length);
        for (let i = 0; i < binaryString.length; i++) {
          bytes[i] = binaryString.charCodeAt(i);
        }
        blob = new Blob([bytes], { type: detectedMime });
      } catch (decodeError) {
        console.error("[ImageEditor] Base64 decode failed, falling back to fetch:", decodeError);
        const response = await fetch(data.dataUrl);
        blob = await response.blob();
      }
      const extension = data.format === "jpeg" ? "jpg" : data.format;
      const fileName = `${data.title.replace(/[^a-zA-Z0-9]/g, "_")}.${extension}`;
      const mimeType = data.format === "jpeg" ? "image/jpeg" : `image/${data.format}`;
      const file = new File([blob], fileName, { type: mimeType });

      // Upload the image to KV as cover art (for thumbnails/share images)
      // The created image serves as its own cover since it IS the visual content
      let finalCoverUrl: string | undefined;
      if (data.dataUrl && coverNeedsUpload(data.dataUrl)) {
        console.log("[ImageEditor] Uploading created image to KV for cover art...");
        const coverResult = await uploadCover(data.dataUrl, `created-${Date.now()}`);
        if (coverResult.success && coverResult.url) {
          console.log("[ImageEditor] Cover uploaded:", coverResult.url);
          finalCoverUrl = coverResult.url;
        } else {
          console.warn("[ImageEditor] Cover upload failed, thumbnails will use fallback:", coverResult.error);
        }
      }

      // Use the existing upload hook
      const result = await uploadFile(file, {
        title: data.title,
        author: userProfile?.username || "",
        categories: [data.category],
        uploaderFid: userProfile?.fid,
        uploaderUsername: userProfile?.username,
        uploaderMemberId: userProfile?.memberId,
        uploaderEnsSubname: userProfile?.ensSubname,
        uploaderStoredUsername: userProfile?.storedFarcasterUsername, // Social identity
        coverUrl: finalCoverUrl, // Use the uploaded KV URL for cover
      });

      if (result.success) {
        // Store contentKey for activity feed posting
        if (result.contentKey) {
          setLastUploadedContentKey(result.contentKey);
          setShowShareToFeed(true);
          // Server already incremented count via recordServerUpload — just refresh.
          refreshUploadCount();
        }

        // Add to selected stacks
        if (result.contentKey && data.stackIds.length > 0) {
          for (const stackId of data.stackIds) {
            try {
              await fetch("/api/stacks", {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                  stackId,
                  action: "add-item",
                  owner: walletAddress,
                  contentKey: result.contentKey,
                }),
              });
            } catch (e) {
              console.error(`[ImageUpload] Error adding to stack ${stackId}:`, e);
            }
          }
        }

        // Set upload state to complete
        setUploadState({
          status: "complete",
          fileName: fileName,
          fileSize: file.size,
          totalChunks: progress.totalTransactions || 1,
          completedChunks: progress.completedTransactions || 1,
          currentChunkStatus: "done",
          cdnUrl: result.cdnUrl,
        });
        setBookTitle(data.title);
        setLastUploadedContentType("image");

        onUploadComplete?.();
      } else {
        setUploadState({
          status: "idle",
          fileName: "",
          fileSize: 0,
          totalChunks: 0,
          completedChunks: 0,
          currentChunkStatus: "pending",
          error: result.error,
        });
      }
    } catch (err) {
      console.error("[ImageUpload] Error:", err);
      const errorMessage = err instanceof Error ? err.message : "Upload failed";
      setUploadState(prev => ({
        ...prev,
        error: errorMessage,
      }));
    } finally {
      setIsUploadingImage(false);
    }
  };

  // Handle CDN link import - creates a reference to existing content
  const handleCdnLinkUpload = async (data: {
    cdnUrl: string;
    contentType: "pdf" | "image" | "audio" | "video" | "text" | "unknown";
    title: string;
    author: string;
    selectedCategories: string[];
    selectedStackIds: string[];
    publicationYear?: string;
    publisher?: string;
    isbn?: string;
    coverArtUrl?: string;
  }) => {
    // Check upload limits before allowing CDN import.
    // Upload Pass bypasses the warm-up tier but does NOT grant unlimited daily uploads.
    if (uploadsRemaining <= 0) {
      setUploadState(prev => ({
        ...prev,
        error: `Daily upload limit reached (${dailyLimit}/day). ${isInWarmupPeriod && !hasUploadPass ? "Purchase an Upload Pass to bypass the warm-up limit." : "Try again tomorrow."}`,
      }));
      return;
    }

    setIsUploadingLink(true);

    try {
      // Upload cover to KV if it's a data URL (user-provided URLs are already hosted)
      let finalCoverUrl = data.coverArtUrl;
      if (data.coverArtUrl && coverNeedsUpload(data.coverArtUrl)) {
        console.log("[CDNLink] Uploading cover art to KV...");
        const coverResult = await uploadCover(data.coverArtUrl, `cdn-import-${Date.now()}`);
        if (coverResult.success && coverResult.url) {
          console.log("[CDNLink] Cover uploaded:", coverResult.url);
          finalCoverUrl = coverResult.url;
        } else {
          console.warn("[CDNLink] Cover upload failed, thumbnails will use fallback:", coverResult.error);
          finalCoverUrl = undefined;
        }
      }

      // Register the CDN link as a discovery entry via API
      const response = await fetch("/api/register-cdn-link", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          cdnUrl: data.cdnUrl,
          contentType: data.contentType,
          title: data.title,
          author: data.author,
          categories: data.selectedCategories,
          publicationYear: data.publicationYear,
          publisher: data.publisher,
          isbn: data.isbn,
          coverUrl: finalCoverUrl,
          uploaderAddress: walletAddress,
          uploaderFid: userProfile?.fid,
          uploaderUsername: userProfile?.username,
          uploaderMemberId: userProfile?.memberId,
          uploaderEnsSubname: userProfile?.ensSubname,
          uploaderStoredUsername: userProfile?.storedFarcasterUsername, // Social identity
        }),
      });

      const result = await response.json();

      if (response.ok && result.success) {
        // Store contentKey for activity feed posting
        if (result.contentKey) {
          setLastUploadedContentKey(result.contentKey);
          setShowShareToFeed(true);
          // Server already incremented count via recordServerUpload — just refresh.
          refreshUploadCount();
        }

        // Add to selected stacks
        if (result.contentKey && data.selectedStackIds.length > 0) {
          for (const stackId of data.selectedStackIds) {
            try {
              await fetch("/api/stacks", {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                  stackId,
                  action: "add-item",
                  owner: walletAddress,
                  contentKey: result.contentKey,
                }),
              });
            } catch (e) {
              console.error(`[CDNLink] Error adding to stack ${stackId}:`, e);
            }
          }
        }

        // Set upload state to complete (mark as import, not new upload)
        setUploadState({
          status: "complete",
          fileName: data.title,
          fileSize: 0,
          totalChunks: 1,
          completedChunks: 1,
          currentChunkStatus: "done",
          cdnUrl: data.cdnUrl,
          isImport: true, // CDN imports are not new uploads to Net Protocol
        });
        setBookTitle(data.title);
        setAuthorName(data.author);
        // Track content type for "View Content" button (CDN imports already have a URL)
        setLastUploadedContentType(data.contentType);

        // If it's a PDF and no cover was provided, extract one in the background
        // This is lightweight - runs in user's browser, doesn't block the UI
        if (data.contentType === "pdf" && !data.coverArtUrl && result.contentKey && walletAddress) {
          extractAndSaveCover(data.cdnUrl, result.contentKey, walletAddress).catch(err => {
            console.log("[CDNLink] Cover extraction skipped:", err);
          });
        }

        onUploadComplete?.();
      } else {
        setUploadState(prev => ({
          ...prev,
          error: result.error || "Failed to register content",
        }));
      }
    } catch (err) {
      console.error("[CDNLink] Error:", err);
      setUploadState(prev => ({
        ...prev,
        error: err instanceof Error ? err.message : "Registration failed",
      }));
    } finally {
      setIsUploadingLink(false);
    }
  };

  // Handle social receipt upload - archives a tweet, cast, or other social post as a permanent receipt
  const handleReceiptUpload = async (data: {
    cdnUrl: string; // This is actually a data URL (base64) from the receipt generator
    contentType: "pdf" | "image" | "audio" | "video" | "text" | "unknown";
    title: string;
    author: string;
    selectedCategories: string[];
    selectedStackIds: string[];
    coverArtUrl?: string;
    socialPlatform: SocialPlatform;
    originalUrl: string;
    socialContent: SocialContent;
  }) => {
    // Check upload limits before allowing receipt archive.
    // Upload Pass bypasses the warm-up tier but does NOT grant unlimited daily uploads.
    if (uploadsRemaining <= 0) {
      setUploadState(prev => ({
        ...prev,
        error: `Daily upload limit reached (${dailyLimit}/day). ${isInWarmupPeriod && !hasUploadPass ? "Purchase an Upload Pass to bypass the warm-up limit." : "Try again tomorrow."}`,
      }));
      return;
    }

    setIsUploadingReceipt(true);

    try {
      // IMPORTANT: Social receipts must be uploaded to Net Protocol, NOT just registered as CDN links!
      // The cdnUrl here is actually a data URL (base64 image) from the receipt generator.
      // We need to convert it to a File and upload via the relay hook.

      // Step 1: Convert the data URL (or fetch from URL) to a Blob
      // NOTE: We use manual base64 decoding instead of fetch() because Safari/iOS/Base App
      // can throw "Load failed" when fetch() is called on data: URLs due to WebKit security policies.
      let blob: Blob;
      if (data.cdnUrl.startsWith("data:")) {
        // It's a base64 data URL - decode manually (safer than fetch for data: URLs)
        try {
          const [header, base64Data] = data.cdnUrl.split(",");
          const mimeMatch = header.match(/data:([^;]+)/);
          const mimeType = mimeMatch ? mimeMatch[1] : "image/png";
          const binaryString = atob(base64Data);
          const bytes = new Uint8Array(binaryString.length);
          for (let i = 0; i < binaryString.length; i++) {
            bytes[i] = binaryString.charCodeAt(i);
          }
          blob = new Blob([bytes], { type: mimeType });
        } catch (decodeError) {
          console.error("[Receipt] Base64 decode failed, falling back to fetch:", decodeError);
          // Fallback to fetch if manual decode fails (shouldn't happen with valid data URLs)
          const response = await fetch(data.cdnUrl);
          blob = await response.blob();
        }
      } else {
        // It's a URL - fetch and convert to blob
        const response = await fetch(data.cdnUrl);
        blob = await response.blob();
      }

      // Step 2: Create a File from the blob
      const fileName = `receipt-${data.socialPlatform}-${Date.now()}.png`;
      const file = new File([blob], fileName, { type: "image/png" });

      // Step 3: Upload the receipt image to KV as cover art (for thumbnails/share images)
      // The receipt image serves as its own cover since it's already a visual representation
      let finalCoverUrl: string | undefined;
      if (data.cdnUrl && coverNeedsUpload(data.cdnUrl)) {
        console.log("[Receipt] Uploading receipt image to KV for cover art...");
        const coverResult = await uploadCover(data.cdnUrl, `receipt-${data.socialPlatform}-${Date.now()}`);
        if (coverResult.success && coverResult.url) {
          console.log("[Receipt] Cover uploaded:", coverResult.url);
          finalCoverUrl = coverResult.url;
        } else {
          console.warn("[Receipt] Cover upload failed, thumbnails will use fallback:", coverResult.error);
        }
      }

      // Step 4: Upload to Net Protocol via the relay hook (same as image editor)
      const result = await uploadFile(file, {
        title: data.title,
        author: data.author,
        categories: data.selectedCategories,
        uploaderFid: userProfile?.fid,
        uploaderUsername: userProfile?.username,
        uploaderMemberId: userProfile?.memberId,
        uploaderEnsSubname: userProfile?.ensSubname,
        uploaderStoredUsername: userProfile?.storedFarcasterUsername,
        coverUrl: finalCoverUrl, // Use the uploaded KV URL for cover
        // Social receipt metadata - stored in discovery entry
        isSocialReceipt: true,
        socialPlatform: data.socialPlatform,
        originalUrl: data.originalUrl,
        socialText: data.socialContent?.text,
        socialAuthor: data.socialContent?.author?.username,
        socialTimestamp: data.socialContent?.timestamp,
      });

      if (result.success) {
        // Store contentKey for activity feed posting
        if (result.contentKey) {
          setLastUploadedContentKey(result.contentKey);
          setShowShareToFeed(true);
          // Server already incremented count via recordServerUpload — just refresh.
          refreshUploadCount();
        }

        // Add to selected stacks
        if (result.contentKey && data.selectedStackIds.length > 0) {
          for (const stackId of data.selectedStackIds) {
            try {
              await fetch("/api/stacks", {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                  stackId,
                  action: "add-item",
                  owner: walletAddress,
                  contentKey: result.contentKey,
                }),
              });
            } catch (e) {
              console.error(`[Receipt] Error adding to stack ${stackId}:`, e);
            }
          }
        }

        // Set upload state to complete - this is a REAL upload now, not just an import
        setUploadState({
          status: "complete",
          fileName: fileName,
          fileSize: file.size,
          totalChunks: progress.totalTransactions || 1,
          completedChunks: progress.completedTransactions || 1,
          currentChunkStatus: "done",
          cdnUrl: result.cdnUrl, // This is now a REAL Net Protocol CDN URL!
        });
        setBookTitle(data.title);
        setAuthorName(data.author);
        setLastUploadedContentType("image");

        // Store social receipt data for sharing
        if (result.contentKey) {
          setLastSocialReceiptData({
            platform: data.socialPlatform,
            author: data.socialContent?.author?.username || 'unknown',
            contentKey: result.contentKey,
          });
        }

        // Add to upload log
        addLogEntry({
          fileName: fileName,
          fileSize: file.size,
          status: "success",
          contentKey: result.contentKey,
          countedAgainstLimit: true,
        });

        onUploadComplete?.();
      } else {
        setUploadState(prev => ({
          ...prev,
          error: result.error || "Failed to archive receipt to Net Protocol",
        }));
        addLogEntry({
          fileName: fileName,
          fileSize: file.size,
          status: "failed",
          error: result.error || "Upload to Net Protocol failed",
          countedAgainstLimit: false,
        });
      }
    } catch (err) {
      console.error("[Receipt] Error:", err);
      const errorMessage = err instanceof Error ? err.message : "Archive failed";
      setUploadState(prev => ({
        ...prev,
        error: errorMessage,
      }));
      addLogEntry({
        fileName: data.title,
        fileSize: 0,
        status: "failed",
        error: errorMessage,
        countedAgainstLimit: false,
      });
    } finally {
      setIsUploadingReceipt(false);
    }
  };

  // Handle batch CDN import
  const handleBatchCdnImport = async (items: Array<{
    cdnUrl: string;
    contentType: ContentType;
    title: string;
    author: string;
    selectedCategories: string[];
    selectedStackIds: string[];
    coverArtUrl?: string;
    coverArtFile?: File;
  }>) => {
    // Check upload limits before allowing batch CDN import
    if (uploadsRemaining < items.length && !hasUploadPass) {
      setUploadState(prev => ({
        ...prev,
        error: `Can only import ${uploadsRemaining} more items today. You're trying to import ${items.length}. Purchase an Upload Pass to continue.`,
      }));
      return;
    }

    setIsBatchCdnImporting(true);

    for (const item of items) {
      try {
        // Handle cover art - either a URL or uploaded file
        let coverUrl = item.coverArtUrl;

        // If a cover file was uploaded, convert to base64 and upload it
        if (item.coverArtFile && !coverUrl) {
          try {
            const dataUrl = await new Promise<string>((resolve, reject) => {
              const reader = new FileReader();
              reader.onload = () => resolve(reader.result as string);
              reader.onerror = reject;
              reader.readAsDataURL(item.coverArtFile!);
            });

            // Upload the cover to get a hosted URL
            const uploadResult = await uploadCover(dataUrl, `batch-${Date.now()}`);
            if (uploadResult.success && uploadResult.url) {
              coverUrl = uploadResult.url;
            }
          } catch (e) {
            console.log("[BatchCDN] Cover upload failed, continuing without cover:", e);
          }
        }

        // Register the CDN link as a discovery entry via API
        const response = await fetch("/api/register-cdn-link", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            cdnUrl: item.cdnUrl,
            contentType: item.contentType,
            title: item.title,
            author: item.author,
            categories: item.selectedCategories,
            coverUrl,
            uploaderAddress: walletAddress,
            uploaderFid: userProfile?.fid,
            uploaderUsername: userProfile?.username,
            uploaderMemberId: userProfile?.memberId,
            uploaderEnsSubname: userProfile?.ensSubname,
            uploaderStoredUsername: userProfile?.storedFarcasterUsername, // Social identity
          }),
        });

        const result = await response.json();

        if (response.ok && result.success && result.contentKey) {
          // Server already incremented count via recordServerUpload — just refresh.
          refreshUploadCount();

          // Add to selected stacks
          for (const stackId of item.selectedStackIds) {
            try {
              await fetch("/api/stacks", {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                  stackId,
                  action: "add-item",
                  owner: walletAddress,
                  contentKey: result.contentKey,
                }),
              });
            } catch (e) {
              console.error(`[BatchCDN] Error adding to stack ${stackId}:`, e);
            }
          }
        }
      } catch (err) {
        console.error("[BatchCDN] Error importing item:", item.title, err);
      }
    }

    setIsBatchCdnImporting(false);
    setShowBatchCdnImport(false);
    onUploadComplete?.();
  };

  // Handle posting to Net Library feed
  const handlePostToFeed = async () => {
    if (!lastUploadedContentKey) return;

    setIsPostingToFeed(true);
    try {
      const success = await postUpload({
        contentKey: lastUploadedContentKey,
        bookTitle: bookTitle || uploadState.fileName,
        bookAuthor: authorName || "Unknown",
        username: userProfile?.username,
        pfpUrl: userProfile?.pfpUrl,
        appBaseUrl: window.location.origin,
      });

      setFeedPostResult(success ? "success" : "error");
      if (success) {
        setShowShareToFeed(false);
      }
    } catch {
      setFeedPostResult("error");
    } finally {
      setIsPostingToFeed(false);
    }
  };

  const coverInputRef = useRef<HTMLInputElement>(null);

  // State for batch upload with retry capability
  const [_batchPremiumPaid, setBatchPremiumPaid] = useState(false);
  const [currentUploadingFileId, setCurrentUploadingFileId] = useState<string | null>(null);

  // Reference for tracking pause state in async loop
  const batchPausedRef = useRef(false);
  const batchCancelledRef = useRef(false); // Track if batch was cancelled (vs resumed)
  const resumeResolverRef = useRef<(() => void) | null>(null);

  // Handle multi-file queue upload with gas checks
  // Each QueuedUpload now has its own stackIds field for per-file stack assignment
  const handleMultiFileUpload = async (files: QueuedUpload[], premiumPaid: boolean = false) => {
    setShowMultiUpload(false);
    setUploadQueue(files);
    setIsProcessingQueue(true);
    setQueueProgress({ current: 0, total: files.length });
    setBatchPremiumPaid(premiumPaid);
    setBatchPaused(false);
    batchPausedRef.current = false;
    batchCancelledRef.current = false;

    // Step 1: Estimate relay cost for first file (x402 USDC) - relay handles batch internally
    try {
      // Use first file to estimate - relay will handle full batch cost automatically
      if (files.length > 0) {
        const costEstimate = await estimateUploadCost(files[0].file);
        const balanceUsdc = costEstimate.balanceInfo?.balanceUsdc || 0;
        const shortfall = costEstimate.balanceInfo?.shortfallUsdc || 0;

        const balanceEth = costEstimate.balanceInfo?.balanceEth || 0;
        setBatchGasEstimate({
          estimatedCostEth: (costEstimate.estimatedCostEth || 0).toFixed(6),
          estimatedCostUsdc: costEstimate.estimatedCostUsdc.toFixed(2),
          balanceEth: balanceEth.toFixed(6),
          balanceUsdc: balanceUsdc.toFixed(2),
          sufficient: costEstimate.canProceed,
          shortfall: shortfall.toFixed(2),
          lowBalance: costEstimate.lowBalance,
        });

        if (!costEstimate.canProceed) {
          // Show warning - relay will prompt for funding automatically
          console.log(`[BatchUpload] Insufficient balance: need ~$${costEstimate.estimatedCostUsdc.toFixed(2)} USDC, have $${balanceUsdc.toFixed(2)} USDC`);
        }
      }
    } catch (e) {
      console.error("[BatchUpload] Cost estimation failed:", e);
    }

    // Step 2: Process files - relay handles funding automatically
    for (let i = 0; i < files.length; i++) {
      const item = files[i];
      setQueueProgress({ current: i + 1, total: files.length });
      setCurrentUploadingFileId(item.id);

      // Check if paused - wait for resume
      if (batchPausedRef.current) {
        await new Promise<void>(resolve => {
          resumeResolverRef.current = resolve;
        });
        batchPausedRef.current = false;
      }

      // x402 relay handles balance checks automatically during upload
      // If funding is needed, it will prompt via progress.status === "needs-funding"

      // Update queue item status
      setUploadQueue(prev => prev.map(q =>
        q.id === item.id ? { ...q, status: "uploading" as const, error: undefined } : q
      ));

      // Upload cover image to get a hosted URL (if it's a base64 data URL)
      let finalCoverUrl = item.coverUrl;
      if (item.coverUrl && coverNeedsUpload(item.coverUrl)) {
        console.log(`[BatchUpload] Uploading cover for "${item.title}"...`);
        const coverResult = await uploadCover(item.coverUrl);
        if (coverResult.success && coverResult.url) {
          console.log(`[BatchUpload] Cover uploaded: ${coverResult.url}`);
          finalCoverUrl = coverResult.url;
        } else {
          console.warn(`[BatchUpload] Cover upload failed for "${item.title}":`, coverResult.error);
          finalCoverUrl = undefined;
        }
      }

      try {
        const result = await uploadFile(item.file, {
          title: item.title || item.file.name,
          author: item.author || "Unknown",
          categories: item.categories,
          coverUrl: finalCoverUrl,
          uploaderFid: userProfile?.fid,
          uploaderUsername: userProfile?.username,
          uploaderMemberId: userProfile?.memberId,
          uploaderEnsSubname: userProfile?.ensSubname,
          uploaderStoredUsername: userProfile?.storedFarcasterUsername, // Social identity
        });

        if (result.success) {
          setUploadQueue(prev => prev.map(q =>
            q.id === item.id
              ? { ...q, status: "complete" as const, cdnUrl: result.cdnUrl, progress: 100 }
              : q
          ));

          // Add to stacks if any were selected for this file
          const fileStackIds = item.stackIds || [];
          if (result.contentKey && fileStackIds.length > 0) {
            console.log(`[BatchUpload] Adding "${item.title}" to ${fileStackIds.length} stack(s)...`);
            for (const stackId of fileStackIds) {
              try {
                await fetch("/api/stacks", {
                  method: "PUT",
                  headers: { "Content-Type": "application/json" },
                  body: JSON.stringify({
                    stackId,
                    action: "add-item",
                    owner: walletAddress,
                    contentKey: result.contentKey,
                  }),
                });
              } catch (e) {
                console.warn(`[BatchUpload] Failed to add to stack ${stackId}:`, e);
              }
            }
          }
        } else {
          // Check if it's an insufficient funds error
          // Check if it's a funding/balance error
          const isFundingError = result.error?.toLowerCase().includes("insufficient") ||
                            result.error?.toLowerCase().includes("fund") ||
                            result.error?.toLowerCase().includes("usdc") ||
                            result.error?.toLowerCase().includes("balance");

          if (isFundingError) {
            // Pause and offer to add funds via relay
            setBatchPaused(true);
            batchPausedRef.current = true;
            setPausedFileId(item.id);

            // Re-estimate cost for THIS file and check balance
            const costEstimate = await estimateUploadCost(item.file);
            const balanceInfo = await getRelayBalance();
            setBatchGasEstimate({
              estimatedCostEth: (costEstimate.estimatedCostEth || 0).toFixed(6),
              estimatedCostUsdc: costEstimate.estimatedCostUsdc.toFixed(2),
              balanceEth: (costEstimate.balanceInfo?.balanceEth || 0).toFixed(6),
              balanceUsdc: balanceInfo?.balanceUsdc.toFixed(2) || "0.00",
              sufficient: false,
              shortfall: costEstimate.balanceInfo?.shortfallUsdc.toFixed(2) || costEstimate.estimatedCostUsdc.toFixed(2),
            });
            setBatchFundingState({ loading: false, error: null }); // Reset funding state when modal opens
            setShowBatchAddFundsModal(true);

            // Keep item as pending for retry, not error
            setUploadQueue(prev => prev.map(q =>
              q.id === item.id
                ? { ...q, status: "pending" as const }
                : q
            ));

            // Wait for user to fund or cancel
            await new Promise<void>(resolve => {
              resumeResolverRef.current = resolve;
            });
            batchPausedRef.current = false;

            // Check if user cancelled - if so, don't retry, just continue to next
            if (batchCancelledRef.current) {
              // Item already marked as error by cancelBatchUpload
              continue;
            }

            // After successful funding, RETRY this item by decrementing i
            // This will cause the loop to process this item again
            i--;
            continue;
          } else {
            setUploadQueue(prev => prev.map(q =>
              q.id === item.id
                ? { ...q, status: "error" as const, error: result.error }
                : q
            ));
          }
        }
      } catch (error) {
        setUploadQueue(prev => prev.map(q =>
          q.id === item.id
            ? { ...q, status: "error" as const, error: error instanceof Error ? error.message : "Upload failed" }
            : q
        ));
      }

      // Small delay between uploads
      if (i < files.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 500));
      }
    }

    setCurrentUploadingFileId(null);
    setPausedFileId(null);
    setIsProcessingQueue(false);
    setBatchPaused(false);

    // Save drafts for any failed uploads (so user can retry with same metadata)
    // Note: Using the current state directly, not inside setter
    const currentQueue = uploadQueue;
    const hasFailures = currentQueue.some(q => q.status === "error" || q.status === "pending");
    console.log("[BATCH COMPLETE] Queue status:", {
      total: currentQueue.length,
      complete: currentQueue.filter(q => q.status === "complete").length,
      errors: currentQueue.filter(q => q.status === "error").length,
      pending: currentQueue.filter(q => q.status === "pending").length,
      hasFailures,
    });
    if (hasFailures) {
      console.log("[BATCH COMPLETE] Saving failed drafts for recovery...");
      saveFailedDrafts(currentQueue);
    }
    // Clear drafts for successful uploads
    currentQueue.filter(q => q.status === "complete").forEach(q => {
      if (q.file) {
        console.log("[BATCH COMPLETE] Clearing draft for successful upload:", q.file.name);
        clearDraftForFile(q.file);
      }
    });

    onUploadComplete?.();
  };

  // Resume batch upload after adding funds
  const resumeBatchUpload = async () => {
    setShowBatchAddFundsModal(false);
    setBatchPaused(false);
    // Note: batchPausedRef.current will be set to false in the loop after promise resolves

    // Refresh relay balance before resuming
    const balanceInfo = await getRelayBalance();
    setBatchGasEstimate(prev => prev ? {
      ...prev,
      balanceUsdc: balanceInfo?.balanceUsdc.toFixed(2) || "0.00",
      // Note: balanceEth would need to be fetched separately if needed
    } : null);

    // Resume the upload loop - the promise awaited in the funding error handler will resolve
    if (resumeResolverRef.current) {
      resumeResolverRef.current();
      resumeResolverRef.current = null;
    }
  };

  // Cancel remaining batch uploads
  const cancelBatchUpload = () => {
    setShowBatchAddFundsModal(false);
    setBatchPaused(false);
    batchPausedRef.current = false;
    batchCancelledRef.current = true; // Signal that batch was cancelled, not resumed

    // Mark all pending files as skipped
    setUploadQueue(prev => prev.map(q =>
      q.status === "pending" ? { ...q, status: "error" as const, error: "Cancelled" } : q
    ));

    // Resume to exit the loop (it will check batchCancelledRef and not retry)
    if (resumeResolverRef.current) {
      resumeResolverRef.current();
      resumeResolverRef.current = null;
    }

    setIsProcessingQueue(false);
  };

  // Retry a single failed file
  const retryFailedFile = async (fileId: string) => {
    const file = uploadQueue.find(f => f.id === fileId);
    if (!file) return;

    setCurrentUploadingFileId(fileId);
    setUploadQueue(prev => prev.map(q =>
      q.id === fileId ? { ...q, status: "uploading" as const, error: undefined } : q
    ));

    try {
      const result = await uploadFile(file.file, {
        title: file.title || file.file.name,
        author: file.author || "Unknown",
        categories: file.categories,
        coverUrl: file.coverUrl,
        uploaderFid: userProfile?.fid,
        uploaderUsername: userProfile?.username,
        uploaderMemberId: userProfile?.memberId,
        uploaderEnsSubname: userProfile?.ensSubname,
        uploaderStoredUsername: userProfile?.storedFarcasterUsername, // Social identity
      });

      if (result.success) {
        setUploadQueue(prev => prev.map(q =>
          q.id === fileId
            ? { ...q, status: "complete" as const, cdnUrl: result.cdnUrl, progress: 100 }
            : q
        ));
      } else {
        setUploadQueue(prev => prev.map(q =>
          q.id === fileId
            ? { ...q, status: "error" as const, error: result.error }
            : q
        ));
      }
    } catch (error) {
      setUploadQueue(prev => prev.map(q =>
        q.id === fileId
          ? { ...q, status: "error" as const, error: error instanceof Error ? error.message : "Retry failed" }
          : q
      ));
    }

    setCurrentUploadingFileId(null);
  };

  // Skip a failed file (remove from queue)
  const skipFailedFile = (fileId: string) => {
    setUploadQueue(prev => prev.filter(q => q.id !== fileId));
  };

  const clearQueue = () => {
    setUploadQueue([]);
    setQueueProgress({ current: 0, total: 0 });
    resetUpload();
  };

  const handleCoverUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
    // DEBUG: Log when cover file input is triggered
    console.log("[UploadTab] handleCoverUpload triggered - cover file picker was opened");
    console.trace("[UploadTab] Stack trace for cover upload trigger:");

    const file = e.target.files?.[0];
    if (file) {
      // Convert to data URL so it persists across sessions (blob URLs expire)
      const reader = new FileReader();
      reader.onloadend = () => {
        const dataUrl = reader.result as string;
        setCoverArtUrl(dataUrl);
        setIsUserSelectedCover(true); // Mark as user-selected to prevent auto-extraction from overwriting
        isUserSelectedCoverRef.current = true; // Also set ref for async race condition
        setShowCoverUpload(false);
      };
      reader.onerror = () => {
        console.error("[UploadTab] Failed to read cover image");
        // Fallback to blob URL (won't persist but will show preview)
        const localUrl = URL.createObjectURL(file);
        setCoverArtUrl(localUrl);
        setIsUserSelectedCover(true);
        isUserSelectedCoverRef.current = true;
        setShowCoverUpload(false);
      };
      reader.readAsDataURL(file);
    }
  };

  return (
    <div className="space-y-4">
      {/* Upload Wallet Balance - Persistent header showing balance */}
      <UploadWalletBalance
        walletAddress={walletAddress}
        refreshTrigger={balanceRefreshTrigger}
        onAddFunds={async () => {
          // Fetch actual balance before opening modal
          const balanceInfo = await getRelayBalance();
          setGasEstimate({
            estimatedCostEth: "0", // No upload cost - just adding funds
            estimatedCostUsdc: "0",
            balanceEth: "0", // Will be populated by checkBalance
            balanceUsdc: balanceInfo?.balanceUsdc.toFixed(2) || "0.00",
            sufficient: balanceInfo?.sufficient || false,
          });
          setIsStandaloneAddFunds(true); // Mark as standalone add funds (from header)
          setShowAddFundsModal(true);
        }}
      />

      {/* Recovery Banner - Show if there's an interrupted upload */}
      {recoveryState && uploadState.status === "idle" && (
        <Card className="bg-yellow-500/10 border-2 border-yellow-500/50">
          <CardContent className="p-4">
            <div className="flex items-start gap-3">
              <WarningIcon size={24} className="text-yellow-400 shrink-0" />
              <div className="flex-1">
                <H4 className="text-yellow-400 font-mono text-sm">Interrupted Upload Detected</H4>
                <P className="text-gray-300 font-mono text-xs mt-1">
                  &quot;{recoveryState.title}&quot;
                </P>
                <Small className="text-gray-400 font-mono block mt-1">
                  {getRecoveryInfo(recoveryState).progress} • {getRecoveryInfo(recoveryState).timeAgo}
                </Small>
                <div className="bg-black/30 rounded-lg p-3 mt-3">
                  <Small className="text-yellow-400/80 font-mono text-[11px] block leading-relaxed">
                    The {recoveryState.completedChunkKeys.length} chunk{recoveryState.completedChunkKeys.length !== 1 ? "s" : ""} already uploaded are stored onchain. To complete this upload, you&apos;ll need to restart with the same file.
                  </Small>
                  <Small className="text-gray-500 font-mono text-[10px] block mt-2">
                    File: {recoveryState.fileName} ({(recoveryState.fileSize / (1024 * 1024)).toFixed(1)} MB)
                  </Small>
                </div>
                <div className="flex gap-2 mt-3">
                  <button
                    onClick={() => {
                      // Pre-fill metadata from recovery state
                      setBookTitle(recoveryState.title);
                      setAuthorName(recoveryState.author);
                      setSelectedCategories(recoveryState.categories);
                      if (recoveryState.coverUrl) {
                        setCoverArtUrl(recoveryState.coverUrl);
                      }
                      // IMPORTANT: Store recovery keys BEFORE clearing so we can resume with same keys
                      if (recoveryState.allChunkKeys && recoveryState.allChunkKeys.length > 0) {
                        setPendingRecovery({
                          completedChunkKeys: recoveryState.completedChunkKeys,
                          allChunkKeys: recoveryState.allChunkKeys,
                          storageKey: recoveryState.storageKey,
                        });
                        console.log(`[Recovery] Stored ${recoveryState.completedChunkKeys.length} completed chunk keys for resume`);
                      }
                      // Clear recovery display state - relay handles recovery via chunk idempotency
                      setRecoveryState(null);
                      // Trigger file picker
                      fileInputRef.current?.click();
                    }}
                    className="flex-1 py-2 rounded-lg bg-[#00ff00]/20 text-[#00ff00] font-mono text-xs hover:bg-[#00ff00]/30 transition-all border border-[#00ff00]/50"
                  >
                    <RefreshIcon size={12} className="inline mr-1" /> Re-upload Same File
                  </button>
                  <button
                    onClick={dismissRecovery}
                    className="py-2 px-3 rounded-lg bg-[#1a1a1a] text-gray-400 font-mono text-xs hover:bg-[#222] hover:text-white transition-all"
                  >
                    Dismiss
                  </button>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* Multi-file upload mode */}
      {showMultiUpload && (
        <MultiFileUpload
          categories={categories}
          stacks={userStacks || []}
          isLoadingStacks={isLoadingStacks}
          onFilesSelected={handleMultiFileUpload}
          onCancel={() => setShowMultiUpload(false)}
          onNavigateToProfile={onNavigateToProfile}
        />
      )}

      {/* Batch CDN import mode */}
      {showBatchCdnImport && (
        <BatchCdnImport
          categories={categories}
          stacks={userStacks || []}
          isLoadingStacks={isLoadingStacks}
          onImport={handleBatchCdnImport}
          onCancel={() => setShowBatchCdnImport(false)}
          isImporting={isBatchCdnImporting}
        />
      )}

      {/* Queue processing view - FIXED FLOATING PROGRESS */}
      {isProcessingQueue && uploadQueue.length > 0 && (
        <div className="space-y-4">
          {/* Fixed floating header for batch upload progress */}
          <div className="fixed top-0 left-0 right-0 z-[9999] bg-black/95 border-b-2 border-[#00ff00]/50 p-3 shadow-lg shadow-[#00ff00]/20">
            <div className="max-w-md mx-auto">
              <div className="flex items-center justify-between mb-2">
                <div className="flex items-center gap-2">
                  <div className="w-3 h-3 rounded-full bg-[#00ff00] animate-pulse" />
                  <span className="text-white font-mono text-sm font-bold flex items-center gap-1">
                    <FolderIcon size={14} /> Batch Upload {queueProgress.current}/{queueProgress.total}
                  </span>
                </div>
                <span className="text-[#00ff00] font-mono text-xs">
                  {uploadQueue.filter(q => q.status === "complete").length} ✓
                  {uploadQueue.filter(q => q.status === "error").length > 0 && (
                    <span className="text-red-400 ml-2">
                      {uploadQueue.filter(q => q.status === "error").length} ✗
                    </span>
                  )}
                </span>
              </div>
              <div className="h-2 bg-[#1a1a1a] rounded-full overflow-hidden">
                <div
                  className="h-full bg-gradient-to-r from-[#00ff00] to-[#00dd00] transition-all duration-500"
                  style={{ width: `${queueProgress.total > 0 ? (queueProgress.current / queueProgress.total) * 100 : 0}%` }}
                />
              </div>
              {/* Current file being uploaded */}
              {currentUploadingFileId && (
                <div className="mt-2 text-center">
                  <Small className="text-gray-400 font-mono text-[10px]">
                    Uploading: {uploadQueue.find(q => q.id === currentUploadingFileId)?.title || "..."}
                  </Small>
                </div>
              )}
            </div>
          </div>

          {/* Spacer for fixed header */}
          <div className="h-20" />

          {/* Main progress card */}
          <Card className="bg-[#00ff00]/5 border-2 border-[#00ff00]/30">
            <CardContent className="p-4">
              <div className="flex items-center justify-between mb-3">
                <H4 className="text-[#00ff00] font-mono flex items-center gap-2"><FolderIcon size={18} /> Batch Upload Progress</H4>
                <Small className="text-white font-mono font-bold">
                  {queueProgress.total > 0 ? Math.round((queueProgress.current / queueProgress.total) * 100) : 0}%
                </Small>
              </div>
              <div className="h-3 bg-[#1a1a1a] rounded-full overflow-hidden mb-3">
                <div
                  className="h-full bg-gradient-to-r from-[#00ff00] to-[#00dd00] transition-all duration-500"
                  style={{ width: `${queueProgress.total > 0 ? (queueProgress.current / queueProgress.total) * 100 : 0}%` }}
                />
              </div>
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">
                  {uploadQueue.filter(q => q.status === "complete").length} complete
                </Small>
                <Small className="text-gray-400 font-mono">
                  {uploadQueue.filter(q => q.status === "pending").length} pending
                </Small>
                {uploadQueue.filter(q => q.status === "error").length > 0 && (
                  <Small className="text-red-400 font-mono">
                    {uploadQueue.filter(q => q.status === "error").length} failed
                  </Small>
                )}
              </div>
            </CardContent>
          </Card>

          {/* File list with status */}
          <div className="space-y-2 max-h-64 overflow-y-auto">
            {uploadQueue.map((item, idx) => (
              <Card
                key={item.id}
                className={`border transition-all ${
                  item.status === "complete" ? "border-green-500/30 bg-green-500/5" :
                  item.status === "error" ? "border-red-500/30 bg-red-500/5" :
                  item.status === "uploading" ? "border-yellow-500/30 bg-yellow-500/5 animate-pulse" :
                  "border-[#1a1a1a] bg-[#0a0a0a]"
                }`}
              >
                <CardContent className="p-3">
                  <div className="flex items-center gap-3">
                    <div className="w-8 h-8 rounded-full flex items-center justify-center bg-black/30 shrink-0">
                      {item.status === "complete" ? <CheckCircleIcon size={18} className="text-green-400" /> :
                       item.status === "error" ? <XCircleIcon size={18} className="text-red-400" /> :
                       item.status === "uploading" ? <LoadingIcon size={18} className="text-[#00ff00] animate-spin" /> :
                       <span className="text-lg">{idx + 1}</span>}
                    </div>
                    <div className="flex-1 min-w-0">
                      <P className="text-white font-mono text-xs truncate">{item.title}</P>
                      <Small className="text-gray-500 font-mono text-[10px]">
                        {item.file.size >= 1024 * 1024
                          ? `${(item.file.size / (1024 * 1024)).toFixed(1)} MB`
                          : `${(item.file.size / 1024).toFixed(0)} KB`}
                      </Small>
                      {item.error && (
                        <Small className="text-red-400 font-mono text-[10px] block mt-1">{item.error}</Small>
                      )}
                    </div>
                    {/* Show progress indicator for uploading item */}
                    {item.status === "uploading" && (
                      <div className="w-4 h-4 border-2 border-yellow-400 border-t-transparent rounded-full animate-spin" />
                    )}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>

          {/* Batch info */}
          <div className="text-center">
            <Small className="text-gray-500 font-mono text-[10px]">
              Files are uploaded sequentially • Stay on this screen until complete
            </Small>
          </div>
        </div>
      )}

      {/* Queue complete view with error handling */}
      {!isProcessingQueue && uploadQueue.length > 0 && (
        <div className="space-y-4">
          {/* Success/Mixed result header */}
          <div className="text-center py-4">
            {(() => {
              const completedCount = uploadQueue.filter(q => q.status === "complete").length;
              const errorCount = uploadQueue.filter(q => q.status === "error").length;
              const pendingCount = uploadQueue.filter(q => q.status === "pending").length;
              const allCompleted = completedCount === uploadQueue.length;
              const noneCompleted = completedCount === 0;
              const _hasErrors = errorCount > 0 || pendingCount > 0;

              return (
                <>
                  <div className="text-5xl mb-3 flex justify-center">
                    {allCompleted ? <PartyIcon size={48} className="text-[#00ff00]" /> : noneCompleted ? <XCircleIcon size={48} className="text-red-400" /> : <WarningIcon size={48} className="text-yellow-400" />}
                  </div>
                  <H4 className={`font-mono ${allCompleted ? "text-[#00ff00]" : noneCompleted ? "text-red-400" : "text-yellow-400"}`}>
                    {allCompleted
                      ? "Batch Upload Complete!"
                      : noneCompleted
                        ? "Upload Failed"
                        : "Batch Upload Finished with Errors"}
                  </H4>
                </>
              );
            })()}
            <P className="text-gray-400 font-mono mt-2">
              {uploadQueue.filter(q => q.status === "complete").length} of {uploadQueue.length} files uploaded successfully
            </P>
          </div>

          {/* Summary card */}
          <Card className="bg-[#00ff00]/5 border border-[#00ff00]/30">
            <CardContent className="p-3">
              <div className="flex justify-around text-center">
                <div>
                  <div className="text-2xl font-bold text-green-400 font-mono">
                    {uploadQueue.filter(q => q.status === "complete").length}
                  </div>
                  <Small className="text-gray-400 font-mono">Success</Small>
                </div>
                {uploadQueue.filter(q => q.status === "error").length > 0 && (
                  <div>
                    <div className="text-2xl font-bold text-red-400 font-mono">
                      {uploadQueue.filter(q => q.status === "error").length}
                    </div>
                    <Small className="text-gray-400 font-mono">Failed</Small>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>

          {/* Failed files with retry/skip options */}
          {uploadQueue.filter(q => q.status === "error").length > 0 && (
            <div className="space-y-2">
              <Small className="text-red-400 font-mono font-bold block px-1">Failed uploads:</Small>
              {uploadQueue.filter(q => q.status === "error").map((item) => {
                // Determine error icon and hint based on error message
                const errorLower = (item.error || "").toLowerCase();
                let ErrorIconComponent: React.ComponentType<{ size?: number; className?: string }> = XCircleIcon;
                let errorIconColor = "text-red-400";
                let errorHint = "";
                let canRetry = true;

                if (errorLower.includes("cancelled") || errorLower.includes("user")) {
                  ErrorIconComponent = BanIcon;
                  errorIconColor = "text-gray-400";
                  errorHint = "You cancelled this - retry when ready";
                } else if (errorLower.includes("insufficient") || errorLower.includes("usdc") || errorLower.includes("fund") || errorLower.includes("balance")) {
                  ErrorIconComponent = DollarBillIcon;
                  errorIconColor = "text-yellow-400";
                  errorHint = "Fund your Upload Wallet with USDC";
                } else if (errorLower.includes("too large") || errorLower.includes("size")) {
                  ErrorIconComponent = PackageIcon;
                  errorIconColor = "text-orange-400";
                  errorHint = "File exceeds size limit";
                  canRetry = false;
                } else if (errorLower.includes("network") || errorLower.includes("connection")) {
                  ErrorIconComponent = SignalIcon;
                  errorIconColor = "text-blue-400";
                  errorHint = "Check your internet connection";
                } else if (errorLower.includes("wallet signature timed out") || errorLower.includes("farcaster wallet")) {
                  ErrorIconComponent = PhoneIcon;
                  errorIconColor = "text-purple-400";
                  errorHint = "Farcaster wallet had issues - close the app and try again";
                } else if (errorLower.includes("timeout") || errorLower.includes("congested")) {
                  ErrorIconComponent = ClockIcon;
                  errorIconColor = "text-orange-400";
                  errorHint = "Try again in a few minutes";
                } else if (errorLower.includes("rate limit") || errorLower.includes("too many")) {
                  ErrorIconComponent = TrafficLightIcon;
                  errorIconColor = "text-yellow-400";
                  errorHint = "Wait a moment before retrying";
                } else if (errorLower.includes("reverted") || errorLower.includes("contract")) {
                  ErrorIconComponent = WarningIcon;
                  errorIconColor = "text-yellow-400";
                  errorHint = "Contract rejected the transaction";
                } else if (errorLower.includes("nonce") || errorLower.includes("pending")) {
                  ErrorIconComponent = RefreshIcon;
                  errorIconColor = "text-blue-400";
                  errorHint = "Wait for pending transaction to complete";
                } else if (errorLower.includes("invalid") || errorLower.includes("corrupted")) {
                  ErrorIconComponent = DocumentIcon;
                  errorIconColor = "text-red-400";
                  errorHint = "File may be corrupted";
                  canRetry = false;
                }

                return (
                  <Card key={item.id} className="bg-red-500/5 border border-red-500/30">
                    <CardContent className="p-3">
                      <div className="flex items-start gap-3">
                        <ErrorIconComponent size={18} className={`shrink-0 ${errorIconColor}`} />
                        <div className="flex-1 min-w-0">
                          <P className="text-white font-mono text-xs truncate">{item.title}</P>
                          <Small className="text-red-400 font-mono text-[10px]">{item.error}</Small>
                          {errorHint && (
                            <Small className="text-yellow-400/70 font-mono text-[9px] block mt-1 flex items-center gap-1">
                              <LightbulbIcon size={10} className="shrink-0" /> {errorHint}
                            </Small>
                          )}
                        </div>
                      </div>
                      <div className="flex gap-2 mt-3">
                        {canRetry ? (
                          <button
                            onClick={() => retryFailedFile(item.id)}
                            disabled={currentUploadingFileId === item.id}
                            className="flex-1 py-2 rounded-lg bg-yellow-500/20 text-yellow-400 font-mono text-xs hover:bg-yellow-500/30 disabled:opacity-50 transition-all"
                          >
                            {currentUploadingFileId === item.id ? "Retrying..." : <><RefreshIcon size={12} className="inline mr-1" /> Retry</>}
                          </button>
                        ) : (
                          <button
                            disabled
                            className="flex-1 py-2 rounded-lg bg-gray-500/20 text-gray-500 font-mono text-xs cursor-not-allowed"
                          >
                            Cannot Retry
                          </button>
                        )}
                        <button
                          onClick={() => skipFailedFile(item.id)}
                          className="flex-1 py-2 rounded-lg bg-red-500/20 text-red-400 font-mono text-xs hover:bg-red-500/30 transition-all"
                        >
                          <CloseIcon size={12} className="inline mr-1" /> Remove
                        </button>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          )}

          {/* Completed files list with CDN links */}
          {uploadQueue.filter(q => q.status === "complete").length > 0 && (
            <div className="space-y-3">
              <div className="flex items-center justify-between">
                <span className="text-green-400 font-mono text-xs flex items-center gap-2">
                  <CheckCircleIcon size={14} />
                  {uploadQueue.filter(q => q.status === "complete").length} file{uploadQueue.filter(q => q.status === "complete").length > 1 ? "s" : ""} uploaded successfully
                </span>
                {uploadQueue.filter(q => q.status === "complete" && q.cdnUrl).length > 1 && (
                  <button
                    onClick={() => {
                      const cdnUrls = uploadQueue
                        .filter(q => q.status === "complete" && q.cdnUrl)
                        .map(q => q.cdnUrl)
                        .join("\n");
                      navigator.clipboard.writeText(cdnUrls);
                      // Show brief toast-like feedback
                      const btn = document.getElementById("copy-all-cdns-btn");
                      if (btn) {
                        btn.textContent = "Copied!";
                        setTimeout(() => { btn.textContent = "Copy All CDNs"; }, 1500);
                      }
                    }}
                    id="copy-all-cdns-btn"
                    className="px-2 py-1 rounded bg-[#00ff00]/10 text-[#00ff00] text-[10px] font-mono hover:bg-[#00ff00]/20 transition-all flex items-center gap-1"
                  >
                    <ClipboardIcon size={10} /> Copy All CDNs
                  </button>
                )}
              </div>
              <div className="space-y-2 max-h-48 overflow-y-auto">
                {uploadQueue.filter(q => q.status === "complete").map((item) => (
                  <div key={item.id} className="p-2 bg-green-500/5 border border-green-500/20 rounded-lg">
                    <div className="flex items-center gap-2 mb-1">
                      <span className="text-green-400">✓</span>
                      <span className="text-gray-200 font-mono text-xs truncate flex-1">{item.title}</span>
                    </div>
                    {item.cdnUrl && (
                      <div className="flex items-center gap-2 ml-5">
                        <input
                          type="text"
                          readOnly
                          value={item.cdnUrl}
                          className="flex-1 px-2 py-1 rounded bg-black/50 border border-green-500/20 text-[10px] font-mono text-gray-400 truncate"
                          onClick={(e) => (e.target as HTMLInputElement).select()}
                        />
                        <button
                          onClick={() => {
                            navigator.clipboard.writeText(item.cdnUrl || "");
                            const btn = document.getElementById(`copy-cdn-${item.id}`);
                            if (btn) {
                              btn.classList.add("text-green-400");
                              setTimeout(() => { btn.classList.remove("text-green-400"); }, 1000);
                            }
                          }}
                          id={`copy-cdn-${item.id}`}
                          className="p-1 rounded bg-[#00ff00]/10 text-gray-400 hover:text-[#00ff00] transition-all"
                          title="Copy CDN link"
                        >
                          <ClipboardIcon size={12} />
                        </button>
                      </div>
                    )}
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* Action button */}
          <Button
            onClick={clearQueue}
            className="w-full bg-[#00ff00] text-black hover:bg-[#00dd00] font-mono mt-4"
          >
            {uploadQueue.filter(q => q.status === "error").length > 0
              ? "Done"
              : "Upload More"}
          </Button>
        </div>
      )}

      {uploadState.status === "idle" && !showMultiUpload && !showBatchCdnImport && uploadQueue.length === 0 && (
        <>
          {/* File Rejected Error Banner - Show if file was rejected during selection */}
          {uploadState.error && (
            <Card className="bg-red-500/10 border-2 border-red-500/50 mb-4">
              <CardContent className="p-3">
                <div className="flex items-start gap-2">
                  <XCircleIcon size={18} className="text-red-400 shrink-0 mt-0.5" />
                  <div>
                    <P className="text-red-400 font-mono text-sm font-bold">File Not Accepted</P>
                    <Small className="text-gray-300 font-mono block mt-1">{uploadState.error}</Small>
                    <button
                      type="button"
                      onClick={() => setUploadState(prev => ({ ...prev, error: undefined }))}
                      className="text-gray-500 font-mono text-[10px] mt-2 hover:text-gray-300"
                    >
                      Dismiss
                    </button>
                  </div>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Upload Mode Tabs */}
          <div className="flex border border-[#00ff00] rounded-lg overflow-hidden mb-4">
            <button
              onClick={() => setUploadMode("file")}
              className={`flex-1 py-2 font-mono text-xs transition-all ${
                uploadMode === "file"
                  ? "bg-[#00ff00]/20 text-[#00ff00] border-b-2 border-[#00ff00]"
                  : "text-gray-400 hover:text-white hover:bg-[#1a1a1a]"
              }`}
            >
              <DocumentIcon size={12} className="inline mr-1" /> File
            </button>
            <button
              onClick={() => setUploadMode("create")}
              className={`flex-1 py-2 font-mono text-xs transition-all border-l border-[#00ff00] ${
                uploadMode === "create"
                  ? "bg-[#00ff00]/20 text-[#00ff00] border-b-2 border-[#00ff00]"
                  : "text-gray-400 hover:text-white hover:bg-[#1a1a1a]"
              }`}
            >
              <PartyIcon size={12} className="inline mr-1" /> Create
            </button>
            <button
              onClick={() => setUploadMode("link")}
              className={`flex-1 py-2 font-mono text-xs transition-all border-l border-[#00ff00] ${
                uploadMode === "link"
                  ? "bg-[#00ff00]/20 text-[#00ff00] border-b-2 border-[#00ff00]"
                  : "text-gray-400 hover:text-white hover:bg-[#1a1a1a]"
              }`}
            >
              <LinkIcon size={12} className="inline mr-1" /> CDN
            </button>
            <button
              onClick={() => setUploadMode("receipt")}
              className={`flex-1 py-2 font-mono text-xs transition-all border-l border-[#00ff00] ${
                uploadMode === "receipt"
                  ? "bg-[#00ff00]/20 text-[#00ff00] border-b-2 border-[#00ff00]"
                  : "text-gray-400 hover:text-white hover:bg-[#1a1a1a]"
              }`}
            >
              <ReceiptIcon size={12} className="inline mr-1" /> Social
            </button>
          </div>

          {/* Create Mode - Write Something or Create Something */}
          {uploadMode === "create" && (
            <div className="space-y-3">
              {/* LIVE ERROR BANNER - Base App debugging (shows after failed upload) */}
              {progress.error && !isUploadingText && !isUploadingImage && (
                <Card className="bg-red-900/30 border-2 border-red-500/50">
                  <CardContent className="p-3">
                    <div className="flex items-start gap-2">
                      <XCircleIcon size={24} className="text-red-400 shrink-0" />
                      <div className="flex-1 min-w-0">
                        <H4 className="text-red-400 font-mono text-sm">Upload Failed</H4>
                        <Small className="text-red-300 font-mono text-[11px] break-words block mt-1">
                          {progress.error}
                        </Small>
                        {progress.currentStep && (
                          <Small className="text-gray-400 font-mono text-[10px] block mt-1">
                            Last step: {progress.currentStep}
                          </Small>
                        )}
                      </div>
                    </div>
                  </CardContent>
                </Card>
              )}
              {/* Write Something - Collapsible */}
              <Card className={`bg-[#0a0a0a] border-2 transition-colors ${createSection === "write" ? "border-[#00ff00]/50" : "border-[#00ff00]/20"}`}>
                <button
                  onClick={() => setCreateSection(createSection === "write" ? null : "write")}
                  className="w-full p-4 flex items-center justify-between text-left"
                >
                  <div className="flex items-center gap-3">
                    <PencilIcon size={24} className="text-[#00ff00]" />
                    <div>
                      <H4 className="text-[#00ff00] font-mono">Write Something</H4>
                      <Small className="text-gray-500 font-mono">Text editor with rich formatting</Small>
                    </div>
                  </div>
                  <span className={`text-gray-400 transition-transform text-xl ${createSection === "write" ? "rotate-90" : ""}`}>
                    ▸
                  </span>
                </button>
                {createSection === "write" && (
                  <CardContent className="p-4 pt-0 border-t border-[#00ff00]/20">
                    <TextEditorUpload
                      categories={categories}
                      stacks={userStacks || []}
                      isLoadingStacks={isLoadingStacks}
                      onUpload={handleTextEditorUpload}
                      isUploading={isUploadingText}
                    />
                  </CardContent>
                )}
              </Card>

              {/* Create Something - Collapsible */}
              <Card className={`bg-[#0a0a0a] border-2 transition-colors ${createSection === "draw" ? "border-[#00ff00]/50" : "border-[#00ff00]/20"}`}>
                <button
                  onClick={() => setCreateSection(createSection === "draw" ? null : "draw")}
                  className="w-full p-4 flex items-center justify-between text-left"
                >
                  <div className="flex items-center gap-3">
                    <PaletteIcon size={24} className="text-[#00ff00]" />
                    <div>
                      <H4 className="text-[#00ff00] font-mono">Create Something</H4>
                      <Small className="text-gray-500 font-mono">Draw, make memes, add text & emojis</Small>
                    </div>
                  </div>
                  <span className={`text-gray-400 transition-transform text-xl ${createSection === "draw" ? "rotate-90" : ""}`}>
                    ▸
                  </span>
                </button>
                {createSection === "draw" && (
                  <CardContent className="p-4 pt-0 border-t border-[#00ff00]/20">
                    <CreateImageUpload
                      categories={categories}
                      stacks={userStacks || []}
                      isLoadingStacks={isLoadingStacks}
                      onUpload={handleCreatedImageUpload}
                      isUploading={isUploadingImage}
                      autoOpenEditor={true}
                      onAutoOpenCancel={() => setCreateSection(null)}
                    />
                  </CardContent>
                )}
              </Card>
            </div>
          )}

          {/* CDN Link Mode - Import existing content */}
          {uploadMode === "link" && (
            <>
              {/* Batch import button for CDN links */}
              <div className="flex justify-end mb-2">
                <button
                  onClick={() => setShowBatchCdnImport(true)}
                  className="text-[#00ff00]/70 hover:text-[#00ff00] font-mono text-xs px-2 py-1 border border-[#00ff00]/30 rounded hover:border-[#00ff00] transition-all"
                >
                  <FolderIcon size={12} className="inline mr-1" /> Batch Import
                </button>
              </div>
              <CdnLinkUpload
                categories={categories}
                stacks={userStacks || []}
                isLoadingStacks={isLoadingStacks}
                onUpload={handleCdnLinkUpload}
                isUploading={isUploadingLink}
              />
            </>
          )}

          {/* Receipt Mode - Social Post Archive */}
          {uploadMode === "receipt" && (
            <SocialReceiptUpload
              categories={categories}
              stacks={userStacks || []}
              isLoadingStacks={isLoadingStacks}
              onUpload={handleReceiptUpload}
              isUploading={isUploadingReceipt}
            />
          )}

          {/* File Upload Mode (default) */}
          {uploadMode === "file" && (
            <>
              {/* Batch upload button for files */}
              <div className="flex justify-end mb-2">
                <button
                  onClick={() => setShowMultiUpload(true)}
                  className="text-[#00ff00]/70 hover:text-[#00ff00] font-mono text-xs px-2 py-1 border border-[#00ff00]/30 rounded hover:border-[#00ff00] transition-all"
                >
                  <FolderIcon size={12} className="inline mr-1" /> Batch Upload
                </button>
              </div>
              {/* Hidden file input - positioned off-screen to prevent accidental touch on mobile */}
              <input
                ref={fileInputRef}
                type="file"
                accept=".pdf,.txt,.epub,.docx,.doc,.xlsx,.xls,.pptx,.ppt,.rtf,image/*,audio/*,video/*"
                onChange={handleFileInputChange}
                className="sr-only"
                style={{ position: 'absolute', left: '-9999px', top: '-9999px' }}
                tabIndex={-1}
                aria-hidden="true"
              />

              <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
                <CardContent className="p-2 space-y-4">
                  {/* Drag & Drop */}
                  <div
                    onDragOver={handleDragOver}
                    onDragLeave={handleDragLeave}
                    onDrop={handleDrop}
                    onClick={() => !isCheckingDuplicate && fileInputRef.current?.click()}
                    className={`border-2 border-dashed rounded-lg p-4 cursor-pointer transition-all flex flex-col items-center justify-center ${
                      isCheckingDuplicate
                        ? "border-yellow-500/50 bg-yellow-500/10"
                        : isDragging
                        ? "border-[#00ff00] bg-[#00ff00]/20"
                        : "border-[#00ff00]/30 bg-black hover:border-[#00ff00] hover:bg-[#00ff00]/5"
                    }`}
                  >
                    {epubConversion && epubConversion.stage !== "complete" ? (
                      <>
                        <div className="w-8 h-8 border-2 border-purple-400 border-t-transparent rounded-full animate-spin mb-2" />
                        <P className="text-purple-400 font-mono font-medium text-center text-sm">
                          Converting EPUB to PDF...
                        </P>
                        <Small className="text-purple-400/70 font-mono text-center text-[10px]">{epubConversion.message}</Small>
                        <div className="w-full max-w-[200px] mt-2 h-1.5 bg-black rounded-full overflow-hidden border border-purple-400/30">
                          <div
                            className="h-full bg-purple-500 transition-all duration-300"
                            style={{ width: `${epubConversion.percent}%` }}
                          />
                        </div>
                      </>
                    ) : isCheckingDuplicate ? (
                      <>
                        <div className="w-8 h-8 border-2 border-yellow-400 border-t-transparent rounded-full animate-spin mb-2" />
                        <P className="text-yellow-400 font-mono font-medium text-center text-sm">
                          Processing file...
                        </P>
                        <Small className="text-yellow-400/70 font-mono text-center text-[10px]">Checking eligibility & extracting cover</Small>
                      </>
                    ) : (
                      <>
                        <DocumentIcon size={32} className="text-[#00ff00] mb-1" />
                        <P className="text-[#00ff00] font-mono font-medium text-center text-sm">
                          {isDragging ? "Drop your file here!" : "Drag & Drop"}
                        </P>
                        <Small className="text-[#00ff00]/50 font-mono text-center text-[10px]">or tap to browse • PDF, Images, Audio, Video, Text</Small>
                      </>
                    )}
                  </div>

              <div>
                <div className="flex items-center justify-between mb-1">
                  <Small className="text-[#00ff00] font-mono">Title</Small>
                  <Small className={`font-mono text-[10px] ${bookTitle.length > 256 ? 'text-red-400' : bookTitle.length > 200 ? 'text-yellow-400' : 'text-gray-500'}`}>
                    {bookTitle.length}/256
                  </Small>
                </div>
                <input
                  type="text"
                  value={bookTitle}
                  onChange={(e) => setBookTitle(e.target.value.slice(0, 256))}
                  maxLength={256}
                  placeholder="e.g., The Great Gatsby"
                  className="w-full px-3 py-2 rounded-md bg-black border border-[#00ff00]/30 text-white font-mono placeholder:text-gray-500 focus:border-[#00ff00] focus:ring-1 focus:ring-[#00ff00] focus:outline-none"
                />
              </div>
              <div>
                <Small className="text-[#00ff00] font-mono mb-1 block">Author</Small>
                <input
                  type="text"
                  value={authorName}
                  onChange={(e) => setAuthorName(e.target.value)}
                  placeholder="e.g., F. Scott Fitzgerald"
                  className="w-full px-3 py-2 rounded-md bg-black border border-[#00ff00]/30 text-white font-mono placeholder:text-gray-500 focus:border-[#00ff00] focus:ring-1 focus:ring-[#00ff00] focus:outline-none"
                />
              </div>
              {/* Optional metadata fields - collapsible */}
              <details className="group">
                <summary className="flex items-center gap-2 cursor-pointer text-[#00ff00]/70 hover:text-[#00ff00] font-mono text-xs list-none">
                  <span className="transition-transform group-open:rotate-90">▶</span>
                  Additional Details (optional)
                </summary>
                <div className="mt-3 space-y-3 pl-4 border-l-2 border-[#00ff00]/20">
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <Small className="text-[#00ff00]/70 font-mono mb-1 block text-[11px]">Publication Year</Small>
                      <input
                        type="number"
                        value={publicationYear}
                        onChange={(e) => setPublicationYear(e.target.value)}
                        placeholder="e.g., 1925"
                        min="1000"
                        max={new Date().getFullYear()}
                        className="w-full px-3 py-2 rounded-md bg-black border border-[#00ff00]/20 text-white font-mono placeholder:text-gray-600 focus:border-[#00ff00] focus:ring-1 focus:ring-[#00ff00] focus:outline-none text-sm"
                      />
                    </div>
                    <div>
                      <Small className="text-[#00ff00]/70 font-mono mb-1 block text-[11px]">Publisher</Small>
                      <input
                        type="text"
                        value={publisher}
                        onChange={(e) => setPublisher(e.target.value)}
                        placeholder="e.g., Scribner"
                        className="w-full px-3 py-2 rounded-md bg-black border border-[#00ff00]/20 text-white font-mono placeholder:text-gray-600 focus:border-[#00ff00] focus:ring-1 focus:ring-[#00ff00] focus:outline-none text-sm"
                      />
                    </div>
                  </div>
                  <div>
                    <Small className="text-[#00ff00]/70 font-mono mb-1 block text-[11px]">ISBN / DOI</Small>
                    <input
                      type="text"
                      value={isbn}
                      onChange={(e) => setIsbn(e.target.value)}
                      placeholder="e.g., 978-0743273565 or 10.1000/xyz123"
                      className="w-full px-3 py-2 rounded-md bg-black border border-[#00ff00]/20 text-white font-mono placeholder:text-gray-600 focus:border-[#00ff00] focus:ring-1 focus:ring-[#00ff00] focus:outline-none text-sm"
                    />
                  </div>
                </div>
              </details>
              <div>
                <div className="flex items-center justify-between mb-1">
                  <Small className="text-[#00ff00] font-mono">Category</Small>
                  <Small className="text-gray-500 font-mono text-[10px]">
                    {selectedCategories.length}/3 selected
                  </Small>
                </div>
                <CategoryDropdown
                  categories={categories}
                  selectedCategories={selectedCategories}
                  onToggle={toggleCategory}
                  maxSelections={3}
                />
              </div>
              {/* Add to Stack (optional) */}
              <div>
                <div className="flex items-center justify-between mb-1">
                  <Small className="text-[#00ff00] font-mono">Add to Stack (optional)</Small>
                  {selectedStackIds.length > 0 && (
                    <Small className="text-purple-400 font-mono text-[10px]">
                      {selectedStackIds.length} selected
                    </Small>
                  )}
                </div>
                <StackSelectionDropdown
                  stacks={userStacks}
                  selectedStackIds={selectedStackIds}
                  onToggle={toggleStackSelection}
                  isLoading={isLoadingStacks}
                />
                <Small className="text-gray-500 font-mono text-[10px] mt-1 block">
                  Automatically add this item to your stacks
                </Small>
              </div>
              {/* Cover Art Upload */}
              <div>
                <Small className="text-[#00ff00] font-mono mb-1 block">Cover Art (optional)</Small>
                {isExtractingCover ? (
                  <div className="flex items-center gap-3 p-3 bg-[#00ff00]/5 rounded-lg border border-[#00ff00]/20">
                    <div className="w-8 h-8 rounded bg-[#00ff00]/20 flex items-center justify-center animate-pulse">
                      <DocumentIcon size={16} className="text-[#00ff00]" />
                    </div>
                    <Small className="text-[#00ff00] font-mono">Extracting cover from PDF...</Small>
                  </div>
                ) : coverArtUrl ? (
                  <div className="flex items-center gap-3">
                    <div className="w-16 h-20 rounded overflow-hidden border border-[#00ff00]/30">
                      <img src={coverArtUrl} alt="Cover" className="w-full h-full object-cover" />
                    </div>
                    <div className="flex-1">
                      <Small className="text-[#00ff00] font-mono flex items-center gap-1"><CheckIcon size={12} /> Cover ready!</Small>
                      <Small className="text-gray-500 font-mono text-[10px] block">Auto-extracted from PDF</Small>
                      <div className="flex items-center gap-4 mt-2">
                        <button
                          type="button"
                          onClick={(e) => {
                            console.log("[UploadTab] Change cover button clicked");
                            e.stopPropagation();
                            coverInputRef.current?.click();
                          }}
                          className="text-xs text-[#00ff00] font-mono hover:text-[#00ff00]/80 underline underline-offset-2 cursor-pointer active:opacity-70 py-1 px-1 -mx-1 min-h-[32px] flex items-center"
                        >
                          Change
                        </button>
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            setCoverArtUrl(null);
                            setIsUserSelectedCover(false);
                            isUserSelectedCoverRef.current = false;
                          }}
                          className="text-xs text-red-400 font-mono hover:text-red-300 underline underline-offset-2 cursor-pointer active:opacity-70 py-1 px-1 -mx-1 min-h-[32px] flex items-center"
                        >
                          Remove
                        </button>
                      </div>
                    </div>
                  </div>
                ) : (
                  <div className="space-y-2">
                    <button
                      type="button"
                      onClick={() => setShowCoverUpload(true)}
                      className="w-full py-3 min-h-[44px] border-2 border-dashed border-[#00ff00]/30 rounded-lg text-[#00ff00]/70 font-mono text-sm hover:border-[#00ff00] hover:text-[#00ff00] hover:bg-[#00ff00]/5 transition-all flex items-center justify-center gap-2"
                    >
                      <ImageIcon size={16} /> Upload cover (optional)
                    </button>
                    <input
                      type="url"
                      inputMode="url"
                      placeholder="Or paste image URL..."
                      className="w-full px-3 py-2 min-h-[44px] bg-black/50 border border-[#00ff00]/20 rounded-lg text-white font-mono text-sm placeholder:text-gray-600 focus:border-[#00ff00] focus:outline-none"
                      onKeyDown={(e) => {
                        if (e.key === 'Enter') {
                          const url = (e.target as HTMLInputElement).value.trim();
                          if (url && (url.startsWith('http://') || url.startsWith('https://'))) {
                            setCoverArtUrl(url);
                            setIsUserSelectedCover(true);
                            isUserSelectedCoverRef.current = true;
                          }
                        }
                      }}
                      onBlur={(e) => {
                        const url = e.target.value.trim();
                        if (url && (url.startsWith('http://') || url.startsWith('https://'))) {
                          setCoverArtUrl(url);
                          setIsUserSelectedCover(true);
                          isUserSelectedCoverRef.current = true;
                        }
                      }}
                    />
                  </div>
                )}
                <Small className="text-[#00ff00]/50 font-mono text-[10px] mt-1 block">
                  PDF covers auto-extracted • Or upload/paste URL
                </Small>
              </div>

              {/* Upload Button */}
              <Button
                onClick={() => fileInputRef.current?.click()}
                className="w-full bg-[#00ff00] text-black hover:bg-[#00dd00] font-mono h-12 mt-4"
              >
                UPLOAD to Net Library
              </Button>
            </CardContent>
          </Card>

          {/* Upload Limits Info Card - Members Only */}
          {!isUploadLimitsLoading && isMember && (
            <Card className={`border mt-3 ${
              isInWarmupPeriod && uploadsRemaining === 0 && !hasUploadPass
                ? "bg-red-500/5 border-red-500/30"
                : isInWarmupPeriod
                ? "bg-yellow-500/5 border-yellow-500/20"
                : "bg-[#00ff00]/5 border-[#00ff00]/20"
            }`}>
              <CardContent className="p-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <span className="text-lg">
                      {isInWarmupPeriod && uploadsRemaining === 0 && !hasUploadPass
                        ? <BanIcon size={18} className="text-red-400" />
                        : isInWarmupPeriod
                        ? <SeedlingIcon size={18} className="text-yellow-400" />
                        : <UploadIcon size={18} className="text-[#00ff00]" />}
                    </span>
                    <div>
                      <Small className={`font-mono font-bold block ${
                        isInWarmupPeriod && uploadsRemaining === 0 && !hasUploadPass
                          ? "text-red-400"
                          : isInWarmupPeriod
                          ? "text-yellow-400"
                          : "text-[#00ff00]"
                      }`}>
                        {uploadsRemaining} uploads remaining
                        <span className="text-gray-500 font-normal text-[9px] ml-1">
                          (resets in {(() => {
                            const now = new Date();
                            const midnight = new Date(now);
                            midnight.setUTCHours(24, 0, 0, 0);
                            const hoursLeft = Math.ceil((midnight.getTime() - now.getTime()) / (1000 * 60 * 60));
                            return `${hoursLeft}h`;
                          })()})
                        </span>
                      </Small>
                      {isInWarmupPeriod ? (
                        uploadsRemaining === 0 && !hasUploadPass ? (
                          <Small className="text-red-400/70 font-mono text-[9px]">
                            Daily limit reached during warm-up period
                          </Small>
                        ) : (
                          <Small className="text-yellow-400/70 font-mono text-[9px]">
                            New member warm-up • {daysRemainingInWarmup} day{daysRemainingInWarmup !== 1 ? "s" : ""} until full access
                          </Small>
                        )
                      ) : (
                        <Small className="text-[#00ff00]/70 font-mono text-[9px]">
                          ✓ Full access unlocked
                        </Small>
                      )}
                    </div>
                  </div>
                  <div className="text-right">
                    <Small className="text-gray-400 font-mono text-[10px] block">Max size</Small>
                    <Small className={`font-mono text-xs font-bold ${isInWarmupPeriod ? "text-yellow-400" : "text-[#00ff00]"}`}>
                      100MB
                    </Small>
                  </div>
                </div>

                {/* Unlimited Pass CTA - Only when in warm-up AND hit daily limit AND don't have pass */}
                {isInWarmupPeriod && uploadsRemaining === 0 && !hasUploadPass && (
                  <div className="mt-3 pt-3 border-t border-red-500/20">
                    <div className="bg-purple-500/10 border border-purple-500/30 rounded-lg p-3">
                      <div className="flex items-center justify-between mb-2">
                        <div>
                          <Small className="text-purple-400 font-mono font-bold block">
                            ∞ Unlimited Pass - $10
                          </Small>
                          <Small className="text-gray-400 font-mono text-[9px]">
                            Jailbreak warm-up • 100 uploads/day • Unlimited storage
                          </Small>
                        </div>
                        <Small className="text-purple-400/70 font-mono text-[9px]">
                          {daysRemainingInWarmup}d left
                        </Small>
                      </div>
                      <button
                        onClick={() => onNavigateToProfile?.()}
                        className="w-full py-2 rounded-lg bg-purple-500 text-white font-mono text-xs font-bold hover:bg-purple-600 transition-all"
                      >
                        Get Unlimited Pass
                      </button>
                      <Small className="text-gray-500 font-mono text-[9px] block mt-2 text-center">
                        Or wait {daysRemainingInWarmup} day{daysRemainingInWarmup !== 1 ? "s" : ""} for full access
                      </Small>
                    </div>
                  </div>
                )}

                {isInWarmupPeriod && (uploadsRemaining > 0 || hasUploadPass) && (
                  <div className="mt-2 pt-2 border-t border-yellow-500/10">
                    <Small className="text-gray-500 font-mono text-[9px] flex items-center gap-1">
                      <LightbulbIcon size={10} className="shrink-0" /> New members: {WARMUP_DAILY_LIMIT}/day for 7 days → {REGULAR_DAILY_LIMIT}/day after
                    </Small>
                  </div>
                )}

                {/* Base App: Prompt to link Farcaster address for existing members */}
                {isInWarmupPeriod && appMode === "base-app" && (
                  <div className="mt-3 pt-3 border-t border-purple-500/20">
                    <div className="bg-purple-500/5 border border-purple-500/20 rounded-lg p-3">
                      <Small className="text-purple-300 font-mono text-[10px] flex items-center gap-1 mb-2">
                        <LinkIcon size={12} /> Already a Net Library member on Farcaster?
                      </Small>
                      <Small className="text-gray-400 font-mono text-[9px] block mb-2">
                        Link this wallet to your Farcaster account to unlock your full membership benefits.
                      </Small>
                      <button
                        onClick={() => safeOpenUrl("https://warpcast.com/~/settings/verified-addresses")}
                        className="w-full py-2 rounded-lg bg-purple-500/20 border border-purple-500/40 text-purple-300 font-mono text-[10px] font-bold hover:bg-purple-500/30 transition-all"
                      >
                        Add Verified Address in Warpcast →
                      </button>
                      <Small className="text-gray-500 font-mono text-[8px] block mt-2 text-center">
                        Add this wallet as a verified address, then refresh
                      </Small>
                    </div>
                  </div>
                )}
              </CardContent>
            </Card>
          )}
            </>
          )}

        </>
      )}

      {uploadState.status === "selected" && (
        <div className="space-y-4">
          {/* Previous Upload Error - Show if retrying after failure */}
          {uploadState.error && (
            <Card className="bg-red-500/10 border-2 border-red-500/50">
              <CardContent className="p-4">
                <div className="flex items-start gap-3">
                  <span className="text-2xl shrink-0">
                    {(uploadState.error || '').toLowerCase().includes("cancel") || (uploadState.error || '').toLowerCase().includes("reject")
                      ? <BanIcon size={24} className="text-red-400" />
                      : (uploadState.error || '').toLowerCase().includes("insufficient") || (uploadState.error || '').toLowerCase().includes("gas")
                      ? "⛽"
                      : (uploadState.error || '').toLowerCase().includes("simulation") || (uploadState.error || '').toLowerCase().includes("generating")
                      ? <SettingsIcon size={24} className="text-yellow-400" />
                      : <XCircleIcon size={24} className="text-red-400" />}
                  </span>
                  <div className="flex-1">
                    <H4 className="text-red-400 font-mono text-sm">Upload Failed - Ready to Retry</H4>
                    <Small className="text-gray-300 font-mono mt-1 block">
                      {createAppError(uploadState.error).message}
                    </Small>
                    <Small className="text-gray-500 font-mono text-[10px] block mt-0.5">
                      Error code: {createAppError(uploadState.error).code}
                    </Small>
                    {((uploadState.error || '').toLowerCase().includes("simulation") || (uploadState.error || '').toLowerCase().includes("generating")) && (
                      <Small className="text-yellow-400/80 font-mono text-[10px] mt-2 flex items-center gap-1">
                        <LightbulbIcon size={10} className="shrink-0" /> Tip: Wait a few seconds and try again. If this keeps happening, the network may be congested.
                      </Small>
                    )}
                    {((uploadState.error || '').toLowerCase().includes("insufficient") || (uploadState.error || '').toLowerCase().includes("fund") || (uploadState.error || '').toLowerCase().includes("usdc")) && (
                      <div className="mt-2 space-y-1">
                        <Small className="text-yellow-400/80 font-mono text-[10px] flex items-center gap-1">
                          <LightbulbIcon size={10} className="shrink-0" /> Wallet: {walletAddress ? `${walletAddress.slice(0, 6)}...${walletAddress.slice(-4)}` : "not connected"}
                        </Small>
                        <Small className="text-yellow-400/80 font-mono text-[10px] flex items-center gap-1">
                          <DollarBillIcon size={10} className="shrink-0" /> Relay Balance: ${progress.backendWalletBalance?.toFixed(2) || "0.00"} USDC
                        </Small>
                        <Small className="text-gray-400 font-mono text-[10px] block">
                          Fund your Upload Wallet to continue uploading.
                        </Small>
                      </div>
                    )}
                  </div>
                </div>
                <Small className="text-green-400/70 font-mono text-[10px] block mt-3">
                  ✓ Your metadata is saved - just tap Upload to try again
                </Small>
              </CardContent>
            </Card>
          )}

          {/* Hard Block Warnings - Cannot upload */}
          {duplicateWarning?.isDuplicate && duplicateWarning.isHardBlock && (
            <Card className="bg-red-500/10 border-2 border-red-500/50">
              <CardContent className="p-4">
                <H4 className="text-red-400 font-mono flex items-center gap-2">
                  <XCircleIcon size={16} className="text-red-400" />
                  {duplicateWarning.matchType === "exact-hash" && "Exact Duplicate Detected"}
                  {duplicateWarning.matchType === "exact-isbn" && "ISBN/DOI Already Exists"}
                  {duplicateWarning.matchType === "exact-title-author" && "Title Already Exists"}
                </H4>
                <Small className="text-gray-300 font-mono mt-2 block">
                  {duplicateWarning.message || "This content already exists in the library."}
                </Small>
                {duplicateWarning.existingEntry && (
                  <div className="mt-3 p-2 bg-black/30 rounded-lg">
                    <Small className="text-white font-mono font-bold block">
                      &quot;{duplicateWarning.existingEntry.title}&quot;
                    </Small>
                    <Small className="text-gray-400 font-mono text-[10px] block">
                      by {duplicateWarning.existingEntry.author} • Uploaded {new Date(duplicateWarning.existingEntry.uploadedAt).toLocaleDateString()}
                    </Small>
                    {duplicateWarning.existingEntry.isbn && (
                      <Small className="text-gray-500 font-mono text-[10px] block mt-1">
                        ISBN/DOI: {duplicateWarning.existingEntry.isbn}
                      </Small>
                    )}
                  </div>
                )}
                <Small className="text-red-400/70 font-mono text-[10px] block mt-2">
                  Uploading duplicate content is not allowed. Please choose a different file.
                </Small>
              </CardContent>
            </Card>
          )}

          {/* Soft Warning - Can still upload but shows caution */}
          {duplicateWarning?.isDuplicate && !duplicateWarning.isHardBlock && (
            <Card className="bg-yellow-500/10 border border-yellow-500/50">
              <CardContent className="p-4">
                <H4 className="text-yellow-400 font-mono flex items-center gap-2">
                  <WarningIcon size={18} /> {duplicateWarning.matchType === "same-author-similar-title"
                    ? "Similar Work by Same Author"
                    : "Similar Title Found"}
                </H4>
                <Small className="text-gray-300 font-mono mt-2 block">
                  {duplicateWarning.message || "A similar item may already exist. Please verify this is different content."}
                </Small>
                {duplicateWarning.existingEntry && (
                  <div className="mt-2 p-2 bg-black/30 rounded-lg">
                    <Small className="text-white font-mono">
                      &quot;{duplicateWarning.existingEntry.title}&quot; by {duplicateWarning.existingEntry.author}
                    </Small>
                  </div>
                )}
                <Small className="text-yellow-400/70 font-mono text-[10px] block mt-2">
                  You can still proceed if this is a different edition or version.
                </Small>
              </CardContent>
            </Card>
          )}

          {/* Legacy title-based duplicate warning */}
          {uploadState.duplicateWarning && !duplicateWarning?.isDuplicate && (
            <Card
              className={`${
                uploadState.duplicateWarning.type === "exact"
                  ? "bg-red-500/10 border-red-500/50"
                  : "bg-yellow-500/10 border-yellow-500/50"
              }`}
            >
              <CardContent className="p-4">
                <H4
                  className={`font-mono ${
                    uploadState.duplicateWarning.type === "exact"
                      ? "text-red-400"
                      : "text-yellow-400"
                  }`}
                >
                  <WarningIcon size={16} className="inline mr-1" />
                  {uploadState.duplicateWarning.type === "exact"
                    ? "Duplicate Found"
                    : "Similar Title Found"}
                </H4>
                <Small className="text-gray-400 font-mono mt-2 block">
                  {uploadState.duplicateWarning.type === "exact"
                    ? "A book with this exact title already exists."
                    : "Similar books already exist:"}
                </Small>
                <div className="mt-2 space-y-1">
                  {(uploadState.duplicateWarning.matchedBooks || []).map((book) => (
                    <div key={book.id} className="text-sm text-gray-300 font-mono">
                      • {book.title} by {book.author}
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Warm-up Period Limit - User can get Unlimited Pass to jailbreak */}
          {canPurchaseUploadPass && (
            <Card className="bg-yellow-500/10 border-2 border-yellow-500/50">
              <CardContent className="p-4">
                <H4 className="text-yellow-400 font-mono flex items-center gap-2">
                  <ClockIcon size={18} /> Daily Limit Reached
                </H4>
                <Small className="text-gray-300 font-mono mt-2 block">
                  {uploadWarning}
                </Small>
                <div className="mt-3 p-3 bg-black/30 rounded-lg">
                  <div className="flex items-center justify-between">
                    <div>
                      <Small className="text-white font-mono font-bold block">
                        ∞ Unlimited Pass - $10
                      </Small>
                      <Small className="text-gray-400 font-mono text-[10px] block mt-1">
                        Jailbreak warm-up • 100 uploads/day • Unlimited storage
                      </Small>
                    </div>
                    <div className="text-right">
                      <Small className="text-yellow-400 font-mono text-[10px] block">
                        {daysRemainingInWarmup} days remaining
                      </Small>
                    </div>
                  </div>
                </div>
                <Small className="text-gray-500 font-mono text-[10px] mt-3 flex items-center gap-1">
                  <LightbulbIcon size={10} className="shrink-0" /> Or wait {daysRemainingInWarmup} more days for full access (100 uploads/day)
                </Small>
              </CardContent>
            </Card>
          )}

          <Card className="bg-[#00ff00]/10 border-2 border-[#00ff00]/30">
            <CardContent className="p-4">
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-lg bg-[#00ff00]/20 flex items-center justify-center">
                  <DocumentIcon size={24} className="text-[#00ff00]" />
                </div>
                <div className="flex-1 min-w-0">
                  <P className="font-mono text-white truncate">{uploadState.fileName}</P>
                  <div className="flex items-center gap-2">
                    <Small className="text-[#00ff00] font-mono">
                      {(uploadState.fileSize / (1024 * 1024)).toFixed(1)} MB
                    </Small>
                    {originalEpubName && (
                      <span className="px-1.5 py-0.5 bg-purple-500/20 text-purple-400 rounded text-[9px] font-mono flex items-center gap-1">
                        <LibraryIcon size={10} /> from EPUB
                      </span>
                    )}
                  </div>
                </div>
                <div className="text-center shrink-0">
                  <div className="text-2xl font-bold text-[#00ff00] font-mono">{uploadState.totalChunks}</div>
                  <Small className="text-[#00ff00]/70 font-mono text-[9px]">TXs needed</Small>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Editable metadata fields */}
          <Card className="bg-[#0a0a0a] border border-[#00ff00]/30">
            <CardContent className="p-4 space-y-4">
              <div>
                <div className="flex items-center justify-between mb-1">
                  <Small className="text-[#00ff00] font-mono">Title</Small>
                  <Small className={`font-mono text-[10px] ${bookTitle.length > 256 ? 'text-red-400' : bookTitle.length > 200 ? 'text-yellow-400' : 'text-gray-500'}`}>
                    {bookTitle.length}/256
                  </Small>
                </div>
                <input
                  type="text"
                  value={bookTitle}
                  onChange={(e) => setBookTitle(e.target.value.slice(0, 256))}
                  maxLength={256}
                  placeholder="e.g., The Great Gatsby"
                  className="w-full px-3 py-2 rounded-md bg-black border border-[#00ff00]/30 text-white font-mono placeholder:text-gray-500 focus:border-[#00ff00] focus:ring-1 focus:ring-[#00ff00] focus:outline-none"
                />
              </div>
              <div>
                <Small className="text-[#00ff00] font-mono mb-1 block">Author</Small>
                <input
                  type="text"
                  value={authorName}
                  onChange={(e) => setAuthorName(e.target.value)}
                  placeholder="e.g., F. Scott Fitzgerald"
                  className="w-full px-3 py-2 rounded-md bg-black border border-[#00ff00]/30 text-white font-mono placeholder:text-gray-500 focus:border-[#00ff00] focus:ring-1 focus:ring-[#00ff00] focus:outline-none"
                />
              </div>
              {/* Optional metadata fields - collapsible */}
              <details className="group">
                <summary className="flex items-center gap-2 cursor-pointer text-[#00ff00]/70 hover:text-[#00ff00] font-mono text-xs list-none">
                  <span className="transition-transform group-open:rotate-90">▶</span>
                  Additional Details (optional)
                </summary>
                <div className="mt-3 space-y-3 pl-4 border-l-2 border-[#00ff00]/20">
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <Small className="text-[#00ff00]/70 font-mono mb-1 block text-[11px]">Publication Year</Small>
                      <input
                        type="number"
                        value={publicationYear}
                        onChange={(e) => setPublicationYear(e.target.value)}
                        placeholder="e.g., 1925"
                        min="1000"
                        max={new Date().getFullYear()}
                        className="w-full px-3 py-2 rounded-md bg-black border border-[#00ff00]/20 text-white font-mono placeholder:text-gray-600 focus:border-[#00ff00] focus:ring-1 focus:ring-[#00ff00] focus:outline-none text-sm"
                      />
                    </div>
                    <div>
                      <Small className="text-[#00ff00]/70 font-mono mb-1 block text-[11px]">Publisher</Small>
                      <input
                        type="text"
                        value={publisher}
                        onChange={(e) => setPublisher(e.target.value)}
                        placeholder="e.g., Scribner"
                        className="w-full px-3 py-2 rounded-md bg-black border border-[#00ff00]/20 text-white font-mono placeholder:text-gray-600 focus:border-[#00ff00] focus:ring-1 focus:ring-[#00ff00] focus:outline-none text-sm"
                      />
                    </div>
                  </div>
                  <div>
                    <Small className="text-[#00ff00]/70 font-mono mb-1 block text-[11px]">ISBN / DOI</Small>
                    <input
                      type="text"
                      value={isbn}
                      onChange={(e) => setIsbn(e.target.value)}
                      placeholder="e.g., 978-0743273565 or 10.1000/xyz123"
                      className="w-full px-3 py-2 rounded-md bg-black border border-[#00ff00]/20 text-white font-mono placeholder:text-gray-600 focus:border-[#00ff00] focus:ring-1 focus:ring-[#00ff00] focus:outline-none text-sm"
                    />
                  </div>
                </div>
              </details>
              <div>
                <div className="flex items-center justify-between mb-1">
                  <Small className="text-[#00ff00] font-mono">Category</Small>
                  <Small className="text-gray-500 font-mono text-[10px]">
                    {selectedCategories.length}/3 selected
                  </Small>
                </div>
                <CategoryDropdown
                  categories={categories}
                  selectedCategories={selectedCategories}
                  onToggle={toggleCategory}
                  maxSelections={3}
                />
              </div>
              {/* Add to Stack (optional) - also shown in selected state */}
              <div>
                <div className="flex items-center justify-between mb-1">
                  <Small className="text-[#00ff00] font-mono">Add to Stack (optional)</Small>
                  {selectedStackIds.length > 0 && (
                    <Small className="text-purple-400 font-mono text-[10px]">
                      {selectedStackIds.length} selected
                    </Small>
                  )}
                </div>
                <StackSelectionDropdown
                  stacks={userStacks}
                  selectedStackIds={selectedStackIds}
                  onToggle={toggleStackSelection}
                  isLoading={isLoadingStacks}
                />
                <Small className="text-gray-500 font-mono text-[10px] mt-1 block">
                  Automatically add this item to your stacks
                </Small>
              </div>
              {/* Encryption toggle — members only */}
              {isMember && (
                <div className="border border-[#00ff00]/20 rounded-lg p-3 space-y-3">
                  <div className="flex items-center justify-between">
                    <div>
                      <Small className="text-[#00ff00] font-mono flex items-center gap-1.5">
                        <LockIcon size={12} /> Encrypt this item
                      </Small>
                      <Small className="text-gray-500 font-mono text-[10px] block mt-0.5">
                        AES-256-GCM client-side encryption
                      </Small>
                    </div>
                    <button
                      type="button"
                      onClick={() => {
                        const next = !encryptEnabled;
                        setEncryptEnabled(next);
                        if (next && savedPasswords.length === 0 && !isFetchingPasswords) {
                          fetchSavedPasswords();
                        }
                        if (!next) {
                          setEncryptPassword("");
                          setSelectedSavedPasswordId(null);
                          setPasswordSource("new");
                        }
                      }}
                      className={`relative w-10 h-5 rounded-full transition-colors ${encryptEnabled ? "bg-[#00ff00]/60" : "bg-gray-700"}`}
                      aria-label="Toggle encryption"
                    >
                      <span className={`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${encryptEnabled ? "translate-x-5" : "translate-x-0"}`} />
                    </button>
                  </div>

                  {encryptEnabled && (
                    <div className="space-y-2 pt-1 border-t border-[#00ff00]/10">
                      {/* Saved password selector */}
                      {isFetchingPasswords ? (
                        <Small className="text-gray-500 font-mono text-[10px] block">Loading saved passwords…</Small>
                      ) : savedPasswords.length > 0 ? (
                        <div>
                          <Small className="text-[#00ff00]/70 font-mono text-[11px] mb-1 block">Use saved password</Small>
                          <select
                            value={selectedSavedPasswordId || ""}
                            onChange={(e) => {
                              const id = e.target.value;
                              if (id) {
                                setSelectedSavedPasswordId(id);
                                setPasswordSource("saved");
                                // Don't touch encryptPassword — it's irrelevant when using a saved password
                              } else {
                                setSelectedSavedPasswordId(null);
                                setPasswordSource("new");
                                setEncryptPassword(""); // Clear so the input starts blank
                              }
                            }}
                            className="w-full px-3 py-1.5 rounded bg-black border border-[#00ff00]/20 text-white font-mono text-sm focus:border-[#00ff00] focus:outline-none"
                          >
                            <option value="">— Type a new password —</option>
                            {savedPasswords.map(p => (
                              <option key={p.id} value={p.id}>{p.label}</option>
                            ))}
                          </select>
                        </div>
                      ) : null}

                      {/* New password input — shown when source is 'new' */}
                      {passwordSource === "new" && (
                        <div>
                          <Small className="text-[#00ff00]/70 font-mono text-[11px] mb-1 block">Password</Small>
                          <input
                            type="password"
                            value={encryptPassword}
                            onChange={(e) => setEncryptPassword(e.target.value)}
                            placeholder="Enter encryption password…"
                            className="w-full px-3 py-2 rounded-md bg-black border border-[#00ff00]/20 text-white font-mono text-sm placeholder:text-gray-600 focus:border-[#00ff00] focus:ring-1 focus:ring-[#00ff00] focus:outline-none"
                          />
                        </div>
                      )}

                      {/* Save password checkbox (only for new passwords that have content) */}
                      {passwordSource === "new" && encryptPassword.trim() && (
                        <div className="space-y-1.5">
                          <label className="flex items-center gap-2 cursor-pointer">
                            <input
                              type="checkbox"
                              checked={encryptSavePassword}
                              onChange={(e) => setEncryptSavePassword(e.target.checked)}
                              className="rounded border-[#00ff00]/30 bg-black text-[#00ff00] focus:ring-[#00ff00]"
                            />
                            <Small className="text-gray-400 font-mono text-[11px]">Save this password to my password list</Small>
                          </label>
                          {encryptSavePassword && (
                            <input
                              type="text"
                              value={encryptPasswordLabel}
                              onChange={(e) => setEncryptPasswordLabel(e.target.value)}
                              placeholder={`Label (optional, e.g. "${bookTitle || "My File"}")`}
                              className="w-full px-3 py-1.5 rounded bg-black border border-[#00ff00]/20 text-white font-mono text-[11px] placeholder:text-gray-600 focus:border-[#00ff00] focus:outline-none"
                            />
                          )}
                        </div>
                      )}

                      {/* Warning banner */}
                      <div className="p-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">
                        <Small className="text-yellow-400 font-mono text-[10px] block leading-relaxed">
                          ⚠ Only people with this password can view the content. Save your password — it cannot be recovered if lost.
                        </Small>
                      </div>
                    </div>
                  )}
                </div>
              )}

              {/* Cover Art Upload - also shown in selected state */}
              <div>
                <Small className="text-[#00ff00] font-mono mb-1 block">Cover Art (optional)</Small>
                {isExtractingCover ? (
                  <div className="flex items-center gap-3 p-3 bg-[#00ff00]/5 rounded-lg border border-[#00ff00]/20">
                    <div className="w-8 h-8 rounded bg-[#00ff00]/20 flex items-center justify-center animate-pulse">
                      <DocumentIcon size={16} className="text-[#00ff00]" />
                    </div>
                    <Small className="text-[#00ff00] font-mono">Extracting cover from PDF...</Small>
                  </div>
                ) : coverArtUrl ? (
                  <div className="flex items-center gap-3">
                    <div className="w-16 h-20 rounded overflow-hidden border border-[#00ff00]/30">
                      <img src={coverArtUrl} alt="Cover" className="w-full h-full object-cover" />
                    </div>
                    <div className="flex-1">
                      <Small className="text-[#00ff00] font-mono flex items-center gap-1"><CheckIcon size={12} /> Cover ready!</Small>
                      <Small className="text-gray-500 font-mono text-[10px] block">
                        {selectedFile?.name.toLowerCase().endsWith('.pdf') ? 'Auto-extracted from PDF' : 'Custom cover'}
                      </Small>
                      <div className="flex items-center gap-4 mt-2">
                        <button
                          type="button"
                          onClick={(e) => {
                            console.log("[UploadTab] Change cover button clicked");
                            e.stopPropagation();
                            coverInputRef.current?.click();
                          }}
                          className="text-xs text-[#00ff00] font-mono hover:text-[#00ff00]/80 underline underline-offset-2 cursor-pointer active:opacity-70 py-1 px-1 -mx-1 min-h-[32px] flex items-center"
                        >
                          Change
                        </button>
                        <button
                          type="button"
                          onClick={(e) => {
                            e.stopPropagation();
                            setCoverArtUrl(null);
                            setIsUserSelectedCover(false);
                            isUserSelectedCoverRef.current = false;
                          }}
                          className="text-xs text-red-400 font-mono hover:text-red-300 underline underline-offset-2 cursor-pointer active:opacity-70 py-1 px-1 -mx-1 min-h-[32px] flex items-center"
                        >
                          Remove
                        </button>
                      </div>
                    </div>
                  </div>
                ) : (
                  <div className="space-y-2">
                    <button
                      type="button"
                      onClick={() => setShowCoverUpload(true)}
                      className="w-full py-3 min-h-[44px] border-2 border-dashed border-[#00ff00]/30 rounded-lg text-[#00ff00]/70 font-mono text-sm hover:border-[#00ff00] hover:text-[#00ff00] hover:bg-[#00ff00]/5 transition-all flex items-center justify-center gap-2"
                    >
                      <ImageIcon size={16} /> Upload cover (optional)
                    </button>
                    <input
                      type="url"
                      inputMode="url"
                      placeholder="Or paste image URL..."
                      className="w-full px-3 py-2 min-h-[44px] bg-black/50 border border-[#00ff00]/20 rounded-lg text-white font-mono text-sm placeholder:text-gray-600 focus:border-[#00ff00] focus:outline-none"
                      onKeyDown={(e) => {
                        if (e.key === 'Enter') {
                          const url = (e.target as HTMLInputElement).value.trim();
                          if (url && (url.startsWith('http://') || url.startsWith('https://'))) {
                            setCoverArtUrl(url);
                            setIsUserSelectedCover(true);
                            isUserSelectedCoverRef.current = true;
                          }
                        }
                      }}
                      onBlur={(e) => {
                        const url = e.target.value.trim();
                        if (url && (url.startsWith('http://') || url.startsWith('https://'))) {
                          setCoverArtUrl(url);
                          setIsUserSelectedCover(true);
                          isUserSelectedCoverRef.current = true;
                        }
                      }}
                    />
                  </div>
                )}
                <Small className="text-[#00ff00]/50 font-mono text-[10px] mt-1 block">
                  PDF covers auto-extracted • Or upload/paste URL
                </Small>
              </div>
            </CardContent>
          </Card>

          {/* Extra spacing before action buttons for better mobile touch targets */}
          <div className="flex gap-2 mt-2">
            <Button
              onClick={handleReset}
              variant="outline"
              className="flex-1 border-[#222] text-gray-400 hover:border-[#00ff00] hover:text-[#00ff00]"
            >
              Cancel
            </Button>
            {canPurchaseUploadPass ? (
              // Warm-up period limit - direct to profile for Unlimited Pass purchase
              <Button
                onClick={() => {
                  // Navigate to profile tab where Unlimited Pass can be purchased
                  onNavigateToProfile?.();
                }}
                disabled={
                  uploadState.duplicateWarning?.type === "exact" ||
                  (duplicateWarning?.isDuplicate && duplicateWarning.isHardBlock) ||
                  !isConnected ||
                  isCheckingDuplicate
                }
                className="flex-1 bg-purple-500 text-white hover:bg-purple-600 font-mono disabled:opacity-50"
              >
                {isCheckingDuplicate ? "Checking..." : "Get Unlimited Pass ($10)"}
              </Button>
            ) : (
              // Normal upload button
              <Button
                onClick={async (e) => {
                  // DEBUG: Log when upload button is clicked
                  console.log("[UploadTab] Upload to Net Protocol button clicked");

                  // Prevent any event bubbling that might trigger other elements
                  e.stopPropagation();
                  e.preventDefault();

                  // Estimate relay cost before showing confirmation (x402 USDC)
                  if (selectedFile) {
                    setIsEstimatingGas(true);
                    try {
                      const estimate = await estimateUploadCost(selectedFile);
                      const balanceEth = estimate.balanceInfo?.balanceEth || 0;
                      const balanceUsdc = estimate.balanceInfo?.balanceUsdc || 0;
                      setGasEstimate({
                        estimatedCostEth: (estimate.estimatedCostEth || 0).toFixed(6),
                        estimatedCostUsdc: estimate.estimatedCostUsdc.toFixed(2),
                        balanceEth: balanceEth.toFixed(6),
                        balanceUsdc: balanceUsdc.toFixed(2),
                        sufficient: estimate.canProceed,
                        lowBalance: estimate.lowBalance,
                      });
                    } catch (e) {
                      console.error("Cost estimation failed:", e);
                      setGasEstimate(null);
                    }
                    setIsEstimatingGas(false);
                  }
                  setShowConfirmUpload(true);
                }}
                disabled={
                  uploadState.duplicateWarning?.type === "exact" ||
                  (duplicateWarning?.isDuplicate && duplicateWarning.isHardBlock) ||
                  !isConnected ||
                  isEstimatingGas ||
                  isCheckingDuplicate ||
                  (encryptEnabled && passwordSource === "new" && !encryptPassword.trim()) ||
                  (encryptEnabled && passwordSource === "saved" && !selectedSavedPasswordId)
                }
                className="flex-1 bg-[#00ff00] text-black hover:bg-[#00dd00] font-mono disabled:opacity-50 min-h-[48px]"
              >
                {isCheckingDuplicate ? "Checking..." : isEstimatingGas ? "Estimating cost..." : isEncryptingFile ? "Encrypting…" : "Upload to Net Protocol"}
              </Button>
            )}
          </div>

          {/* Upload Confirmation Modal */}
          {showConfirmUpload && (
            <div
              className="fixed inset-0 bg-black/90 flex items-center justify-center z-50 p-4"
              onClick={() => setShowConfirmUpload(false)}
            >
              <div
                className="bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg p-4 w-full max-w-sm"
                onClick={(e) => e.stopPropagation()}
              >
                <H4 className="text-[#00ff00] font-mono mb-3 flex items-center gap-2"><WarningIcon size={18} /> Confirm Upload</H4>

                <div className="space-y-3 mb-4">
                  {/* Combined Upload Details with transaction info */}
                  <div className="bg-black/50 border border-[#00ff00]/20 rounded-lg p-3 space-y-2">
                    <div className="flex items-center justify-between">
                      <Small className="text-[#00ff00] font-mono font-bold flex items-center gap-1"><ClipboardIcon size={12} /> {bookTitle || uploadState.fileName}</Small>
                      <Small className="text-gray-400 font-mono text-[10px]">{(uploadState.fileSize / (1024 * 1024)).toFixed(1)} MB</Small>
                    </div>
                    <Small className="text-gray-400 font-mono text-[10px]">by {authorName || "Unknown"}</Small>

                    {/* Inline signature count */}
                    {(() => {
                      const CHUNKS_PER_BATCH = 5; // Match use-net-upload.ts - smaller batches for Base App compatibility
                      const totalBatchesNeeded = Math.ceil(uploadState.totalChunks / CHUNKS_PER_BATCH);
                      const signaturesNeeded = uploadState.totalChunks > 1 ? totalBatchesNeeded : 1;
                      return (
                        <div className="flex items-center justify-between pt-2 border-t border-[#00ff00]/10">
                          <Small className="text-gray-400 font-mono text-[10px]">Signatures needed:</Small>
                          <Small className="text-green-400 font-mono text-xs font-bold">{signaturesNeeded}</Small>
                        </div>
                      );
                    })()}
                  </div>

                  {/* x402 Relay Cost - ETH (with USD display) */}
                  {gasEstimate && (
                    <div className={`px-3 py-2 border rounded-lg ${gasEstimate.sufficient ? "bg-[#1a1a1a] border-gray-700" : "bg-red-500/10 border-red-500/30"}`}>
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-2">
                          <span className="text-sm">⟠</span>
                          <div className="flex flex-col">
                            <Small className="text-gray-300 font-mono text-[11px]">
                              ~{gasEstimate.estimatedCostEth} ETH
                            </Small>
                            <Small className="text-gray-500 font-mono text-[9px]">
                              (~${gasEstimate.estimatedCostUsdc})
                            </Small>
                          </div>
                        </div>
                        <div className="flex flex-col items-end">
                          <Small className={`font-mono text-[10px] ${gasEstimate.sufficient ? "text-green-400" : "text-red-400"}`}>
                            {gasEstimate.sufficient ? "✓" : "✗"} {gasEstimate.balanceEth} ETH
                          </Small>
                          <Small className="text-gray-500 font-mono text-[9px]">
                            (${gasEstimate.balanceUsdc})
                          </Small>
                        </div>
                      </div>
                      {!gasEstimate.sufficient && (
                        <button
                          onClick={() => {
                            setIsStandaloneAddFunds(false); // This is during upload, not standalone
                            setShowAddFundsModal(true);
                          }}
                          className="w-full mt-2 py-1.5 rounded bg-purple-500/20 text-purple-400 font-mono text-[10px] hover:bg-purple-500/30"
                        >
                          Add Funds
                        </button>
                      )}
                    </div>
                  )}

                  {/* Membership Required - only if applicable */}
                  {requiresMembership(uploadState.fileSize, isMember) && (
                    <div className="px-3 py-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg">
                      <Small className="text-yellow-400 font-mono text-[11px] flex items-center gap-1">
                        <TagIcon size={12} /> Membership required for files over 200KB
                      </Small>
                    </div>
                  )}

                  {/* Premium Upload Fee - only if applicable */}
                  {requiresPremiumUpload(uploadState.fileSize, isMember) && (
                    <div className={`px-3 py-2 border rounded-lg ${premiumPaid ? "bg-green-500/10 border-green-500/30" : "bg-purple-500/10 border-purple-500/30"}`}>
                      {premiumPaid ? (
                        <Small className="text-green-400 font-mono text-[11px] flex items-center gap-1"><CheckCircleIcon size={12} /> Premium fee paid</Small>
                      ) : (
                        <div className="flex items-center justify-between">
                          <Small className="text-purple-400 font-mono text-[11px] flex items-center gap-1"><StarIcon size={12} /> Premium fee required</Small>
                          <Small className="text-purple-400 font-mono text-xs font-bold">${calculatePremiumFee(uploadState.fileSize)}</Small>
                        </div>
                      )}
                    </div>
                  )}
                </div>

                <div className="flex gap-2">
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      e.preventDefault();
                      setShowConfirmUpload(false);
                      setGasEstimate(null);
                    }}
                    className="flex-1 py-3 rounded-lg bg-[#1a1a1a] text-gray-400 font-mono text-sm hover:bg-[#222] hover:text-white transition-all"
                  >
                    Go Back
                  </button>
                  {/* Show Membership Required button for non-members with large files */}
                  {requiresMembership(uploadState.fileSize, isMember) ? (
                    <button
                      type="button"
                      disabled
                      className="flex-1 py-3 rounded-lg font-mono text-sm font-bold bg-yellow-500/20 text-yellow-400 cursor-not-allowed flex items-center justify-center gap-2"
                    >
                      <TagIcon size={14} /> Membership Required
                    </button>
                  ) : requiresPremiumUpload(uploadState.fileSize, isMember) && !premiumPaid ? (
                    /* Show Pay button if premium is required and not yet paid */
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowPremiumModal(true);
                      }}
                      disabled={gasEstimate !== null && !gasEstimate.sufficient}
                      className={`flex-1 py-3 rounded-lg font-mono text-sm font-bold transition-all ${
                        gasEstimate && !gasEstimate.sufficient
                          ? "bg-gray-600 text-gray-400 cursor-not-allowed"
                          : "bg-purple-500 text-white hover:bg-purple-600"
                      }`}
                    >
                      {gasEstimate && !gasEstimate.sufficient
                        ? "Insufficient USDC"
                        : `Pay $${calculatePremiumFee(uploadState.fileSize)} USDC`}
                    </button>
                  ) : (
                    <button
                      type="button"
                      onClick={async (e) => {
                        // Prevent any event bubbling that might trigger file inputs on iOS
                        e.stopPropagation();
                        e.preventDefault();

                        setIsPreparingUpload(true);
                        // Small delay to show loading state before modal closes
                        await new Promise(resolve => setTimeout(resolve, 100));
                        setShowConfirmUpload(false);
                        setGasEstimate(null);
                        handleUpload().finally(() => setIsPreparingUpload(false));
                      }}
                      disabled={(gasEstimate !== null && !gasEstimate.sufficient) || isPreparingUpload}
                      className={`flex-1 py-3 rounded-lg font-mono text-sm font-bold transition-all ${
                        isPreparingUpload
                          ? "bg-[#00ff00]/70 text-black/70 cursor-wait"
                          : gasEstimate && !gasEstimate.sufficient
                          ? "bg-gray-600 text-gray-400 cursor-not-allowed"
                          : "bg-[#00ff00] text-black hover:bg-[#00dd00]"
                      }`}
                    >
                      {isPreparingUpload ? (
                        <span className="flex items-center justify-center gap-2">
                          <span className="w-4 h-4 border-2 border-black/30 border-t-black rounded-full animate-spin" />
                          Preparing...
                        </span>
                      ) : gasEstimate && !gasEstimate.sufficient ? (
                        "Insufficient USDC"
                      ) : (
                        "Yes, Upload"
                      )}
                    </button>
                  )}
                </div>
              </div>
            </div>
          )}
        </div>
      )}

      {/* Funding success banner - shows briefly when funds received */}
      {fundingSuccess.show && (
        <div className="fixed top-0 left-0 right-0 z-[9999] bg-black/95 border-b-2 border-green-500/50 p-3 shadow-lg shadow-green-500/20">
          <div className="max-w-md mx-auto">
            <div className="flex items-center justify-center gap-3">
              <span className="text-green-400 text-lg">✓</span>
              <span className="text-white font-mono text-sm">
                Funds received{fundingSuccess.amount ? ` — $${fundingSuccess.amount} USDC` : ""}
              </span>
            </div>
          </div>
        </div>
      )}

      {/* Only show floating progress during actual upload, not during standalone funding */}
      {uploadState.status === "uploading" && !isStandaloneAddFunds && (
        <div className="space-y-4">
          {/* FIXED FLOATING PROGRESS - Always visible even when wallet popup covers the screen */}
          <div className={`fixed top-0 left-0 right-0 z-[9999] bg-black/95 border-b-2 ${
            uploadState.isFunding ? "border-purple-500/50" : "border-[#00ff00]/50"
          } p-3 shadow-lg ${uploadState.isFunding ? "shadow-purple-500/20" : "shadow-[#00ff00]/20"}`}>
            <div className="max-w-md mx-auto">
              {uploadState.isFunding ? (
                /* FUNDING: Single clear message */
                <div className="flex items-center justify-center gap-3">
                  <div className="w-3 h-3 rounded-full bg-purple-400 animate-pulse" />
                  <span className="text-white font-mono text-sm flex items-center gap-1.5">
                    <MoneyIcon size={14} className="text-purple-400" /> Confirming funding transaction...
                  </span>
                </div>
              ) : (
                /* UPLOADING: Show progress */
                <>
                  <div className="flex items-center justify-between mb-2">
                    <div className="flex items-center gap-2">
                      <div className={`w-3 h-3 rounded-full ${
                        uploadState.usedBatchMode ? "bg-green-400" : "bg-yellow-400"
                      } animate-pulse`} />
                      <span className="text-white font-mono text-sm font-bold flex items-center gap-1">
                        <UploadIcon size={14} />
                        {uploadState.usedBatchMode
                          ? uploadState.totalBatches && uploadState.totalBatches > 1
                            ? `Batch ${uploadState.currentBatch}/${uploadState.totalBatches}`
                            : "Uploading..."
                          : `Chunk ${Math.min(uploadState.completedChunks + 1, uploadState.totalChunks)}/${uploadState.totalChunks}`}
                      </span>
                    </div>
                    <span className="font-mono text-xs text-[#00ff00] flex items-center gap-1">
                      {uploadState.currentChunkStatus === "signing"
                        ? <><PencilIcon size={12} /> Sign in wallet</>
                        : uploadState.currentChunkStatus === "waiting-onchain"
                        ? <><LoadingIcon size={12} className="animate-spin" /> Waiting for blockchain...</>
                        : <><LoadingIcon size={12} className="animate-spin" /> Confirming...</>}
                    </span>
                  </div>
                  {/* Progress bar */}
                  <div className="h-2 bg-[#1a1a1a] rounded-full overflow-hidden">
                    <div
                      className={`h-full transition-all duration-500 ${
                        uploadState.usedBatchMode
                          ? "bg-gradient-to-r from-green-500 to-green-400"
                          : "bg-gradient-to-r from-[#00ff00] to-[#00dd00]"
                      }`}
                      style={{
                        width: `${Math.min(100, Math.max(5, (uploadState.completedChunks / uploadState.totalChunks) * 100))}%`,
                      }}
                    />
                  </div>
                  {/* Percentage */}
                  <div className="text-center mt-1">
                    <span className="font-mono text-[10px] text-[#00ff00]/70">
                      {uploadState.totalChunks > 0
                        ? `${Math.min(100, Math.round((uploadState.completedChunks / uploadState.totalChunks) * 100))}% complete`
                        : "0% complete"}
                    </span>
                  </div>
                </>
              )}
              {/* Error display - only show if there's an error */}
              {progress.error && (
                <div className="mt-2 px-2 py-1 bg-red-900/50 border border-red-500/50 rounded text-[9px] font-mono text-center">
                  <span className="text-red-400 flex items-center gap-1"><XCircleIcon size={10} /> {progress.error}</span>
                </div>
              )}
            </div>
          </div>

          {/* Spacer to prevent content from being hidden behind fixed header */}
          <div className="h-20" />

          {/* Status card - only show for actual upload progress, NOT during funding (banner handles funding) */}
          {!uploadState.isFunding && (
            <Card className={`bg-[#0a0a0a] border-2 ${
              uploadState.usedBatchMode
                ? "border-green-500/30"
                : "border-[#00ff00]/30"
            }`}>
              <CardContent className="p-4">
                <div className="flex items-center gap-3">
                  <div
                    className={`w-10 h-10 rounded-full flex items-center justify-center ${
                      uploadState.currentChunkStatus === "signing"
                        ? uploadState.usedBatchMode
                          ? "bg-green-500/20 border border-green-500"
                          : "bg-yellow-500/20 border border-yellow-500"
                        : "bg-[#00ff00]/20 border border-[#00ff00]"
                    }`}
                  >
                    {uploadState.currentChunkStatus === "signing"
                      ? uploadState.usedBatchMode ? "🚀" : <PencilIcon size={16} />
                      : <LoadingIcon size={16} className="animate-spin" />}
                  </div>
                  <div className="flex-1">
                    {uploadState.usedBatchMode ? (
                      <>
                        <P className="font-mono text-white font-bold">
                          {uploadState.totalBatches && uploadState.totalBatches > 1
                            ? `Batch ${uploadState.currentBatch} of ${uploadState.totalBatches}`
                            : `Processing ${uploadState.totalChunks} chunks`}
                        </P>
                        <Small className="text-green-400 font-mono flex items-center gap-1">
                          {uploadState.currentChunkStatus === "signing"
                            ? uploadState.totalBatches && uploadState.totalBatches > 1
                              ? "Approve this batch in your wallet"
                              : "Approve in your wallet"
                            : uploadState.currentChunkStatus === "waiting-onchain"
                            ? <><LoadingIcon size={10} className="animate-spin" /> Waiting for blockchain confirmation...</>
                            : "Confirming on chain..."}
                        </Small>
                      </>
                    ) : (
                      <>
                        <P className="font-mono text-white font-bold">
                          Chunk {Math.min(uploadState.completedChunks + 1, uploadState.totalChunks)} of {uploadState.totalChunks}
                        </P>
                        <Small className="text-gray-400 font-mono flex items-center gap-1">
                          {uploadState.currentChunkStatus === "signing"
                            ? "Approve in your wallet"
                            : uploadState.currentChunkStatus === "waiting-onchain"
                            ? <><LoadingIcon size={10} className="animate-spin" /> Waiting for blockchain confirmation...</>
                            : "Confirming on chain..."}
                        </Small>
                      </>
                    )}
                  </div>
                  <div className={`w-3 h-3 rounded-full ${
                    uploadState.usedBatchMode
                      ? "bg-green-400"
                      : "bg-yellow-400"
                  } animate-pulse`} />
                </div>
                {/* Show transaction link when waiting for on-chain confirmation */}
                {uploadState.currentChunkStatus === "waiting-onchain" && progress.txHashes.length > 0 && (
                  <div className="mt-3 pt-3 border-t border-[#00ff00]/20">
                    <a
                      href={`https://basescan.org/tx/${progress.txHashes[progress.txHashes.length - 1]}`}
                      target="_blank"
                      rel="noopener noreferrer"
                      className="text-xs font-mono text-[#00ff00]/70 hover:text-[#00ff00] underline flex items-center gap-1"
                    >
                      <LinkIcon size={12} /> View transaction on BaseScan
                    </a>
                  </div>
                )}

                {/* Cancel button - shows during active upload */}
                <div className="mt-3 pt-3 border-t border-[#00ff00]/20">
                  <button
                    onClick={handleCancelUpload}
                    disabled={isCancelling}
                    className={`w-full py-2 text-sm font-mono transition-colors ${
                      isCancelling
                        ? "text-yellow-400 cursor-not-allowed"
                        : "text-gray-500 hover:text-red-400"
                    }`}
                  >
                    {isCancelling ? <><LoadingIcon size={12} className="inline animate-spin mr-1" /> Cancelling...</> : "Cancel upload"}
                  </button>
                  {isCancelling && (
                    <Small className="text-yellow-400/70 font-mono text-[10px] text-center block mt-1">
                      Note: Confirmed transactions cannot be reversed
                    </Small>
                  )}
                </div>
              </CardContent>
            </Card>
          )}

          {/* Cancel button for funding - shown separately when funding */}
          {uploadState.isFunding && (
            <Card className="bg-[#0a0a0a] border-2 border-purple-500/30">
              <CardContent className="p-4">
                <button
                  onClick={() => {
                    setUploadState(prev => ({
                      ...prev,
                      status: "idle",
                      isFunding: false,
                      error: undefined,
                    }));
                    resetUpload();
                  }}
                  className="w-full py-2 text-purple-400/70 font-mono text-xs hover:text-purple-300 transition-colors"
                >
                  Cancel and try again
                </button>
              </CardContent>
            </Card>
          )}

        </div>
      )}

      {uploadState.status === "complete" && (
        <div className="space-y-4 text-center py-8">
          <div className="mb-4 flex justify-center"><CheckCircleIcon size={64} className="text-[#00ff00]" /></div>
          <H4 className="text-[#00ff00] font-mono">
            {uploadState.isImport ? "Import Complete!" : "Upload Complete!"}
          </H4>
          <P className="text-gray-400 font-mono">
            <span className="text-white font-bold">{bookTitle || uploadState.fileName}</span>{" "}
            {uploadState.isImport
              ? "has been added to Net Library"
              : "is now stored onchain via Net Protocol"
            }
          </P>
          {/* Encryption notice — only shown when the uploaded item was encrypted */}
          {encryptEnabled && (
            <div className="flex items-center justify-center gap-2 px-4 py-2 rounded-lg bg-yellow-500/10 border border-yellow-500/20 mx-auto max-w-xs">
              <LockIcon size={14} className="text-yellow-400 shrink-0" />
              <Small className="text-yellow-400 font-mono text-[11px] text-left">
                This item is encrypted. You&apos;ll need your password to view it.
              </Small>
            </div>
          )}
          {/* Show CDN link for actual uploads to Net Protocol (not imports - they already have the link) */}
          {uploadState.cdnUrl && !uploadState.isImport && (
            <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30 text-left">
              <CardContent className="p-3">
                <div className="flex items-center justify-between mb-2">
                  <Small className="text-[#00ff00] font-mono">CDN Link</Small>
                  <button
                    onClick={() => {
                      navigator.clipboard.writeText(uploadState.cdnUrl || "");
                      const btn = document.getElementById("copy-single-cdn-btn");
                      if (btn) {
                        btn.textContent = "Copied!";
                        setTimeout(() => { btn.textContent = "Copy"; }, 1500);
                      }
                    }}
                    id="copy-single-cdn-btn"
                    className="px-2 py-1 rounded bg-[#00ff00]/10 text-[#00ff00] text-[10px] font-mono hover:bg-[#00ff00]/20 transition-all flex items-center gap-1"
                  >
                    <ClipboardIcon size={10} /> Copy
                  </button>
                </div>
                <input
                  type="text"
                  readOnly
                  value={uploadState.cdnUrl}
                  onClick={(e) => (e.target as HTMLInputElement).select()}
                  className="w-full px-2 py-1.5 rounded bg-black border border-[#00ff00]/20 text-white font-mono text-xs"
                />
              </CardContent>
            </Card>
          )}

          {/* Share to Net Protocol Feed - Optional */}
          {showShareToFeed && (
            <Card className="bg-purple-500/10 border-2 border-purple-500/30 text-left">
              <CardContent className="p-4 space-y-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <span className="text-xl">📢</span>
                    <H4 className="text-purple-400 font-mono text-sm">Announce on Net Protocol?</H4>
                  </div>
                  <span className="text-[10px] font-mono text-gray-500 bg-gray-800 px-2 py-0.5 rounded">
                    OPTIONAL
                  </span>
                </div>
                <P className="text-gray-300 font-mono text-xs">
                  Share your upload to the Net Library feed so others can discover it.
                </P>
                <div className="bg-yellow-500/10 border border-yellow-500/20 rounded p-2">
                  <Small className="text-yellow-400/80 font-mono text-[10px] flex items-center gap-1">
                    <WarningIcon size={12} /> This requires an additional transaction with a small gas fee (~$0.01)
                  </Small>
                </div>
                <div className="flex gap-2">
                  <button
                    onClick={() => setShowShareToFeed(false)}
                    className="flex-1 py-2.5 rounded-lg bg-[#1a1a1a] text-gray-300 font-mono text-xs hover:bg-[#222] hover:text-white transition-all"
                  >
                    No Thanks
                  </button>
                  <button
                    onClick={handlePostToFeed}
                    disabled={isPostingToFeed}
                    className="flex-1 py-2.5 rounded-lg bg-purple-500 text-white font-mono text-xs font-bold hover:bg-purple-600 disabled:opacity-50 transition-all"
                  >
                    {isPostingToFeed ? "Posting..." : "Yes, Share ⛓️"}
                  </button>
                </div>
              </CardContent>
            </Card>
          )}

          {/* Feed post result */}
          {feedPostResult === "success" && (
            <Card className="bg-green-500/10 border border-green-500/30">
              <CardContent className="p-3 text-center">
                <Small className="text-green-400 font-mono">
                  ✓ Posted to Net Protocol feed!
                </Small>
              </CardContent>
            </Card>
          )}
          {feedPostResult === "error" && (
            <Card className="bg-red-500/10 border border-red-500/30">
              <CardContent className="p-3 text-center">
                <Small className="text-red-400 font-mono text-xs">
                  Failed to post to feed. You can try again later.
                </Small>
              </CardContent>
            </Card>
          )}

          {/* View/Play Content button for media types (audio, video, image) */}
          {uploadState.cdnUrl && lastUploadedContentType && lastUploadedContentType !== "pdf" && lastUploadedContentType !== "unknown" && (
            <button
              onClick={() => setShowMultimediaViewer(true)}
              className="w-full py-3 rounded-lg bg-cyan-500/20 border border-cyan-500/50 text-cyan-400 font-mono font-bold hover:bg-cyan-500/30 transition-all flex items-center justify-center gap-2"
            >
              <span className="text-xl">
                {lastUploadedContentType === "audio" ? "🎵" : lastUploadedContentType === "video" ? "🎬" : lastUploadedContentType === "image" ? "🖼️" : "📝"}
              </span>
              <span>
                {lastUploadedContentType === "audio" ? "Play Audio" : lastUploadedContentType === "video" ? "Play Video" : lastUploadedContentType === "image" ? "View Image" : "View Content"}
              </span>
            </button>
          )}

          {/* Share Social Receipt button */}
          {lastSocialReceiptData && (
            <button
              onClick={() => setShowSocialShareModal(true)}
              className="w-full py-3 rounded-lg bg-purple-500/20 border border-purple-500/50 text-purple-400 font-mono font-bold hover:bg-purple-500/30 transition-all flex items-center justify-center gap-2"
            >
              <ReceiptIcon size={18} />
              <ShareIcon size={14} />
              <span>Share Receipt</span>
            </button>
          )}

          <Button
            onClick={handleReset}
            className="bg-[#00ff00] text-black hover:bg-[#00dd00] font-mono mt-4"
          >
            Upload Another Item
          </Button>
        </div>
      )}

      {/* Multimedia Viewer for playing/viewing imported content */}
      {showMultimediaViewer && uploadState.cdnUrl && lastUploadedContentType && (
        <div className="fixed inset-0 z-50">
          <MultimediaViewer
            contentUrl={uploadState.cdnUrl}
            contentType={lastUploadedContentType}
            title={bookTitle || uploadState.fileName}
            author={authorName || "Unknown"}
            coverUrl={coverArtUrl || undefined}
            contentKey={lastUploadedContentKey || undefined}
            operatorAddress={walletAddress || undefined}
            onBack={() => setShowMultimediaViewer(false)}
            onShare={() => {
              // Copy link to clipboard
              navigator.clipboard.writeText(uploadState.cdnUrl || "").then(() => {
                alert("Link copied to clipboard!");
              });
            }}
          />
        </div>
      )}

      {/* Upload Log - shows history of upload attempts (at bottom of page) */}
      <UploadLog entries={uploadLog} onClear={clearUploadLog} />

      {/* Add Funds Modal - x402 USDC funding */}
      {gasEstimate && (
        <AddFundsModal
          isOpen={showAddFundsModal}
          onClose={() => {
            setShowAddFundsModal(false);
            setIsStandaloneAddFunds(false); // Reset flag when modal closes
          }}
          requiredAmount={gasEstimate.estimatedCostUsdc}
          currentBalance={gasEstimate.balanceUsdc}
          onFundWallet={fundWallet}
          onRecoverFunds={recoverUnverifiedPayments}
          isStandaloneAddFunds={isStandaloneAddFunds}
          onBalanceRefresh={async () => {
            // Re-check balance
            const balanceInfo = await getRelayBalance();
            if (!isStandaloneAddFunds && selectedFile) {
              // During upload - re-check with cost estimate
              try {
                const estimate = await estimateUploadCost(selectedFile);
                const balanceEth = estimate.balanceInfo?.balanceEth || 0;
                const balanceUsdc = estimate.balanceInfo?.balanceUsdc || 0;
                setGasEstimate({
                  estimatedCostEth: (estimate.estimatedCostEth || 0).toFixed(6),
                  estimatedCostUsdc: estimate.estimatedCostUsdc.toFixed(2),
                  balanceEth: balanceEth.toFixed(6),
                  balanceUsdc: balanceUsdc.toFixed(2),
                  sufficient: estimate.canProceed,
                  lowBalance: estimate.lowBalance,
                });
                // Close modal if now sufficient
                if (estimate.canProceed) {
                  setShowAddFundsModal(false);
                  setIsStandaloneAddFunds(false);
                }
              } catch (e) {
                console.error("Cost re-estimation failed:", e);
              }
            } else {
              // Standalone add funds - just update balance
              setGasEstimate({
                estimatedCostEth: "0",
                estimatedCostUsdc: "0",
                balanceEth: "0",
                balanceUsdc: balanceInfo?.balanceUsdc.toFixed(2) || "0.00",
                sufficient: balanceInfo?.sufficient || false,
              });
            }
          }}
          onFundingSuccess={() => {
            // Trigger balance refresh in the header
            setBalanceRefreshTrigger(prev => prev + 1);

            // Only auto-trigger upload if there's a file selected AND this wasn't standalone
            if (!isStandaloneAddFunds && selectedFile) {
              console.log("[Upload] Funding succeeded, auto-triggering upload");
              setShowAddFundsModal(false);
              setIsStandaloneAddFunds(false);
              setTimeout(() => {
                handleUpload();
              }, 500);
            } else {
              // Standalone funding - just close the modal
              console.log("[Upload] Funding succeeded (standalone)");
              setShowAddFundsModal(false);
              setIsStandaloneAddFunds(false);
            }
          }}
        />
      )}

      {/* Premium Upload Modal - handles file size overage only (Stack Pass for warmup is bought from profile) */}
      {selectedFile && (
        <PremiumUploadModal
          isOpen={showPremiumModal}
          onClose={() => setShowPremiumModal(false)}
          onPaymentComplete={async () => {
            setShowPremiumModal(false);
            setPremiumPaid(true);
          }}
          fileSize={selectedFile.size}
          fileName={selectedFile.name}
          paymentReason="file-size"
        />
      )}

      {/* Batch Upload Add Funds Modal - x402 USDC (simplified) */}
      {showBatchAddFundsModal && batchGasEstimate && (
        <div
          className="fixed inset-0 bg-black/90 flex items-center justify-center z-[10000] p-4"
          onClick={() => {
            setBatchFundingState({ loading: false, error: null });
            setShowBatchAddFundsModal(false);
          }}
        >
          <div
            className="bg-[#0a0a0a] border border-purple-500/30 rounded-lg p-4 w-full max-w-xs"
            onClick={(e) => e.stopPropagation()}
          >
            {/* Header */}
            <div className="flex items-center justify-between mb-3">
              <H4 className="text-purple-400 font-mono text-sm">Fund Upload Wallet</H4>
              <button
                onClick={() => {
                  setBatchFundingState({ loading: false, error: null });
                  setShowBatchAddFundsModal(false);
                }}
                className="w-6 h-6 rounded-full bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white text-xs"
              >
                ✕
              </button>
            </div>

            {/* Cost breakdown */}
            <div className="bg-black/50 border border-purple-500/20 rounded-lg p-3 mb-3">
              <Small className="text-gray-400 font-mono block mb-2">
                This upload costs <span className="text-white">~${batchGasEstimate.estimatedCostUsdc === "Unknown" ? "0.10" : Number(batchGasEstimate.estimatedCostUsdc).toFixed(2)}</span>
              </Small>
              <Small className="text-gray-400 font-mono block mb-2">
                Your relay balance: <span className="text-red-400">${Number(batchGasEstimate.balanceUsdc).toFixed(2)}</span>
              </Small>
            </div>

            {/* Funding amount selector - Net Protocol presets only */}
            <div className="bg-purple-500/10 border border-purple-500/30 rounded-lg p-3 mb-3">
              <Small className="text-purple-300 font-mono block mb-2 font-bold">
                How much USDC to add?
              </Small>
              <div className="flex gap-2">
                {[0.10, 0.25, 5.00].map((amt) => (
                  <button
                    key={amt}
                    type="button"
                    onClick={() => setFundingAmount(amt)}
                    className={`flex-1 py-3 rounded font-mono text-sm transition-all ${
                      fundingAmount === amt
                        ? "bg-purple-500 text-white border border-purple-400"
                        : "bg-[#1a1a1a] text-gray-400 hover:bg-[#222] hover:text-white border border-purple-500/20"
                    }`}
                  >
                    {amt < 1 ? `${(amt * 100).toFixed(0)}¢` : `$${amt.toFixed(2)}`}
                  </button>
                ))}
              </div>
              <Small className="text-gray-500 font-mono text-[9px] block mt-2 text-center">
                Funds go to your Upload Wallet for storage transactions
              </Small>
            </div>

            {/* Batch items summary - show all pending files */}
            {uploadQueue.filter(q => q.status === "pending" || q.status === "uploading").length > 0 && (
              <div className="bg-purple-500/10 border border-purple-500/20 rounded px-2 py-1.5 mb-3 max-h-24 overflow-y-auto">
                <Small className="text-purple-300/80 font-mono text-[10px] block mb-1">
                  📁 {uploadQueue.filter(q => q.status === "pending" || q.status === "uploading").length} file{uploadQueue.filter(q => q.status === "pending" || q.status === "uploading").length !== 1 ? "s" : ""} to upload:
                </Small>
                <div className="space-y-0.5">
                  {uploadQueue.filter(q => q.status === "pending" || q.status === "uploading").map((item, idx) => (
                    <Small key={item.id} className="text-gray-400 font-mono text-[9px] block truncate">
                      {idx + 1}. {item.title || item.file.name}
                    </Small>
                  ))}
                </div>
              </div>
            )}

            {/* Connected wallet info - collapsible with copy */}
            {isConnected && walletAddress && (
              <details className="mb-2">
                <summary className="bg-purple-500/10 border border-purple-500/20 rounded px-2 py-1.5 cursor-pointer list-none flex items-center justify-between">
                  <Small className="text-purple-300/80 font-mono text-[9px]">
                    💳 {walletAddress.slice(0, 6)}...{walletAddress.slice(-4)}
                  </Small>
                  <Small className="text-purple-400/60 font-mono text-[8px]">▼</Small>
                </summary>
                <div className="bg-black/30 border border-purple-500/10 border-t-0 rounded-b px-2 py-1.5">
                  <div className="flex items-center gap-2">
                    <Small className="text-white font-mono text-[7px] break-all flex-1 select-all">
                      {walletAddress}
                    </Small>
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        navigator.clipboard.writeText(walletAddress);
                      }}
                      className="shrink-0 px-1.5 py-0.5 bg-purple-500/20 hover:bg-purple-500/30 rounded text-purple-300 font-mono text-[8px] transition-colors"
                    >
                      Copy
                    </button>
                  </div>
                </div>
              </details>
            )}

            {/* Wallet connection warning */}
            {!isConnected && (
              <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-2 mb-3">
                <Small className="text-yellow-400 font-mono text-[10px] flex items-center gap-1"><WarningIcon size={12} /> Wallet not connected. Please reconnect to add funds.</Small>
              </div>
            )}

            {/* Error display - collapsible with copy */}
            {batchFundingState.error && (
              <details className="mb-3" open>
                <summary className="bg-red-500/10 border border-red-500/30 rounded px-2 py-1.5 cursor-pointer list-none flex items-center justify-between">
                  <Small className="text-red-400 font-mono text-[10px] flex items-center gap-1"><XCircleIcon size={10} /> Error occurred</Small>
                  <Small className="text-red-400/60 font-mono text-[8px]">▼</Small>
                </summary>
                <div className="bg-black/30 border border-red-500/10 border-t-0 rounded-b px-2 py-1.5">
                  <div className="flex items-start gap-2">
                    <Small className="text-red-300 font-mono text-[8px] break-all flex-1 select-all">
                      {batchFundingState.error}
                    </Small>
                    <button
                      type="button"
                      onClick={(e) => {
                        e.stopPropagation();
                        navigator.clipboard.writeText(batchFundingState.error || "");
                      }}
                      className="shrink-0 px-1.5 py-0.5 bg-red-500/20 hover:bg-red-500/30 rounded text-red-300 font-mono text-[8px] transition-colors"
                    >
                      Copy
                    </button>
                  </div>
                </div>
              </details>
            )}

            {/* Main action */}
            <button
              type="button"
              onClick={async (e) => {
                e.preventDefault();
                e.stopPropagation();
                console.log("[BATCH FUND] Button clicked, fundWallet:", typeof fundWallet, "address:", walletAddress);
                console.log("[BATCH FUND] User selected amount:", fundingAmount);
                setBatchFundingState({ loading: true, error: null });
                try {
                  const success = await fundWallet(fundingAmount);
                  console.log("[BATCH FUND] fundWallet result:", success);
                  if (success) {
                    setBalanceRefreshTrigger(prev => prev + 1); // Refresh header balance
                    setBatchFundingState({ loading: false, error: null });
                    setShowBatchAddFundsModal(false);
                    resumeBatchUpload();
                  } else {
                    // Funding returned false - try auto-recovery in case payment went through but verify failed
                    // This is common with Base App wallets that can dismiss quickly
                    console.log("[BATCH FUND] Funding returned false, attempting auto-recovery...");
                    const recoveryResult = await recoverPendingPayments();
                    if (recoveryResult.recovered > 0) {
                      console.log("[BATCH FUND] Auto-recovery succeeded!");
                      setBalanceRefreshTrigger(prev => prev + 1); // Refresh header balance
                      setBatchFundingState({ loading: false, error: null });
                      setShowBatchAddFundsModal(false);
                      resumeBatchUpload();
                      return;
                    }
                    // Check actual balance to provide better error
                    const _balanceInfo = await getRelayBalance();
                    setBatchFundingState({
                      loading: false,
                      error: `Funding failed. Connected wallet: ${walletAddress?.slice(0, 6)}...${walletAddress?.slice(-4)}. Check console for details.`
                    });
                  }
                } catch (err) {
                  console.error("[BATCH FUND] fundWallet error:", err);
                  const errMsg = err instanceof Error ? err.message : "Funding failed. Please try again.";

                  // Auto-recovery on error: payment may have succeeded but verify failed
                  // This is critical for Base App wallets that dismiss quickly
                  console.log("[BATCH FUND] Attempting auto-recovery after error...");
                  try {
                    const recoveryResult = await recoverPendingPayments();
                    if (recoveryResult.recovered > 0) {
                      console.log("[BATCH FUND] Auto-recovery succeeded after error!");
                      setBalanceRefreshTrigger(prev => prev + 1); // Refresh header balance
                      setBatchFundingState({ loading: false, error: null });
                      setShowBatchAddFundsModal(false);
                      resumeBatchUpload();
                      return;
                    }
                  } catch (recoveryErr) {
                    console.warn("[BATCH FUND] Auto-recovery failed:", recoveryErr);
                  }

                  setBatchFundingState({
                    loading: false,
                    error: errMsg
                  });
                }
              }}
              disabled={batchFundingState.loading || !isConnected}
              className="w-full py-3 rounded-lg bg-purple-500 text-white font-mono text-sm font-bold hover:bg-purple-600 transition-all mb-3 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {batchFundingState.loading ? (
                <span className="flex items-center justify-center gap-2">
                  <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
                  Sending {fundingAmount < 1 ? `${(fundingAmount * 100).toFixed(0)}¢` : `$${fundingAmount.toFixed(2)}`} USDC...
                </span>
              ) : (
                `Add ${fundingAmount < 1 ? `${(fundingAmount * 100).toFixed(0)}¢` : `$${fundingAmount.toFixed(2)}`} USDC`
              )}
            </button>

            {/* Secondary actions */}
            <div className="flex gap-2 mb-3">
              <button
                onClick={resumeBatchUpload}
                className="flex-1 py-2 rounded bg-[#1a1a1a] text-gray-400 font-mono text-[10px] hover:text-white hover:bg-[#222] transition-all"
              >
                Check & Resume
              </button>
              <a
                href="https://app.uniswap.org/swap?chain=base&outputCurrency=0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
                target="_blank"
                rel="noopener noreferrer"
                className="flex-1 py-2 rounded bg-[#1a1a1a] text-center text-gray-400 font-mono text-[10px] hover:text-white hover:bg-[#222] transition-all"
              >
                Get USDC ↗
              </a>
            </div>

            {/* Progress so far - only if relevant */}
            {uploadQueue.filter(q => q.status === "complete").length > 0 && (
              <Small className="text-green-400/60 font-mono text-[10px] text-center block mb-2">
                ✓ {uploadQueue.filter(q => q.status === "complete").length} uploaded
              </Small>
            )}

            {/* Cancel */}
            <button
              onClick={cancelBatchUpload}
              className="w-full py-2 text-gray-500 font-mono text-[10px] hover:text-gray-300 transition-colors"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      {/* Hidden cover image input - always rendered so Change button works in all states */}
      {/* Position absolute with negative offscreen to ensure no accidental touch interactions on mobile */}
      <input
        ref={coverInputRef}
        type="file"
        accept="image/*"
        onChange={handleCoverUpload}
        className="sr-only"
        style={{ position: 'absolute', left: '-9999px', top: '-9999px' }}
        tabIndex={-1}
        aria-hidden="true"
      />

      {/* Cover Upload Modal */}
      {showCoverUpload && (
        <div
          className="fixed inset-0 bg-black/90 flex items-center justify-center z-50 p-4"
          onClick={() => setShowCoverUpload(false)}
        >
          <div
            className="bg-[#0a0a0a] border border-[#00ff00]/30 rounded-lg p-4 w-full max-w-xs"
            onClick={(e) => e.stopPropagation()}
          >
            <H4 className="text-[#00ff00] font-mono mb-3">🖼️ Upload Cover Art</H4>
            <Small className="text-gray-400 font-mono mb-3 block">
              Select an image for your book cover. If no cover is provided, the Net Library crest will be used.
            </Small>
            <button
              type="button"
              onClick={() => coverInputRef.current?.click()}
              className="w-full py-4 min-h-[56px] border-2 border-dashed border-[#00ff00]/30 rounded-lg text-center hover:border-[#00ff00] hover:bg-[#00ff00]/5 transition-all mb-3"
            >
              <span className="text-3xl block mb-1">🖼️</span>
              <Small className="text-[#00ff00] font-mono">Tap to select image</Small>
            </button>
            <button
              type="button"
              onClick={() => setShowCoverUpload(false)}
              className="w-full py-2 min-h-[44px] rounded bg-[#1a1a1a] text-gray-400 font-mono text-sm hover:bg-[#222] hover:text-[#00ff00]"
            >
              Cancel
            </button>
          </div>
        </div>
      )}

      {/* File Preview Modal - shows before metadata form */}
      {previewFile && (
        <FilePreviewModal
          file={previewFile}
          isOpen={showPreviewModal}
          onClose={handlePreviewClose}
          onContinue={handlePreviewContinue}
        />
      )}

      {/* Social Receipt Share Modal */}
      {showSocialShareModal && lastSocialReceiptData && (
        <SocialReceiptShareModal
          isOpen={showSocialShareModal}
          onClose={() => setShowSocialShareModal(false)}
          platform={lastSocialReceiptData.platform}
          author={lastSocialReceiptData.author}
          contentKey={lastSocialReceiptData.contentKey}
          receiptImageUrl={uploadState.cdnUrl}
        />
      )}

    </div>
  );
}
src/features/app/components/upload-wallet-balance.tsx
"use client";

import { useState, useEffect, useCallback } from "react";
import { Small } from "@neynar/ui";
import { WarningIcon, MoneyIcon, SmartphoneIcon, CircleFilledIcon, GlobeIcon } from "@/components/icons/net-library-icons";
import { useSimplePrice } from "@/neynar-web-sdk/src/coingecko/api-hooks/hooks/simple";

interface UploadWalletBalanceProps {
  walletAddress: string | undefined;
  onAddFunds?: () => void;
  /** Increment this to trigger a balance refresh from parent */
  refreshTrigger?: number;
}

// Store dismissed state in localStorage
const ADVANCED_INFO_DISMISSED_KEY = "upload-wallet-advanced-dismissed";

// Minimum USD balance required for uploads ($0.10)
const MIN_BALANCE_USD = 0.10;

interface BalanceInfo {
  balanceEth: number;  // Actual ETH in backend wallet
  balanceUsd: number;  // Real USD value based on live ETH price
  backendWalletAddress: string;
  sufficient: boolean; // Is balance >= MIN_BALANCE_USD
}

/**
 * Upload Wallet Balance Header
 * Shows the user's Upload Wallet balance persistently at the top of the upload tab.
 * Includes an info button explaining what the Upload Wallet is.
 * Uses live ETH price from CoinGecko for accurate USD conversion.
 */
export function UploadWalletBalance({ walletAddress, onAddFunds, refreshTrigger }: UploadWalletBalanceProps) {
  const [balance, setBalance] = useState<BalanceInfo | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [showInfo, setShowInfo] = useState(false);
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [advancedDismissed, setAdvancedDismissed] = useState(false);

  // Check if user has previously dismissed the advanced info
  useEffect(() => {
    if (typeof window !== "undefined") {
      const dismissed = localStorage.getItem(ADVANCED_INFO_DISMISSED_KEY);
      setAdvancedDismissed(dismissed === "true");
    }
  }, []);

  const handleDismissAdvanced = () => {
    setAdvancedDismissed(true);
    localStorage.setItem(ADVANCED_INFO_DISMISSED_KEY, "true");
  };

  // Fetch live ETH price from CoinGecko (refreshes every 30 seconds)
  const { data: ethPriceData } = useSimplePrice(
    ['ethereum'],
    ['usd'],
    {},
    {
      refetchInterval: 30000, // Refresh price every 30 seconds
      staleTime: 15000, // Consider stale after 15 seconds
    }
  );
  const ethPriceUsd = ethPriceData?.ethereum?.usd || 0;

  const fetchBalance = useCallback(async () => {
    if (!walletAddress) {
      setIsLoading(false);
      return;
    }

    try {
      setError(null);
      const response = await fetch("/api/relay/balance", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          operatorAddress: walletAddress,
          chainId: 8453, // Base
        }),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({ error: "Unknown error" }));
        throw new Error(errorData.error || `API error: ${response.status}`);
      }

      const result = await response.json();

      if (!result.success && result.error) {
        throw new Error(result.error);
      }

      // The relay backend wallet stores ETH (for gas)
      // Users fund with USDC which the relay converts to ETH
      const balanceEth = parseFloat(result.balanceEth || "0");

      // Calculate USD value using live ETH price
      const balanceUsd = ethPriceUsd > 0 ? balanceEth * ethPriceUsd : 0;

      // Check if balance is sufficient (>= $0.10 minimum)
      const sufficient = balanceUsd >= MIN_BALANCE_USD;

      setBalance({
        balanceEth,
        balanceUsd,
        backendWalletAddress: result.backendWalletAddress,
        sufficient,
      });
    } catch (err) {
      console.error("[UploadWalletBalance] Error fetching balance:", err);
      setError(err instanceof Error ? err.message : "Failed to load balance");
    } finally {
      setIsLoading(false);
    }
  }, [walletAddress, ethPriceUsd]);

  // Initial fetch on mount
  useEffect(() => {
    fetchBalance();
  }, [fetchBalance]);

  // Auto-refresh every 30 seconds when visible
  useEffect(() => {
    const interval = setInterval(() => {
      if (document.visibilityState === "visible") {
        fetchBalance();
      }
    }, 30000);

    return () => clearInterval(interval);
  }, [fetchBalance]);

  // Refresh when parent triggers (e.g., after funding)
  useEffect(() => {
    if (refreshTrigger && refreshTrigger > 0) {
      fetchBalance();
    }
  }, [refreshTrigger, fetchBalance]);

  // Don't show if no wallet connected
  if (!walletAddress) {
    return null;
  }

  return (
    <>
      {/* Balance Header */}
      <div className="bg-gradient-to-r from-purple-500/10 via-purple-500/5 to-transparent border border-purple-500 rounded-lg p-3 mb-4">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <MoneyIcon size={20} className="text-purple-400" />
            <div>
              <div className="flex items-center gap-1.5">
                <Small className="text-purple-300 font-mono font-bold text-xs">
                  Upload Wallet
                </Small>
                <button
                  onClick={() => setShowInfo(true)}
                  className="w-4 h-4 rounded-full bg-purple-500/20 text-purple-400 text-[10px] flex items-center justify-center hover:bg-purple-500/30 transition-colors"
                  title="What is this?"
                >
                  ?
                </button>
              </div>
              {isLoading ? (
                <div className="flex items-center gap-1">
                  <div className="w-3 h-3 border border-purple-400/30 border-t-purple-400 rounded-full animate-spin" />
                  <Small className="text-purple-400/50 font-mono text-[10px]">Loading...</Small>
                </div>
              ) : error ? (
                <Small className="text-red-400 font-mono text-[10px]">{error}</Small>
              ) : balance ? (
                <div className="flex items-center gap-1.5">
                  {/* Primary: ETH balance with USD value */}
                  <Small className={`font-mono text-sm font-bold ${
                    balance.sufficient ? "text-[#9ca3af]" : "text-red-400"
                  }`}>
                    {balance.balanceEth.toFixed(6)} ETH
                  </Small>
                  {/* USD value in parentheses */}
                  {ethPriceUsd > 0 && (
                    <Small className="font-mono text-xs text-gray-500">
                      (${balance.balanceUsd.toFixed(2)})
                    </Small>
                  )}
                  {/* Warning emoji - tappable when balance is low */}
                  {!balance.sufficient && (
                    <button
                      onClick={() => setShowInfo(true)}
                      className="text-sm hover:scale-110 transition-transform"
                      title="Balance below minimum"
                    >
                      <WarningIcon size={14} className="text-yellow-400" />
                    </button>
                  )}
                </div>
              ) : (
                <Small className="text-gray-500 font-mono text-[10px]">--</Small>
              )}
            </div>
          </div>

          <div className="flex items-center gap-2">
            {/* Refresh button */}
            <button
              onClick={() => {
                setIsLoading(true);
                fetchBalance();
              }}
              disabled={isLoading}
              className="p-1.5 rounded bg-purple-500/10 text-purple-400/70 hover:text-purple-400 hover:bg-purple-500/20 transition-colors disabled:opacity-50"
              title="Refresh balance"
            >
              <svg
                className={`w-3.5 h-3.5 ${isLoading ? "animate-spin" : ""}`}
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  strokeWidth={2}
                  d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
                />
              </svg>
            </button>

            {/* Add Funds button */}
            {onAddFunds && (
              <button
                onClick={onAddFunds}
                className={`px-3 py-1.5 rounded-lg font-mono text-xs font-bold transition-all ${
                  balance && !balance.sufficient
                    ? "bg-red-500 text-white hover:bg-red-600"
                    : "bg-purple-500 text-white hover:bg-purple-600"
                }`}
              >
                + Add Funds
              </button>
            )}
          </div>
        </div>

      </div>

      {/* Info Modal */}
      {showInfo && (
        <div
          className="fixed inset-0 bg-black/90 flex items-center justify-center z-50 p-4"
          onClick={() => setShowInfo(false)}
        >
          <div
            className="bg-[#0a0a0a] border border-purple-500/30 rounded-lg p-4 w-full max-w-sm max-h-[80vh] overflow-y-auto"
            onClick={(e) => e.stopPropagation()}
          >
            <div className="flex items-center justify-between mb-4">
              <h3 className="text-purple-400 font-mono font-bold text-sm flex items-center gap-2">
                <MoneyIcon size={16} /> Upload Wallet
              </h3>
              <button
                onClick={() => setShowInfo(false)}
                className="w-6 h-6 rounded-full bg-[#1a1a1a] flex items-center justify-center text-gray-400 hover:text-white text-xs"
              >
                ✕
              </button>
            </div>

            <div className="space-y-4 text-xs font-mono">
              <div>
                <h4 className="text-[#00ff00] font-bold mb-1">What is it?</h4>
                <p className="text-gray-300 leading-relaxed">
                  Your Upload Wallet is a special wallet that pays for storing files onchain.
                  Instead of signing 10-15 transactions per upload, you fund it once and
                  uploads happen automatically.
                </p>
              </div>

              <div>
                <h4 className="text-[#00ff00] font-bold mb-1">Why USDC → ETH?</h4>
                <p className="text-gray-300 leading-relaxed">
                  You fund with <span className="text-blue-400">USDC</span> (stable, predictable cost),
                  but the balance shows in <span className="text-purple-400">ETH</span> because
                  that&apos;s what pays for onchain transactions (gas). The relay automatically
                  converts your USDC to ETH at market rate when you fund.
                </p>
              </div>

              <div>
                <h4 className="text-[#00ff00] font-bold mb-1">How does it work?</h4>
                <p className="text-gray-300 leading-relaxed">
                  1. You pay USDC to fund your Upload Wallet<br/>
                  2. The x402 protocol converts USDC → ETH automatically<br/>
                  3. A backend wallet (unique to you) stores the ETH<br/>
                  4. That wallet pays gas for all your uploads<br/>
                  5. No more signing every transaction!
                </p>
              </div>

              <div>
                <h4 className="text-[#00ff00] font-bold mb-1">How much to fund?</h4>
                <ul className="text-gray-300 space-y-1">
                  <li>• <span className="text-yellow-400">10¢</span> — A few test uploads</li>
                  <li>• <span className="text-yellow-400">25¢</span> — ~10-25 small uploads</li>
                  <li>• <span className="text-[#00ff00]">$5</span> — ~200+ uploads (recommended)</li>
                </ul>
              </div>

              <div>
                <h4 className="text-[#00ff00] font-bold mb-1">Is it safe?</h4>
                <p className="text-gray-300 leading-relaxed">
                  Yes! The backend wallet can ONLY pay for Net Protocol storage transactions.
                  It cannot transfer funds anywhere else. Your funds are secured by the x402 protocol.
                </p>
              </div>

              <div className="bg-purple-500/10 border border-purple-500/20 rounded p-2">
                <h4 className="text-purple-400 font-bold mb-1">Your Backend Wallet</h4>
                {balance?.backendWalletAddress ? (
                  <p className="text-gray-400 text-[10px] break-all select-all">
                    {balance.backendWalletAddress}
                  </p>
                ) : (
                  <p className="text-gray-500 text-[10px]">Connect wallet to see address</p>
                )}
              </div>

              {/* Expandable Advanced Section */}
              {!showAdvanced ? (
                <button
                  onClick={() => setShowAdvanced(true)}
                  className="w-full py-2 text-center text-purple-400 hover:text-purple-300 text-[10px] font-mono border-t border-purple-500/20 mt-2"
                >
                  ▶ Using multiple apps? Learn more...
                </button>
              ) : (
                <div className="border-t border-purple-500/20 pt-3 mt-2 space-y-3">
                  <div className="flex items-center justify-between">
                    <h4 className="text-orange-400 font-bold text-xs">Multi-App Access</h4>
                    <button
                      onClick={() => setShowAdvanced(false)}
                      className="text-gray-500 hover:text-gray-400 text-[10px]"
                    >
                      ▼ Hide
                    </button>
                  </div>

                  <div className="bg-orange-500/10 border border-orange-500/20 rounded p-2.5">
                    <p className="text-gray-300 leading-relaxed text-[11px] mb-2">
                      <span className="text-orange-400 font-bold">Important:</span> Your Upload Wallet balance is tied to whichever wallet you connect with.
                    </p>
                    <ul className="text-gray-400 text-[10px] space-y-1.5">
                      <li className="flex items-start gap-1.5">
                        <SmartphoneIcon size={14} className="text-purple-400 mt-0.5 flex-shrink-0" />
                        <span><span className="text-purple-300">Warpcast</span> connects your Farcaster wallet</span>
                      </li>
                      <li className="flex items-start gap-1.5">
                        <CircleFilledIcon size={14} className="text-blue-400 mt-0.5 flex-shrink-0" />
                        <span><span className="text-blue-300">Coinbase Wallet</span> connects your Coinbase wallet</span>
                      </li>
                      <li className="flex items-start gap-1.5">
                        <GlobeIcon size={14} className="text-green-400 mt-0.5 flex-shrink-0" />
                        <span><span className="text-green-300">Web Browser</span> connects via WalletConnect</span>
                      </li>
                    </ul>
                  </div>

                  <div className="text-gray-400 text-[10px] leading-relaxed">
                    <p className="mb-1.5">
                      If these are <span className="text-white">different wallets</span>, each will have its own Upload Wallet balance.
                    </p>
                    <p>
                      <span className="text-[#00ff00]">Good news:</span> Your library and uploads are shared across all platforms — only the funding balance is wallet-specific.
                    </p>
                  </div>

                  {!advancedDismissed && (
                    <button
                      onClick={handleDismissAdvanced}
                      className="w-full py-1.5 text-[10px] text-gray-500 hover:text-gray-400 font-mono"
                    >
                      Don&apos;t show this again
                    </button>
                  )}
                </div>
              )}

              <div className="text-center pt-2 border-t border-purple-500/20">
                <a
                  href="https://docs.cdp.coinbase.com/x402/docs/overview"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="text-purple-400 hover:text-purple-300 underline text-[10px]"
                >
                  Learn more about x402 protocol →
                </a>
              </div>
            </div>

            <button
              onClick={() => setShowInfo(false)}
              className="w-full mt-4 py-2.5 rounded-lg bg-purple-500 text-white font-mono text-sm font-bold hover:bg-purple-600 transition-all"
            >
              Got it!
            </button>
          </div>
        </div>
      )}
    </>
  );
}
src/features/app/components/upvote-button.tsx
"use client";

import { useState, useEffect } from "react";
import { useUpvote, UPVOTE_COST_ETH } from "@/hooks/use-upvotes";
import { useAccount } from "wagmi";
import { UpvoteModal } from "./upvote-modal";

interface UpvoteButtonProps {
  contentKey: string;
  operatorAddress: string;
  upvoteCount: number;
  title?: string;
  onSuccess?: () => void;
  compact?: boolean;
  /** Inline mode: single-click upvote without modal, ideal for list views */
  inline?: boolean;
}

export function UpvoteButton({
  contentKey,
  operatorAddress,
  upvoteCount,
  title = "Item",
  onSuccess,
  compact = false,
  inline = false,
}: UpvoteButtonProps) {
  const { isConnected } = useAccount();
  const { upvote, isUpvoting, isConfirmed, reset } = useUpvote();
  const [showModal, setShowModal] = useState(false);
  const [localUpvotes, setLocalUpvotes] = useState(0);

  const handleUpvote = async (count: number) => {
    const success = await upvote(contentKey, operatorAddress, count);
    if (success) {
      setLocalUpvotes((prev) => prev + count);
      setShowModal(false);
    }
  };

  // When transaction is confirmed, trigger success callback
  useEffect(() => {
    if (isConfirmed) {
      const timer = setTimeout(() => {
        reset();
        onSuccess?.();
      }, 2000);
      return () => clearTimeout(timer);
    }
  }, [isConfirmed, onSuccess, reset]);

  const displayUpvotes = upvoteCount + localUpvotes;

  // Inline version - single-click upvote without modal (for list views)
  if (inline) {
    const handleInlineUpvote = async (e: React.MouseEvent) => {
      e.stopPropagation();
      if (!isConnected || isUpvoting) return;

      const success = await upvote(contentKey, operatorAddress, 1);
      if (success) {
        setLocalUpvotes((prev) => prev + 1);
      }
    };

    return (
      <button
        onClick={handleInlineUpvote}
        disabled={!isConnected || isUpvoting}
        className={`flex items-center gap-1 px-2 py-1 rounded transition-colors ${
          isUpvoting
            ? "bg-[#00ff00]/30 cursor-wait animate-pulse"
            : isConnected
            ? "bg-[#1a1a1a] hover:bg-[#00ff00]/20 hover:scale-105"
            : "bg-[#1a1a1a] opacity-50"
        }`}
        title={
          isConnected
            ? `Upvote ${title} (${UPVOTE_COST_ETH} ETH)`
            : "Connect wallet to upvote"
        }
      >
        <span className={`text-sm ${isUpvoting ? "animate-bounce" : ""}`}>▲</span>
        <span className="text-[#00ff00] text-xs font-mono">{displayUpvotes}</span>
      </button>
    );
  }

  // Compact version - just the count with arrow
  if (compact) {
    return (
      <>
        <button
          onClick={(e) => {
            e.stopPropagation();
            if (isConnected) {
              setShowModal(true);
            }
          }}
          disabled={!isConnected || isUpvoting}
          className={`flex items-center gap-1 px-2 py-1 rounded transition-colors ${
            isUpvoting
              ? "bg-[#00ff00]/20 cursor-wait"
              : "bg-[#1a1a1a] hover:bg-[#00ff00]/20"
          } disabled:opacity-50`}
          title={isConnected ? "Upvote" : "Connect wallet to upvote"}
        >
          <span className="text-[#00ff00] text-sm">▲</span>
          <span className="text-[#00ff00] text-xs font-mono">{displayUpvotes}</span>
        </button>

        <UpvoteModal
          isOpen={showModal}
          onClose={() => setShowModal(false)}
          onUpvote={handleUpvote}
          isUpvoting={isUpvoting}
          bookTitle={title}
          currentUpvotes={displayUpvotes}
        />
      </>
    );
  }

  return (
    <>
      {/* Upvote button */}
      <button
        onClick={(e) => {
          e.stopPropagation();
          if (isConnected) {
            setShowModal(true);
          }
        }}
        disabled={!isConnected || isUpvoting}
        className={`w-10 h-10 rounded-lg flex flex-col items-center justify-center transition-all ${
          isUpvoting
            ? "bg-[#00ff00]/20 text-[#00ff00] cursor-wait"
            : "bg-[#1a1a1a] text-[#00ff00] hover:bg-[#00ff00]/20"
        } disabled:opacity-50`}
        title={isConnected ? "Upvote" : "Connect wallet to upvote"}
      >
        <span className="text-sm">▲</span>
        <span className="text-[8px] font-mono leading-none">{displayUpvotes}</span>
      </button>

      {/* Upvote Modal */}
      <UpvoteModal
        isOpen={showModal}
        onClose={() => setShowModal(false)}
        onUpvote={handleUpvote}
        isUpvoting={isUpvoting}
        bookTitle={title}
        currentUpvotes={displayUpvotes}
      />
    </>
  );
}
src/features/app/components/upvote-modal.tsx
"use client";

import { useState, useMemo } from "react";
import { Button, P, Small, H4 } from "@neynar/ui";
import { UPVOTE_COST_ETH } from "@/hooks/use-upvotes";

// Current ETH price in USD (could be fetched from an API in the future)
const ETH_PRICE_USD = 2500;

interface UpvoteModalProps {
  isOpen: boolean;
  onClose: () => void;
  onUpvote: (count: number) => void;
  isUpvoting: boolean;
  bookTitle: string;
  currentUpvotes: number;
}

type InputMode = "count" | "eth" | "usdc";

const PRESET_AMOUNTS = [1, 10, 100, 1000];

export function UpvoteModal({
  isOpen,
  onClose,
  onUpvote,
  isUpvoting,
  bookTitle,
  currentUpvotes,
}: UpvoteModalProps) {
  const [selectedPreset, setSelectedPreset] = useState<number | "custom">(1);
  const [customAmount, setCustomAmount] = useState("");
  const [inputMode, setInputMode] = useState<InputMode>("count");

  // Calculate upvote count based on input mode
  const upvoteCount = useMemo(() => {
    if (selectedPreset !== "custom") {
      return selectedPreset;
    }

    const value = parseFloat(customAmount) || 0;
    if (value <= 0) return 0;

    switch (inputMode) {
      case "count":
        return Math.floor(value);
      case "eth":
        // ETH amount / cost per upvote
        return Math.floor(value / UPVOTE_COST_ETH);
      case "usdc": {
        // Convert USDC to ETH, then to upvotes
        const ethValue = value / ETH_PRICE_USD;
        return Math.floor(ethValue / UPVOTE_COST_ETH);
      }
      default:
        return 0;
    }
  }, [selectedPreset, customAmount, inputMode]);

  // Calculate total cost in ETH
  const totalCostEth = upvoteCount * UPVOTE_COST_ETH;
  const totalCostUsd = totalCostEth * ETH_PRICE_USD;

  const handleSubmit = () => {
    if (upvoteCount > 0) {
      onUpvote(upvoteCount);
    }
  };

  const handlePresetClick = (amount: number) => {
    setSelectedPreset(amount);
    setCustomAmount("");
  };

  const handleCustomClick = () => {
    setSelectedPreset("custom");
    setInputMode("count");
    setCustomAmount("");
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl w-full max-w-sm overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 py-3 border-b border-[#00ff00]/20 flex items-center justify-between">
          <H4 className="text-[#00ff00] font-mono">▲ Upvote</H4>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors"
          >
            ✕
          </button>
        </div>

        {/* Content */}
        <div className="p-4 space-y-4">
          {/* Explanation banner */}
          <div className="bg-purple-500/10 border border-purple-500/30 rounded-lg p-3">
            <div className="flex items-start gap-2">
              <span className="text-purple-400 text-lg">⛓️</span>
              <div>
                <P className="text-purple-300 font-mono text-xs font-bold">Onchain Tips</P>
                <Small className="text-purple-300/70 font-mono text-[10px] leading-tight block mt-0.5">
                  Upvotes are permanent onchain tips stored forever on Net Protocol. Your support directly rewards the creator!
                </Small>
              </div>
            </div>
          </div>

          {/* Book info */}
          <div className="text-center">
            <P className="text-white font-mono text-sm truncate">{bookTitle}</P>
            <Small className="text-gray-500 font-mono">Currently: {currentUpvotes} upvotes</Small>
          </div>

          {/* Preset amounts */}
          <div className="grid grid-cols-4 gap-2">
            {PRESET_AMOUNTS.map((amount) => (
              <button
                key={amount}
                onClick={() => handlePresetClick(amount)}
                className={`py-3 rounded-lg font-mono text-sm font-bold transition-all ${
                  selectedPreset === amount
                    ? "bg-[#00ff00] text-black"
                    : "bg-[#1a1a1a] text-white border border-[#333] hover:border-[#00ff00]/50"
                }`}
              >
                {amount}
              </button>
            ))}
          </div>

          {/* Custom amount button */}
          <button
            onClick={handleCustomClick}
            className={`w-full py-3 rounded-lg font-mono text-sm font-bold transition-all ${
              selectedPreset === "custom"
                ? "bg-[#00ff00] text-black"
                : "bg-[#1a1a1a] text-white border border-[#333] hover:border-[#00ff00]/50"
            }`}
          >
            Custom Amount
          </button>

          {/* Custom input section */}
          {selectedPreset === "custom" && (
            <div className="space-y-3">
              {/* Input mode selector */}
              <div className="flex gap-1 bg-[#1a1a1a] rounded-lg p-1">
                {[
                  { mode: "count" as InputMode, label: "# Upvotes" },
                  { mode: "eth" as InputMode, label: "ETH" },
                  { mode: "usdc" as InputMode, label: "USDC" },
                ].map(({ mode, label }) => (
                  <button
                    key={mode}
                    onClick={() => {
                      setInputMode(mode);
                      setCustomAmount("");
                    }}
                    className={`flex-1 py-2 rounded-md font-mono text-xs transition-all ${
                      inputMode === mode
                        ? "bg-[#00ff00]/20 text-[#00ff00]"
                        : "text-gray-400 hover:text-white"
                    }`}
                  >
                    {label}
                  </button>
                ))}
              </div>

              {/* Input field */}
              <div className="relative">
                <input
                  type="number"
                  value={customAmount}
                  onChange={(e) => setCustomAmount(e.target.value)}
                  placeholder={
                    inputMode === "count"
                      ? "Enter number of upvotes"
                      : inputMode === "eth"
                      ? "Enter ETH amount"
                      : "Enter USDC amount"
                  }
                  className="w-full px-4 py-3 bg-[#1a1a1a] border border-[#333] rounded-lg text-white font-mono text-sm placeholder-gray-500 focus:outline-none focus:border-[#00ff00]/50"
                  min="0"
                  step={inputMode === "count" ? "1" : "0.0001"}
                />
                {inputMode !== "count" && customAmount && upvoteCount > 0 && (
                  <div className="absolute right-3 top-1/2 -translate-y-1/2">
                    <Small className="text-[#00ff00] font-mono">
                      = {upvoteCount} upvote{upvoteCount !== 1 ? "s" : ""}
                    </Small>
                  </div>
                )}
              </div>
            </div>
          )}

          {/* Cost summary */}
          {upvoteCount > 0 && (
            <div className="bg-[#1a1a1a] rounded-lg p-3 space-y-1">
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">Upvotes</Small>
                <Small className="text-white font-mono font-bold">{upvoteCount}</Small>
              </div>
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">Cost</Small>
                <Small className="text-[#00ff00] font-mono font-bold">
                  {totalCostEth.toFixed(6)} ETH
                </Small>
              </div>
              <div className="flex justify-between">
                <Small className="text-gray-400 font-mono">≈ USD</Small>
                <Small className="text-gray-400 font-mono">
                  ${totalCostUsd.toFixed(2)}
                </Small>
              </div>
            </div>
          )}

          {/* Submit button */}
          <Button
            onClick={handleSubmit}
            disabled={isUpvoting || upvoteCount === 0}
            className={`w-full h-12 font-mono font-bold ${
              isUpvoting
                ? "bg-[#00ff00]/20 text-[#00ff00] cursor-wait"
                : upvoteCount === 0
                ? "bg-gray-600 text-gray-400 cursor-not-allowed"
                : "bg-[#00ff00] text-black hover:bg-[#00dd00]"
            }`}
          >
            {isUpvoting ? (
              "Processing..."
            ) : upvoteCount === 0 ? (
              "Select Amount"
            ) : (
              `▲ Upvote ${upvoteCount}x`
            )}
          </Button>

          {/* Info */}
          <Small className="text-gray-500 font-mono text-center block text-[10px]">
            Each upvote costs {UPVOTE_COST_ETH} ETH (~${(UPVOTE_COST_ETH * ETH_PRICE_USD).toFixed(4)})
          </Small>
        </div>
      </div>
    </div>
  );
}
src/features/app/components/user-content-popover.tsx
"use client";

import { useState, useMemo } from "react";
import { Small } from "@neynar/ui";
import { useDiscoveryContext } from "@/contexts/discovery-context";
import { useStacks } from "@/hooks/use-stacks";
import { useGrids } from "@/hooks/use-grids";
import { LibraryIcon } from "@/components/icons/net-library-icons";
import { CoverImage } from "./cover-image";

// Get best cover URL - prefers coverUrl, falls back to cdnUrl for visual content
function getEffectiveCoverUrl(entry: { coverUrl?: string; cdnUrl?: string; mediaType?: string }): string {
  // If explicit cover art is set, use it
  if (entry.coverUrl) {
    return entry.coverUrl;
  }

  // For image/video content, cdnUrl IS the visual content - use it as thumbnail
  if (entry.cdnUrl && entry.mediaType && ["image", "video"].includes(entry.mediaType)) {
    return entry.cdnUrl;
  }

  return '';
}

interface UserContentPopoverProps {
  isOpen: boolean;
  onClose: () => void;
  /** Wallet address of the user to show content for */
  address: string;
  /** Optional username for display */
  username?: string;
  /** Optional profile picture URL */
  pfpUrl?: string;
  /** Optional FID for Farcaster users */
  fid?: number;
}

/**
 * Lightweight popover showing a user's uploads, stacks, and grids
 * Used when tapping on any user's PFP throughout the app
 */
export function UserContentPopover({
  isOpen,
  onClose,
  address,
  username,
  pfpUrl,
}: UserContentPopoverProps) {
  const [activeTab, setActiveTab] = useState<"uploads" | "stacks" | "grids">("uploads");

  // Get user's content
  const { entries } = useDiscoveryContext();
  const { stacks: userStacks } = useStacks({ owner: address, enabled: isOpen });
  const { grids: userGrids } = useGrids({ creator: address });

  // Filter uploads for this user — hidden items are invisible everywhere except the
  // owner's own hidden feed. They must not appear here or be counted in the tab badge.
  // Check uploaderAddress first — relay uploads store the backend wallet as `operator`
  // and the actual user's wallet as `uploaderAddress`. Fall back to operator for legacy entries.
  const userUploads = useMemo(() => {
    if (!address) return [];
    const addr = address.toLowerCase();
    return entries.filter(
      (e) =>
        !e.hidden && (
          (e.uploaderAddress && e.uploaderAddress.toLowerCase() === addr) ||
          (e.operator && e.operator.toLowerCase() === addr)
        )
    );
  }, [entries, address]);

  if (!isOpen) return null;

  const displayName = username || `${address.slice(0, 6)}...${address.slice(-4)}`;

  return (
    <div
      className="fixed inset-0 bg-black/90 z-[60] flex items-center justify-center p-4"
      onClick={onClose}
    >
      <div
        className="w-full max-w-sm bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl overflow-hidden"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header with user info */}
        <div className="p-4 border-b border-[#00ff00]/20 flex items-center gap-3">
          {pfpUrl ? (
            <img
              src={pfpUrl}
              alt={displayName}
              className="w-12 h-12 rounded-full border-2 border-[#00ff00]/50 object-cover"
            />
          ) : (
            <div className="w-12 h-12 rounded-full border-2 border-[#00ff00]/50 bg-[#00ff00]/10 flex items-center justify-center">
              <span className="text-[#00ff00] font-mono text-lg">?</span>
            </div>
          )}
          <div className="flex-1 min-w-0">
            <p className="text-[#00ff00] font-mono font-bold truncate">
              {username ? `@${username}` : displayName}
            </p>
            <p className="text-gray-500 font-mono text-xs truncate">{address}</p>
          </div>
          <button
            onClick={onClose}
            className="w-8 h-8 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222] transition-colors shrink-0"
          >
            ✕
          </button>
        </div>

        {/* Tab navigation */}
        <div className="flex border-b border-[#00ff00]/20">
          <button
            onClick={() => setActiveTab("uploads")}
            className={`flex-1 py-2.5 font-mono text-xs transition-colors ${
              activeTab === "uploads"
                ? "text-[#00ff00] border-b-2 border-[#00ff00]"
                : "text-gray-500 hover:text-gray-300"
            }`}
          >
            Uploads ({userUploads.length})
          </button>
          <button
            onClick={() => setActiveTab("stacks")}
            className={`flex-1 py-2.5 font-mono text-xs transition-colors ${
              activeTab === "stacks"
                ? "text-[#00ff00] border-b-2 border-[#00ff00]"
                : "text-gray-500 hover:text-gray-300"
            }`}
          >
            Stacks ({userStacks?.length || 0})
          </button>
          <button
            onClick={() => setActiveTab("grids")}
            className={`flex-1 py-2.5 font-mono text-xs transition-colors ${
              activeTab === "grids"
                ? "text-[#00ff00] border-b-2 border-[#00ff00]"
                : "text-gray-500 hover:text-gray-300"
            }`}
          >
            Grids ({userGrids?.length || 0})
          </button>
        </div>

        {/* Content area */}
        <div className="p-3 max-h-64 overflow-y-auto">
          {activeTab === "uploads" && (
            <>
              {userUploads.length > 0 ? (
                <div className="space-y-1.5">
                  {userUploads.slice(0, 15).map((upload) => (
                    <button
                      key={upload.contentKey}
                      onClick={() => {
                        onClose();
                        window.dispatchEvent(
                          new CustomEvent("navigate-to-book", { detail: upload.contentKey })
                        );
                      }}
                      className="w-full flex items-center gap-2 p-2 rounded-lg bg-[#1a1a1a] hover:bg-[#00ff00]/10 transition-colors text-left"
                    >
                      <div className="w-8 h-8 rounded overflow-hidden bg-black shrink-0">
                        <CoverImage
                          src={getEffectiveCoverUrl(upload)}
                          alt=""
                          className="w-full h-full object-cover"
                          fallbackClassName="w-full h-full flex items-center justify-center bg-[#00ff00]/10"
                          fallbackLogoSize="w-4 h-4"
                        />
                      </div>
                      <span className="text-white font-mono text-xs truncate flex-1">
                        {upload.title || "Untitled"}
                      </span>
                      <span className="text-gray-500 font-mono text-[10px] shrink-0">
                        {upload.mediaType || "doc"}
                      </span>
                    </button>
                  ))}
                  {userUploads.length > 15 && (
                    <Small className="text-gray-500 font-mono text-[9px] text-center block mt-2">
                      +{userUploads.length - 15} more
                    </Small>
                  )}
                </div>
              ) : (
                <div className="text-center py-6">
                  <span className="text-gray-500 font-mono text-sm">No uploads yet</span>
                </div>
              )}
            </>
          )}

          {activeTab === "stacks" && (
            <>
              {userStacks && userStacks.length > 0 ? (
                <div className="space-y-1.5">
                  {userStacks.slice(0, 15).map((stack) => (
                    <button
                      key={stack.id}
                      onClick={() => {
                        onClose();
                        window.dispatchEvent(
                          new CustomEvent("navigate-to-stack", { detail: stack })
                        );
                      }}
                      className="w-full flex items-center gap-2 p-2 rounded-lg bg-[#1a1a1a] hover:bg-[#00ff00]/10 transition-colors text-left"
                    >
                      <div className="w-8 h-8 rounded bg-[#00ff00]/10 flex items-center justify-center">
                        <span className="text-[#00ff00]/70 text-sm"><LibraryIcon size={16} /></span>
                      </div>
                      <span className="text-white font-mono text-xs truncate flex-1">
                        {stack.name}
                      </span>
                      <span className="text-gray-500 font-mono text-[10px] shrink-0">
                        {stack.itemCount || 0} items
                      </span>
                    </button>
                  ))}
                  {userStacks.length > 15 && (
                    <Small className="text-gray-500 font-mono text-[9px] text-center block mt-2">
                      +{userStacks.length - 15} more
                    </Small>
                  )}
                </div>
              ) : (
                <div className="text-center py-6">
                  <span className="text-gray-500 font-mono text-sm">No stacks yet</span>
                </div>
              )}
            </>
          )}

          {activeTab === "grids" && (
            <>
              {userGrids && userGrids.length > 0 ? (
                <div className="space-y-1.5">
                  {userGrids.slice(0, 15).map((grid) => (
                    <button
                      key={grid.id}
                      onClick={() => {
                        onClose();
                        window.dispatchEvent(
                          new CustomEvent("navigate-to-grid", { detail: { id: grid.id } })
                        );
                      }}
                      className="w-full flex items-center gap-2 p-2 rounded-lg bg-[#1a1a1a] hover:bg-[#00ff00]/10 transition-colors text-left"
                    >
                      <div className="w-8 h-8 rounded bg-[#00ff00]/10 flex items-center justify-center">
                        <span className="text-[#00ff00]/70 text-sm">🔲</span>
                      </div>
                      <span className="text-white font-mono text-xs truncate flex-1">
                        {grid.name}
                      </span>
                      <span className="text-gray-500 font-mono text-[10px] shrink-0">
                        {grid.size}×{grid.size}
                      </span>
                    </button>
                  ))}
                  {userGrids.length > 15 && (
                    <Small className="text-gray-500 font-mono text-[9px] text-center block mt-2">
                      +{userGrids.length - 15} more
                    </Small>
                  )}
                </div>
              ) : (
                <div className="text-center py-6">
                  <span className="text-gray-500 font-mono text-sm">No grids yet</span>
                </div>
              )}
            </>
          )}
        </div>
      </div>
    </div>
  );
}

/**
 * Clickable user avatar that opens the content popover
 * Use this anywhere you display a user's PFP
 */
export function ClickableUserAvatar({
  address,
  username,
  pfpUrl,
  fid,
  size = "md",
  showUsername = false,
}: {
  address: string;
  username?: string;
  pfpUrl?: string;
  fid?: number;
  size?: "sm" | "md" | "lg";
  showUsername?: boolean;
}) {
  const [showPopover, setShowPopover] = useState(false);

  const sizeClasses = {
    sm: "w-6 h-6",
    md: "w-8 h-8",
    lg: "w-10 h-10",
  };

  const textSizeClasses = {
    sm: "text-[9px]",
    md: "text-[10px]",
    lg: "text-xs",
  };

  return (
    <>
      <button
        onClick={() => setShowPopover(true)}
        className="flex items-center gap-1.5 hover:opacity-80 transition-opacity"
      >
        {pfpUrl ? (
          <img
            src={pfpUrl}
            alt={username || "User"}
            className={`${sizeClasses[size]} rounded-full object-cover border border-[#00ff00]/30`}
          />
        ) : (
          <div
            className={`${sizeClasses[size]} rounded-full bg-[#00ff00]/10 border border-[#00ff00]/30 flex items-center justify-center`}
          >
            <span className="text-[#00ff00]/50 text-xs">?</span>
          </div>
        )}
        {showUsername && username && (
          <span className={`text-[#00ff00]/70 font-mono ${textSizeClasses[size]} hover:text-[#00ff00] transition-colors`}>
            @{username}
          </span>
        )}
      </button>

      <UserContentPopover
        isOpen={showPopover}
        onClose={() => setShowPopover(false)}
        address={address}
        username={username}
        pfpUrl={pfpUrl}
        fid={fid}
      />
    </>
  );
}
src/features/app/components/user-library-card-modal.tsx
"use client";

import { useState, useEffect, useMemo } from "react";
import { createPortal } from "react-dom";
import { Card, CardContent, P, Small } from "@neynar/ui";
import { useAccount } from "wagmi";
import { useDiscoveryContext } from "@/contexts/discovery-context";
import { useLeaderboard } from "@/hooks/use-leaderboard";
import { useUpvoteCounts } from "@/hooks/use-upvotes";
import { useMemberUpvote, useMemberUpvoteCounts, MEMBER_UPVOTE_COST_ETH } from "@/hooks/use-member-upvotes";
import { MemberUpvoteModal } from "@/features/app/components/member-upvote-modal";
import { useStacks } from "@/hooks/use-stacks";
import { useGrids } from "@/hooks/use-grids";
import { useUserStats } from "@/hooks/use-user-stats";
import { type MemberEntry, type SignupPlatform, type GridWithStats } from "@/lib/net-protocol";
import { safeOpenUrl } from "@/lib/app-mode";
import {
  LibraryIcon,
  LinkIcon,
  TrophyIcon,
  FarcasterIcon,
  BaseIcon,
  WebIcon,
  GridIcon,
  UploadIcon,
} from "@/components/icons/net-library-icons";
import { CoverImage } from "./cover-image";

// Minimal membership info needed for display (subset of MembershipInfo)
interface MembershipDisplayInfo {
  memberId: number;
  address: string;
  ensSubname: string;
  signupPlatform?: SignupPlatform | "unknown";
}

interface UserLibraryCardModalProps {
  isOpen: boolean;
  onClose: () => void;
  member: MemberEntry & { pfpUrl?: string; netLink?: { url: string; label: string } | null; signupPlatform?: SignupPlatform; linkedAddresses?: string[]; wid?: string; linkedPlatforms?: SignupPlatform[] };
  // All memberships for users with multiple (each one is real - they paid for each)
  allMemberships?: MembershipDisplayInfo[] | null;
}

// Get platform icon component
function PlatformIcon({ platform, size = 12 }: { platform?: SignupPlatform | "unknown"; size?: number }) {
  if (platform === "farcaster") return <FarcasterIcon size={size} className="text-purple-400" />;
  if (platform === "base-app") return <BaseIcon size={size} className="text-blue-400" />;
  if (platform === "web") return <WebIcon size={size} className="text-yellow-400" />;
  return null;
}

// Braille alphabet mapping
const BRAILLE_MAP: Record<string, string> = {
  'a': '⠁', 'b': '⠃', 'c': '⠉', 'd': '⠙', 'e': '⠑',
  'f': '⠋', 'g': '⠛', 'h': '⠓', 'i': '⠊', 'j': '⠚',
  'k': '⠅', 'l': '⠇', 'm': '⠍', 'n': '⠝', 'o': '⠕',
  'p': '⠏', 'q': '⠟', 'r': '⠗', 's': '⠎', 't': '⠞',
  'u': '⠥', 'v': '⠧', 'w': '⠺', 'x': '⠭', 'y': '⠽',
  'z': '⠵', '0': '⠚', '1': '⠁', '2': '⠃', '3': '⠉',
  '4': '⠙', '5': '⠑', '6': '⠋', '7': '⠛', '8': '⠓',
  '9': '⠊', ' ': '⠀', '.': '⠲', ',': '⠂', '-': '⠤',
  '_': '⠸', '@': '⠈⠁'
};

function toBraille(text: string): string {
  return (text || '').toLowerCase().split('').map(char => BRAILLE_MAP[char] || char).join('');
}

// Format bytes for display
function formatBytes(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

// Get best cover URL - prefers coverUrl, falls back to cdnUrl for visual content
function getEffectiveCoverUrl(entry: { coverUrl?: string; cdnUrl?: string; mediaType?: string }): string {
  // If explicit cover art is set, use it
  if (entry.coverUrl) return entry.coverUrl;

  // For image/video content, cdnUrl IS the visual content - use it as thumbnail
  if (entry.cdnUrl && entry.mediaType && ["image", "video"].includes(entry.mediaType)) {
    return entry.cdnUrl;
  }

  return '';
}

// Grid Preview Thumbnail
function GridPreviewThumb({ grid }: { grid: GridWithStats }) {
  const previewSize = Math.min(grid.size || 3, 3);
  const cells = grid.previewCells || [];

  const filledCells = new Map<string, { coverUrl?: string; cdnUrl?: string }>();
  cells.forEach((cell) => {
    if (cell && cell.row < previewSize && cell.col < previewSize) {
      filledCells.set(`${cell.row}-${cell.col}`, cell);
    }
  });

  return (
    <div
      className="w-12 h-12 rounded-lg bg-black border border-[#00ff00]/20 p-0.5 grid gap-0.5 shrink-0 overflow-hidden"
      style={{
        gridTemplateColumns: `repeat(${previewSize}, 1fr)`,
        gridTemplateRows: `repeat(${previewSize}, 1fr)`,
      }}
    >
      {Array.from({ length: previewSize * previewSize }).map((_, i) => {
        const row = Math.floor(i / previewSize);
        const col = i % previewSize;
        const cell = filledCells.get(`${row}-${col}`);

        if (cell) {
          const imageUrl = getEffectiveCoverUrl({ coverUrl: cell.coverUrl, cdnUrl: cell.cdnUrl });
          return (
            <div key={i} className="rounded-sm overflow-hidden bg-[#1a1a1a]">
              {imageUrl ? (
                <CoverImage
                  src={imageUrl}
                  alt=""
                  className="w-full h-full object-cover"
                  fallbackClassName="w-full h-full bg-[#00ff00]/30"
                  fallbackLogoSize="w-2 h-2"
                />
              ) : (
                <div className="w-full h-full bg-[#00ff00]/30" />
              )}
            </div>
          );
        }
        return <div key={i} className="rounded-sm bg-[#1a1a1a]" />;
      })}
    </div>
  );
}

export function UserLibraryCardModal({ isOpen, onClose, member, allMemberships }: UserLibraryCardModalProps) {
  const [displayName, setDisplayName] = useState<string | null>(null);
  // Farcaster handle resolved live from Neynar (e.g. "cherylfromnet")
  // Separate from member.username which is the display name (e.g. "Cheryl")
  const [farcasterHandle, setFarcasterHandle] = useState<string | null>(null);
  const [showCpis, setShowCpis] = useState(false);
  const [profileSubTab, setProfileSubTab] = useState<"uploads" | "stacks" | "grids">("uploads");
  const [showMemberUpvoteModal, setShowMemberUpvoteModal] = useState(false);

  const { address: currentUserAddress } = useAccount();

  // Derive platform verification from the member's data
  // A platform is "verified" if:
  // 1. They signed up via that platform (signupPlatform)
  // 2. They have explicitly linked that platform (linkedPlatforms)
  // 3. For Farcaster specifically, having an FID indicates Farcaster verification
  // 4. For Web specifically, having a WID indicates Web verification
  // NOTE: Having an address alone does NOT mean Base App verification - everyone has an address
  const linkedPlatforms = member.linkedPlatforms || [];
  const isFarcasterVerified = !!member.fid || linkedPlatforms.includes("farcaster") || member.signupPlatform === "farcaster";
  const isBaseAppVerified = linkedPlatforms.includes("base-app") || member.signupPlatform === "base-app";
  const isWebVerified = !!member.wid || linkedPlatforms.includes("web") || member.signupPlatform === "web";

  // Get discovery data from shared context
  const { entries } = useDiscoveryContext();
  const { getUserRank } = useLeaderboard();

  // Build set of all addresses for this user
  const userAddresses = useMemo(() => {
    const addresses = new Set<string>();
    if (member.address) addresses.add(member.address.toLowerCase());
    if (member.linkedAddresses) {
      member.linkedAddresses.forEach(addr => addr && addresses.add(addr.toLowerCase()));
    }
    if (allMemberships) {
      allMemberships.forEach(m => m.address && addresses.add(m.address.toLowerCase()));
    }
    return addresses;
  }, [member.address, member.linkedAddresses, allMemberships]);

  // Build set of memberIds for this user (for unified identity matching)
  const userMemberIds = useMemo(() => {
    const memberIds = new Set<number>();
    if (member.memberId) memberIds.add(member.memberId);
    if (allMemberships) {
      allMemberships.forEach(m => {
        if (m.memberId) memberIds.add(m.memberId);
      });
    }
    return memberIds;
  }, [member.memberId, allMemberships]);

  // Filter entries for this user's uploads (exclude hidden items).
  // Match by: uploaderAddress (relay uploads), operator address (legacy/direct),
  // importer address (CDN imports), OR memberId (unified identity across platforms).
  const userUploads = entries.filter(
    (e) => !e.hidden && (
      (e.uploaderAddress && userAddresses.has(e.uploaderAddress.toLowerCase())) ||
      (e.operator && userAddresses.has(e.operator.toLowerCase())) ||
      (e.importerAddress && userAddresses.has(e.importerAddress.toLowerCase())) ||
      (e.uploaderMemberId && userMemberIds.has(e.uploaderMemberId))
    )
  );

  // Get user stats from achievements
  const achievementLookupAddress = member.address;
  const { earnedIds: _earnedIds } = useUserStats(achievementLookupAddress);

  // Prepare items for upvote count fetching
  // Use uploaderAddress (user's actual wallet) if present, falling back to operator
  // (backend relay wallet) — must match the address used when casting upvotes
  const upvoteItems = useMemo(() =>
    userUploads.map(upload => ({
      contentKey: upload.contentKey,
      operator: upload.uploaderAddress || upload.operator,
    })),
    [userUploads]
  );

  // Fetch upvote counts
  const { getCount: getUpvoteCount } = useUpvoteCounts(upvoteItems);

  // User's stacks and grids
  const { stacks: userStacks } = useStacks({ owner: member.address, enabled: isOpen });
  const { grids: userGrids } = useGrids({ creator: member.address });

  // Member upvote hook - for upvoting this user
  const memberUpvoteData = useMemo(() =>
    member?.address ? [{ memberId: member.memberId, address: member.address }] : [],
    [member?.memberId, member?.address]
  );
  const { upvoteMember, isUpvoting, isConfirmed, reset: resetUpvote } = useMemberUpvote();
  const { getCount: getMemberUpvotes, refresh: refreshMemberUpvotes } = useMemberUpvoteCounts(memberUpvoteData);

  // Total upvotes = content upvotes on all uploads + member profile upvotes received
  const totalUpvotesReceived = useMemo(() => {
    const contentUpvotes = userUploads.reduce((total, upload) => total + getUpvoteCount(upload.contentKey), 0);
    const memberUpvotes = member?.address ? getMemberUpvotes(member.address) : 0;
    return contentUpvotes + memberUpvotes;
  }, [userUploads, getUpvoteCount, getMemberUpvotes, member?.address]);

  // Refresh when upvote transaction confirms
  useEffect(() => {
    if (isConfirmed) {
      refreshMemberUpvotes();
      resetUpvote();
    }
  }, [isConfirmed, refreshMemberUpvotes, resetUpvote]);

  // Handle upvoting this member — opens the count-selection modal
  const handleUpvoteMember = () => {
    if (!member?.address || isUpvoting) return;
    setShowMemberUpvoteModal(true);
  };

  // Called by MemberUpvoteModal once the user has chosen a count
  const handleSubmitMemberUpvote = async (count: number) => {
    if (!member?.address) return;
    const lowestMemberId = allMemberships && allMemberships.length > 0
      ? Math.min(...allMemberships.map(m => m.memberId))
      : member.memberId;
    await upvoteMember(member.address, lowestMemberId, count);
    setShowMemberUpvoteModal(false);
  };

  // Get user stats from leaderboard
  const { rank, stats: userStats } = useMemo(() => {
    let bestResult = getUserRank(member.address);
    if (member.linkedAddresses) {
      for (const addr of member.linkedAddresses) {
        if (!addr) continue;
        const result = getUserRank(addr);
        if (result.stats && (!bestResult.stats || result.rank < bestResult.rank)) {
          bestResult = result;
        }
      }
    }
    if (allMemberships) {
      for (const m of allMemberships) {
        if (m.address && member.address && m.address.toLowerCase() !== member.address.toLowerCase()) {
          const result = getUserRank(m.address);
          if (result.stats && (!bestResult.stats || result.rank < bestResult.rank)) {
            bestResult = result;
          }
        }
      }
    }
    return bestResult;
  }, [member.address, member.linkedAddresses, allMemberships, getUserRank]);

  // Resolve display name from Neynar
  useEffect(() => {
    if (!member.fid) return;

    async function fetchDisplayName() {
      try {
        const response = await fetch("/api/resolve-user", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ fids: [member.fid] }),
        });
        if (response.ok) {
          const data = await response.json();
          const neynarUser = data.users?.[0];
          if (neynarUser?.display_name) {
            setDisplayName(neynarUser.display_name);
          }
          // Capture the true Farcaster handle (e.g. "cherylfromnet") — distinct from
          // member.username which stores the display name (e.g. "Cheryl")
          if (neynarUser?.username) {
            setFarcasterHandle(neynarUser.username);
          }
        }
      } catch {
        // Ignore errors
      }
    }
    fetchDisplayName();
  }, [member.fid]);

  // Open Farcaster profile
  // Use live-resolved Farcaster handle first, then stored farcasterUsername,
  // then fall back to member.username (which may be a display name, not a handle)
  const resolvedFarcasterHandle = farcasterHandle || member.farcasterUsername || member.username;
  const openProfile = async () => {
    if (!resolvedFarcasterHandle) return;
    const profileUrl = `https://warpcast.com/${resolvedFarcasterHandle}`;
    await safeOpenUrl(profileUrl);
  };

  // Open Net link
  const openNetLink = async () => {
    if (!member.netLink?.url) return;
    await safeOpenUrl(member.netLink.url);
  };

  if (!isOpen) return null;

  const totalBytes = userStats?.totalBytesUploaded || userUploads.reduce((acc, u) => acc + u.fileSize, 0);
  const bytesFormatted = formatBytes(totalBytes);
  const [bytesNum, bytesUnit] = bytesFormatted.split(' ');

  const isMember = member.memberId > 0;
  const isOwnProfile = currentUserAddress && member.address && currentUserAddress.toLowerCase() === member.address.toLowerCase();

  // Use portal to render at document body level (fixes z-index issues with scrolling containers)
  const modalContent = (
    <div
      className="fixed inset-0 bg-black z-[9999] overflow-y-auto"
      onClick={onClose}
    >
      <div className="min-h-full p-4 space-y-4" onClick={(e) => e.stopPropagation()}>
        {/* Back Button Header */}
        <div className="flex items-center justify-between">
          <button
            onClick={onClose}
            className="w-10 h-10 rounded-full bg-[#00ff00]/10 border border-[#00ff00]/30 flex items-center justify-center text-[#00ff00] hover:bg-[#00ff00]/20 transition-colors"
          >
            ←
          </button>
          <P className="text-[#00ff00]/60 font-mono text-sm">Member Profile</P>
          <div className="w-10" /> {/* Spacer */}
        </div>

        {/* NET LIBRARY CARD - Matrix-style library card (matches My Profile exactly) */}
        <div className="relative overflow-hidden rounded-xl border-2 border-[#00ff00]/50 bg-gradient-to-br from-[#0a0a0a] via-[#0d1a0d] to-[#0a0a0a] shadow-[0_0_30px_rgba(0,255,0,0.15)]">
          {/* Scanline effect overlay */}
          <div className="absolute inset-0 bg-[linear-gradient(transparent_50%,rgba(0,0,0,0.1)_50%)] bg-[length:100%_4px] pointer-events-none opacity-30" />

          {/* Glowing corner accents */}
          <div className="absolute top-0 left-0 w-16 h-16 bg-gradient-to-br from-[#00ff00]/20 to-transparent" />
          <div className="absolute bottom-0 right-0 w-16 h-16 bg-gradient-to-tl from-[#00ff00]/20 to-transparent" />

          {/* Card Header */}
          <div className="relative px-4 py-2 border-b border-[#00ff00]/30 bg-[#00ff00]/5">
            <div className="flex items-center justify-between">
              <div className="flex items-center gap-2">
                <div className={`w-2 h-2 rounded-full ${isMember ? 'bg-[#00ff00] animate-pulse shadow-[0_0_8px_#00ff00]' : 'bg-gray-500'}`} />
                <span className="text-[10px] font-mono text-[#00ff00]/70 tracking-[0.2em] uppercase">Net Protocol</span>
              </div>
              <span className="text-[10px] font-mono text-[#00ff00]/50">Onchain Library Card</span>
            </div>
          </div>

          {/* Main Card Content */}
          <div className="relative p-4">
            {/* Top Section - Photo & Identity */}
            <div className="flex gap-4 mb-4">
              {/* Photo with frame + Net Link */}
              <div className="flex flex-col items-start w-20">
                <div className="relative">
                  <div className="w-20 h-24 rounded-lg border-2 border-[#00ff00]/50 overflow-hidden bg-black shadow-[inset_0_0_20px_rgba(0,255,0,0.1)]">
                    {member.pfpUrl ? (
                      <img
                        src={member.pfpUrl}
                        alt={member.username || `Member ${member.memberId}`}
                        className="w-full h-full object-cover"
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center bg-[#00ff00]/10">
                        <span className="text-[#00ff00] font-mono text-2xl font-bold">
                          {member.memberId || '?'}
                        </span>
                      </div>
                    )}
                  </div>
                  {/* Holographic shine effect */}
                  <div className="absolute inset-0 rounded-lg bg-gradient-to-br from-white/10 via-transparent to-transparent pointer-events-none" />
                </div>
                {/* Net Link under photo */}
                {member.netLink ? (
                  <button
                    onClick={openNetLink}
                    className="mt-2 text-[9px] font-mono text-[#00ff00] underline underline-offset-2 hover:text-[#00ff00]/80 transition-colors truncate w-full text-center"
                  >
                    <LinkIcon size={10} className="inline mr-0.5" /> {member.netLink.label || 'Net Link'}
                  </button>
                ) : isMember ? (
                  <span className="mt-2 text-[9px] font-mono text-gray-500 w-full text-center">unlinked</span>
                ) : null}
              </div>

              {/* Identity Info */}
              <div className="min-w-0 flex flex-col justify-between h-24">
                <div className="min-w-0">
                  <P className={`font-mono font-bold text-lg leading-none truncate -mt-0.5 ${member.isAgent ? "text-[#B794F4]" : "text-[#00ff00]"}`}>
                    {displayName || member.username || `Member ${member.memberId}`}
                  </P>
                  {resolvedFarcasterHandle && (
                    <button
                      onClick={openProfile}
                      className={`font-mono truncate block text-sm transition-colors text-left ${
                        member.isAgent
                          ? "text-[#B794F4]/60 hover:text-[#B794F4]"
                          : "text-[#00ff00]/60 hover:text-[#00ff00]"
                      }`}
                    >
                      @{resolvedFarcasterHandle}
                    </button>
                  )}
                  {/* Member badge and ENS subname(s) with platform indicators */}
                  {isMember && (
                    <div className="mt-2 flex flex-col gap-0.5">
                      <span className="text-[10px] font-mono font-bold tracking-wider">
                        <span className={member.isAgent ? "text-[#B794F4]" : "text-[#00ff00]"}>MEMBER</span>
                        {member.isAgent && <span className="text-[#B794F4]"> · AGENT</span>}
                      </span>
                      {/* Show all memberships with platform indicator */}
                      {allMemberships && allMemberships.length > 0 ? (
                        <div className="flex flex-col gap-0.5 -mt-0.5">
                          {allMemberships.map((m) => (
                            <span key={m.memberId} className={`text-[9px] font-mono flex items-center gap-1 ${member.isAgent ? "text-[#B794F4]/70" : "text-[#00ff00]/70"}`}>
                              <span>{m.ensSubname}</span>
                              <PlatformIcon platform={m.signupPlatform} size={10} />
                            </span>
                          ))}
                        </div>
                      ) : member.ensSubname && (
                        <span className={`text-[9px] font-mono -mt-0.5 ${member.isAgent ? "text-[#B794F4]/70" : "text-[#00ff00]/70"}`}>
                          {member.ensSubname}
                        </span>
                      )}
                    </div>
                  )}
                </div>
                {/* Rank Badge */}
                {rank > 0 && rank <= 100 && (
                  <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-[#00ff00]/20 border border-[#00ff00]/30 w-fit">
                    <TrophyIcon size={10} className="text-[#00ff00]" />
                    <span className="text-[8px] font-mono text-[#00ff00] font-bold">RANK #{rank}</span>
                  </span>
                )}
              </div>

              {/* Spacer */}
              <div className="flex-1" />

              {/* Net Library Crest - Watermark style with upvotes below */}
              <div className="flex flex-col items-center flex-shrink-0 self-start" style={{ width: 'calc((100% - 2rem) / 3)' }}>
                <div className="relative opacity-30 w-full" style={{ mixBlendMode: 'screen' }}>
                  <img src="/app-logo.png" alt="Net Library" className="w-full h-auto" />
                </div>
                {/* Upvotes received */}
                <div className="flex items-center gap-1 mt-2">
                  <span className="text-[#00ff00] font-mono text-lg">▲</span>
                  <span className="text-[#00ff00] font-mono text-lg font-bold">{totalUpvotesReceived}</span>
                </div>
              </div>
            </div>

            {/* Membership Address */}
            {isMember && member.address && (
              <div className="mt-2">
                <Small className="text-[8px] font-mono text-gray-600 tracking-wider truncate block">
                  {member.address}
                </Small>
              </div>
            )}

            {/* Cross-Platform Identity System (CPIS) */}
            {isMember && (
              <div className="mt-3">
                <button
                  onClick={() => setShowCpis(!showCpis)}
                  className="w-full flex items-center justify-between p-2 rounded-lg bg-black/30 border border-[#00ff00]/20 hover:border-[#00ff00]/40 transition-colors"
                >
                  <div className="flex items-center gap-2">
                    <span className="text-[10px] font-mono text-gray-400">Cross-Platform Identity</span>
                    <div className="flex items-center gap-1.5">
                      <span className={`flex items-center gap-0.5 text-[9px] font-mono ${isFarcasterVerified ? "text-purple-400" : "text-purple-400/30"}`}>
                        <FarcasterIcon size={10} className={isFarcasterVerified ? "text-purple-400" : "text-purple-400/30"} />
                        {isFarcasterVerified ? "✓" : "○"}
                      </span>
                      <span className={`flex items-center gap-0.5 text-[9px] font-mono ${isBaseAppVerified ? "text-blue-400" : "text-blue-400/30"}`}>
                        <BaseIcon size={10} className={isBaseAppVerified ? "text-blue-400" : "text-blue-400/30"} />
                        {isBaseAppVerified ? "✓" : "○"}
                      </span>
                      <span className={`flex items-center gap-0.5 text-[9px] font-mono ${isWebVerified ? "text-yellow-400" : "text-yellow-400/30"}`}>
                        <WebIcon size={10} className={isWebVerified ? "text-yellow-400" : "text-yellow-400/30"} />
                        {isWebVerified ? "✓" : "○"}
                      </span>
                    </div>
                  </div>
                  <span className="text-gray-500 text-xs">{showCpis ? "▲" : "▼"}</span>
                </button>

                {showCpis && (
                  <div className="mt-2 p-3 rounded-lg bg-black/50 border border-[#00ff00]/10 space-y-3">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <FarcasterIcon size={16} className="text-purple-400" />
                        <Small className="text-white font-mono">Farcaster</Small>
                      </div>
                      {isFarcasterVerified ? (
                        <span className="px-2 py-0.5 rounded text-[9px] font-mono bg-purple-500/20 text-purple-400 border border-purple-500/30">
                          ✓ FID {member.fid}
                        </span>
                      ) : (
                        <span className="px-2 py-0.5 rounded text-[9px] font-mono bg-gray-800 text-gray-500 border border-gray-700">
                          Not Linked
                        </span>
                      )}
                    </div>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <BaseIcon size={16} className="text-blue-400" />
                        <Small className="text-white font-mono">Base Wallet</Small>
                      </div>
                      {isBaseAppVerified ? (
                        <span className="px-2 py-0.5 rounded text-[9px] font-mono bg-blue-500/20 text-blue-400 border border-blue-500/30">
                          ✓ {member.address.slice(0, 6)}...{member.address.slice(-4)}
                        </span>
                      ) : (
                        <span className="px-2 py-0.5 rounded text-[9px] font-mono bg-gray-800 text-gray-500 border border-gray-700">
                          Not Linked
                        </span>
                      )}
                    </div>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center gap-2">
                        <WebIcon size={16} className="text-yellow-400" />
                        <Small className="text-white font-mono">Web ID</Small>
                      </div>
                      {isWebVerified ? (
                        <span className="px-2 py-0.5 rounded text-[9px] font-mono bg-yellow-500/20 text-yellow-400 border border-yellow-500/30">
                          ✓ WID {member.wid}
                        </span>
                      ) : (
                        <span className="px-2 py-0.5 rounded text-[9px] font-mono bg-gray-800 text-gray-500 border border-gray-700">
                          Not Linked
                        </span>
                      )}
                    </div>
                    {member.linkedAddresses && member.linkedAddresses.length > 0 && (
                      <div className="pt-2 border-t border-[#00ff00]/10">
                        <Small className="text-gray-500 font-mono text-[9px] block mb-1">Linked Wallets ({member.linkedAddresses.length})</Small>
                        {member.linkedAddresses.filter(addr => addr).map((addr, i) => (
                          <Small key={i} className="text-blue-400/70 font-mono text-[9px] block">
                            • {addr.slice(0, 6)}...{addr.slice(-4)}
                          </Small>
                        ))}
                      </div>
                    )}
                  </div>
                )}
              </div>
            )}

            {/* Divider with circuit pattern */}
            <div className="relative h-px bg-[#00ff00]/20 my-3">
              <div className="absolute left-0 top-1/2 -translate-y-1/2 w-2 h-2 rounded-full bg-[#00ff00]/40" />
              <div className="absolute right-0 top-1/2 -translate-y-1/2 w-2 h-2 rounded-full bg-[#00ff00]/40" />
              <div className="absolute left-1/4 top-1/2 -translate-y-1/2 w-1 h-1 rounded-full bg-[#00ff00]/30" />
              <div className="absolute left-1/2 top-1/2 -translate-y-1/2 w-1 h-1 rounded-full bg-[#00ff00]/30" />
              <div className="absolute left-3/4 top-1/2 -translate-y-1/2 w-1 h-1 rounded-full bg-[#00ff00]/30" />
            </div>

            {/* Stats Grid */}
            <div className="grid grid-cols-4 gap-2">
              <div className="flex flex-col items-center justify-center p-2 rounded-lg bg-black/50 border border-[#00ff00]/20">
                <P className="text-xl font-bold text-[#00ff00] font-mono leading-none text-center">
                  {userStacks?.length || 0}
                </P>
                <Small className="text-[9px] text-gray-500 font-mono uppercase tracking-wider text-center">Stacks</Small>
              </div>
              <div className="flex flex-col items-center justify-center p-2 rounded-lg bg-black/50 border border-[#00ff00]/20">
                <P className="text-xl font-bold text-[#00ff00] font-mono leading-none text-center">
                  {userGrids?.length || 0}
                </P>
                <Small className="text-[9px] text-gray-500 font-mono uppercase tracking-wider text-center">Grids</Small>
              </div>
              <div className="flex flex-col items-center justify-center p-2 rounded-lg bg-black/50 border border-[#00ff00]/20">
                <P className="text-xl font-bold text-[#00ff00] font-mono leading-none text-center">
                  {userStats?.totalUploads || userUploads.length}
                </P>
                <Small className="text-[9px] text-gray-500 font-mono uppercase tracking-wider text-center">Uploads</Small>
              </div>
              <div className="flex flex-col items-center justify-center p-2 rounded-lg bg-black/50 border border-[#00ff00]/20">
                <P className="text-xl font-bold text-[#00ff00] font-mono leading-none text-center">
                  {bytesNum}
                </P>
                <Small className="text-[9px] text-gray-500 font-mono uppercase tracking-wider text-center">
                  {bytesUnit || 'B'}
                </Small>
              </div>
            </div>

            {/* Upvote Member Button (for other users, not self) */}
            {isMember && !isOwnProfile && currentUserAddress && (
              <button
                onClick={handleUpvoteMember}
                disabled={isUpvoting}
                className={`w-full mt-3 py-2.5 rounded-lg font-mono text-sm transition-all flex items-center justify-center gap-2 ${
                  isUpvoting
                    ? "bg-[#00ff00]/30 border border-[#00ff00] text-[#00ff00] animate-pulse"
                    : "bg-[#00ff00]/10 border border-[#00ff00]/30 text-[#00ff00] hover:bg-[#00ff00]/20 hover:shadow-[0_0_15px_rgba(0,255,0,0.3)] active:scale-[0.98]"
                }`}
              >
                <span className="text-lg">▲</span>
                <span>
                  {isUpvoting
                    ? "Upvoting..."
                    : `Upvote ${displayName || member.username || 'Member'}`
                  }
                </span>
              </button>
            )}

            {/* Own profile message */}
            {isOwnProfile && (
              <div className="w-full mt-3 py-2 text-center text-gray-500 font-mono text-xs">
                This is your profile
              </div>
            )}
          </div>

          {/* Card Footer */}
          <div className="relative px-4 py-2 border-t border-[#00ff00]/20 bg-black/30">
            <div className="flex items-center justify-between gap-2">
              <span className="text-sm font-mono text-[#00ff00]/50 tracking-wide shrink-0" title={member.username || "member"}>
                {toBraille(member.username || "member")}
              </span>

              {member.hasStackPass && (
                <div className="relative flex items-center gap-1.5 px-2 py-0.5 rounded-full bg-gradient-to-r from-purple-500/20 via-[#00ff00]/20 to-purple-500/20 border border-purple-500/40 shrink-0 overflow-hidden">
                  <div
                    className="absolute inset-0 bg-gradient-to-r from-transparent via-white/30 to-transparent"
                    style={{ animation: 'glimmer-initial 0.6s ease-out forwards, glimmer-repeat 5s ease-in-out 1s infinite' }}
                  />
                  <span className="text-[10px] relative z-10">∞</span>
                  <span className="text-[8px] font-mono font-bold bg-gradient-to-r from-purple-400 via-[#00ff00] to-purple-400 bg-clip-text text-transparent tracking-wider uppercase relative z-10">
                    UNLIMITED
                  </span>
                  <style jsx>{`
                    @keyframes glimmer-initial { 0% { transform: translateX(-100%); } 100% { transform: translateX(100%); } }
                    @keyframes glimmer-repeat { 0%, 85%, 100% { transform: translateX(-100%); } 92% { transform: translateX(100%); } }
                  `}</style>
                </div>
              )}

              <span className={`text-[8px] font-mono tracking-widest shrink-0 ${
                member.wid ? 'text-yellow-400/60' :
                member.fid ? 'text-purple-400/60' :
                isMember ? 'text-[#00ff00]/40' : 'text-gray-500'
              }`}>
                {member.wid ? `WID-${member.wid}` :
                 member.fid ? `FID-${member.fid}` :
                 isMember ? `M-${member.memberId}` : 'Non-member'}
              </span>
            </div>
          </div>
        </div>

        {/* Sub-tabs for Uploads, Stacks, Grids (NO hidden/verify for other users) */}
        <div className="flex gap-1 bg-[#0a0a0a] p-1 rounded-xl border border-[#00ff00]/20">
          <button
            onClick={() => setProfileSubTab("uploads")}
            className={`flex-1 py-2 px-2 rounded-lg text-xs font-mono transition-all ${
              profileSubTab === "uploads"
                ? "bg-[#00ff00] text-black"
                : "text-gray-400 hover:text-[#00ff00]"
            }`}
          >
            <UploadIcon size={12} className="inline mr-1" /> Uploads ({userUploads.length})
          </button>
          <button
            onClick={() => setProfileSubTab("stacks")}
            className={`flex-1 py-2 px-2 rounded-lg text-xs font-mono transition-all flex items-center justify-center gap-1 ${
              profileSubTab === "stacks"
                ? "bg-[#00ff00] text-black"
                : "text-gray-400 hover:text-[#00ff00]"
            }`}
          >
            <LibraryIcon size={12} /> Stacks ({userStacks?.length || 0})
          </button>
          <button
            onClick={() => setProfileSubTab("grids")}
            className={`flex-1 py-2 px-2 rounded-lg text-xs font-mono transition-all ${
              profileSubTab === "grids"
                ? "bg-[#00ff00] text-black"
                : "text-gray-400 hover:text-[#00ff00]"
            }`}
          >
            <GridIcon size={12} className="inline mr-1" /> Grids ({userGrids?.length || 0})
          </button>
        </div>

        {/* Uploads Tab */}
        {profileSubTab === "uploads" && (
          <div className="space-y-2">
            {userUploads.length === 0 ? (
              <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
                <CardContent className="p-8 text-center">
                  <div className="w-16 h-16 mx-auto mb-3 rounded-full bg-[#00ff00]/10 flex items-center justify-center border-2 border-dashed border-[#00ff00]/30">
                    <UploadIcon size={28} className="text-[#00ff00]/60" />
                  </div>
                  <P className="text-[#00ff00] font-mono">No uploads yet</P>
                  <Small className="text-gray-500 font-mono">This user hasn&apos;t uploaded any content</Small>
                </CardContent>
              </Card>
            ) : (
              userUploads.slice(0, 20).map((upload) => (
                <Card
                  key={upload.contentKey}
                  className="bg-[#0a0a0a] border-2 border-[#00ff00]/30 hover:border-[#00ff00] hover:shadow-[0_0_15px_rgba(0,255,0,0.3)] transition-all cursor-pointer"
                  onClick={() => {
                    onClose();
                    window.dispatchEvent(new CustomEvent("navigate-to-book", { detail: upload.contentKey }));
                  }}
                >
                  <CardContent className="p-3">
                    <div className="flex gap-3">
                      <div className="w-12 h-16 bg-gradient-to-br from-[#1a1a1a] to-[#0a0a0a] rounded flex items-center justify-center border border-[#00ff00]/20 overflow-hidden shrink-0">
                        <CoverImage
                          src={getEffectiveCoverUrl(upload)}
                          alt={upload.title}
                          className="w-full h-full object-cover"
                          fallbackClassName="w-full h-full flex items-center justify-center"
                          fallbackLogoSize="w-5 h-5"
                        />
                      </div>
                      <div className="flex-1 min-w-0">
                        <P className="font-medium truncate text-white font-mono text-sm">{upload.title}</P>
                        <Small className="text-gray-400 font-mono truncate block">{upload.author}</Small>
                        <div className="flex items-center gap-2 mt-1">
                          <Small className="text-[#00ff00]/70 font-mono text-[10px]">
                            {formatBytes(upload.fileSize)}
                          </Small>
                          <Small className="text-gray-500 font-mono text-[10px]">
                            ▲ {getUpvoteCount(upload.contentKey)}
                          </Small>
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))
            )}
            {userUploads.length > 20 && (
              <Small className="text-gray-500 font-mono text-center block">
                +{userUploads.length - 20} more uploads
              </Small>
            )}
          </div>
        )}

        {/* Stacks Tab */}
        {profileSubTab === "stacks" && (
          <div className="space-y-2">
            {!userStacks || userStacks.length === 0 ? (
              <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
                <CardContent className="p-8 text-center">
                  <div className="w-16 h-16 mx-auto mb-3 rounded-full bg-[#00ff00]/10 flex items-center justify-center border-2 border-dashed border-[#00ff00]/30">
                    <LibraryIcon size={28} className="text-[#00ff00]/60" />
                  </div>
                  <P className="text-[#00ff00] font-mono">No stacks yet</P>
                  <Small className="text-gray-500 font-mono">This user hasn&apos;t created any stacks</Small>
                </CardContent>
              </Card>
            ) : (
              userStacks.slice(0, 20).map((stack) => {
                const previewCovers = stack.previewCovers?.slice(0, 4) || [];
                return (
                  <Card
                    key={stack.id}
                    className="bg-[#0a0a0a] border-2 border-[#00ff00]/30 hover:border-[#00ff00] hover:shadow-[0_0_15px_rgba(0,255,0,0.3)] transition-all cursor-pointer"
                    onClick={() => {
                      onClose();
                      window.dispatchEvent(new CustomEvent("navigate-to-stack", { detail: stack }));
                    }}
                  >
                    <CardContent className="p-3">
                      <div className="flex items-start gap-3">
                        {/* Left side: either preview covers or icon */}
                        {previewCovers.length > 0 ? (
                          <div className="flex items-center gap-0.5 shrink-0">
                            {previewCovers.map((coverUrl, index) => (
                              <div
                                key={index}
                                className="w-6 h-8 rounded bg-gray-800 overflow-hidden"
                              >
                                <CoverImage
                                  src={coverUrl}
                                  alt=""
                                  className="w-full h-full object-cover"
                                  fallbackLogoSize="w-3 h-3"
                                />
                              </div>
                            ))}
                          </div>
                        ) : (
                          <div className="w-10 h-10 rounded-lg bg-[#00ff00]/10 flex items-center justify-center border border-[#00ff00]/30 shrink-0">
                            <LibraryIcon size={20} className="text-[#00ff00]" />
                          </div>
                        )}
                        <div className="flex-1 min-w-0">
                          <P className="font-medium truncate text-white font-mono text-sm">{stack.name}</P>
                          <div className="flex items-center gap-2 mt-0.5">
                            <Small className="text-[#00ff00] font-mono text-[10px]">
                              {stack.itemCount || 0} items
                            </Small>
                            {(stack.upvotes ?? 0) > 0 && (
                              <Small className="text-gray-500 font-mono text-[10px]">
                                ▲ {stack.upvotes}
                              </Small>
                            )}
                          </div>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                );
              })
            )}
            {userStacks && userStacks.length > 20 && (
              <Small className="text-gray-500 font-mono text-center block">
                +{userStacks.length - 20} more stacks
              </Small>
            )}
          </div>
        )}

        {/* Grids Tab */}
        {profileSubTab === "grids" && (
          <div className="space-y-2">
            {!userGrids || userGrids.length === 0 ? (
              <Card className="bg-[#0a0a0a] border-2 border-[#00ff00]/30">
                <CardContent className="p-8 text-center">
                  <div className="w-16 h-16 mx-auto mb-3 rounded-full bg-[#00ff00]/10 flex items-center justify-center border-2 border-dashed border-[#00ff00]/30">
                    <GridIcon size={28} className="text-[#00ff00]/60" />
                  </div>
                  <P className="text-[#00ff00] font-mono">No grids yet</P>
                  <Small className="text-gray-500 font-mono">This user hasn&apos;t created any grids</Small>
                </CardContent>
              </Card>
            ) : (
              userGrids.filter(g => g.visibility !== "hidden").slice(0, 20).map((grid) => (
                <Card
                  key={grid.id}
                  className="bg-[#0a0a0a] border-2 border-[#00ff00]/30 hover:border-[#00ff00] hover:shadow-[0_0_15px_rgba(0,255,0,0.3)] transition-all cursor-pointer"
                  onClick={() => {
                    onClose();
                    window.dispatchEvent(new CustomEvent("navigate-to-grid", { detail: { id: grid.id } }));
                  }}
                >
                  <CardContent className="p-3">
                    <div className="flex items-center gap-3">
                      <GridPreviewThumb grid={grid} />
                      <div className="flex-1 min-w-0">
                        <P className="font-medium truncate text-white font-mono text-sm">{grid.name}</P>
                        <div className="flex items-center gap-2 mt-0.5">
                          <Small className="text-[#00ff00] font-mono text-[10px]">
                            {grid.size}×{grid.size}
                          </Small>
                          <Small className="text-gray-500 font-mono text-[10px]">
                            {grid.cellCount || 0} cells
                          </Small>
                          {grid.upvoteCount > 0 && (
                            <Small className="text-gray-500 font-mono text-[10px]">
                              ▲ {grid.upvoteCount}
                            </Small>
                          )}
                        </div>
                      </div>
                    </div>
                  </CardContent>
                </Card>
              ))
            )}
            {userGrids && userGrids.filter(g => g.visibility !== "hidden").length > 20 && (
              <Small className="text-gray-500 font-mono text-center block">
                +{userGrids.filter(g => g.visibility !== "hidden").length - 20} more grids
              </Small>
            )}
          </div>
        )}
      </div>
    </div>
  );

  const memberUpvoteModal = (
    <MemberUpvoteModal
      isOpen={showMemberUpvoteModal}
      onClose={() => setShowMemberUpvoteModal(false)}
      onUpvote={handleSubmitMemberUpvote}
      isUpvoting={isUpvoting}
      memberName={displayName || member.username || `Member ${member.memberId}`}
      currentUpvotes={member.address ? getMemberUpvotes(member.address) : 0}
    />
  );

  // Render via portal to escape any parent overflow/z-index constraints
  if (typeof document !== 'undefined') {
    return (
      <>
        {createPortal(modalContent, document.body)}
        {createPortal(memberUpvoteModal, document.body)}
      </>
    );
  }
  return <>{modalContent}{memberUpvoteModal}</>;
}
src/features/app/components/web-profile-editor.tsx
"use client";

import { useState, useRef } from "react";
import { createPortal } from "react-dom";
import { Card, CardContent, P, Small } from "@neynar/ui";
import { UploadIcon, WebIcon } from "@/components/icons/net-library-icons";

interface WebProfileEditorProps {
  isOpen: boolean;
  onClose: () => void;
  address: string;
  memberId: number;
  wid: string;
  currentUsername?: string;
  currentPfpUrl?: string;
  onSuccess: () => void;
}

export function WebProfileEditor({
  isOpen,
  onClose,
  address,
  memberId,
  wid,
  currentUsername,
  currentPfpUrl,
  onSuccess,
}: WebProfileEditorProps) {
  const [username, setUsername] = useState(currentUsername || "");
  const [pfpUrl, setPfpUrl] = useState(currentPfpUrl || "");
  const [previewUrl, setPreviewUrl] = useState(currentPfpUrl || "");
  const [isSaving, setIsSaving] = useState(false);
  const [isUploading, setIsUploading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [successMsg, setSuccessMsg] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  // Username validation feedback
  const getUsernameFeedback = (): { valid: boolean; message: string } | null => {
    if (!username) return null;
    if (username.length < 3) {
      return { valid: false, message: "At least 3 characters" };
    }
    if (username.length > 20) {
      return { valid: false, message: "Max 20 characters" };
    }
    if (!/^[a-zA-Z0-9_]+$/.test(username)) {
      return { valid: false, message: "Letters, numbers, underscores only" };
    }
    return { valid: true, message: `@${username.toLowerCase()} available` };
  };

  const usernameFeedback = getUsernameFeedback();

  // Handle file upload for PFP
  const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // Validate file type
    const validTypes = ["image/jpeg", "image/png", "image/webp", "image/gif"];
    if (!validTypes.includes(file.type)) {
      setError("Please use JPG, PNG, WebP, or GIF format");
      return;
    }

    // Validate file size (max 2MB)
    if (file.size > 2 * 1024 * 1024) {
      setError("Image must be under 2MB");
      return;
    }

    setIsUploading(true);
    setError(null);

    try {
      // For now, convert to base64 data URL
      // In production, you'd upload to a proper storage service
      const reader = new FileReader();
      reader.onload = () => {
        const dataUrl = reader.result as string;
        setPfpUrl(dataUrl);
        setPreviewUrl(dataUrl);
        setIsUploading(false);
      };
      reader.onerror = () => {
        setError("Failed to read file");
        setIsUploading(false);
      };
      reader.readAsDataURL(file);
    } catch {
      setError("Failed to process image");
      setIsUploading(false);
    }
  };

  // Handle URL input for PFP
  const handlePfpUrlChange = (url: string) => {
    setPfpUrl(url);
    // Only update preview if it's a valid URL
    if (url.startsWith("https://") || url.startsWith("data:")) {
      setPreviewUrl(url);
    } else {
      setPreviewUrl("");
    }
  };

  // Save profile
  const handleSave = async () => {
    setIsSaving(true);
    setError(null);
    setSuccessMsg(null);

    try {
      const updates: { address: string; customUsername?: string; customPfpUrl?: string } = {
        address,
      };

      // Only include fields that changed
      if (username !== currentUsername) {
        updates.customUsername = username || undefined; // undefined clears it
      }
      if (pfpUrl !== currentPfpUrl) {
        updates.customPfpUrl = pfpUrl || undefined; // undefined clears it
      }

      // Check if anything changed
      if (!updates.customUsername && !updates.customPfpUrl) {
        setError("No changes to save");
        setIsSaving(false);
        return;
      }

      const response = await fetch("/api/profile", {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(updates),
      });

      const data = await response.json();

      if (!response.ok) {
        throw new Error(data.error || "Failed to update profile");
      }

      setSuccessMsg("Profile updated!");
      setTimeout(() => {
        onSuccess();
        onClose();
      }, 1000);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to save");
    } finally {
      setIsSaving(false);
    }
  };

  if (!isOpen) return null;

  const modalContent = (
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/95"
      onClick={onClose}
    >
      <div
        className="w-full max-w-sm bg-[#0a0a0a] border-2 border-yellow-500/30 rounded-xl overflow-hidden shadow-[0_0_30px_rgba(234,179,8,0.2)]"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 py-3 border-b border-yellow-500/20 bg-yellow-500/5">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-2">
              <WebIcon size={18} className="text-yellow-400" />
              <P className="text-yellow-400 font-mono font-medium">Edit Profile</P>
            </div>
            <button
              onClick={onClose}
              className="w-8 h-8 flex items-center justify-center rounded-full hover:bg-white/10 text-gray-400 hover:text-white transition-colors"
            >
              ✕
            </button>
          </div>
          <Small className="text-gray-500 font-mono mt-1">
            Web ID: {wid} • Member #{memberId}
          </Small>
        </div>

        {/* Content */}
        <div className="p-4 space-y-4">
          {/* Profile Picture Section */}
          <div>
            <Small className="text-gray-400 font-mono uppercase tracking-wider text-[10px] mb-2 block">
              Profile Picture
            </Small>
            <div className="flex items-center gap-4">
              {/* Preview */}
              <div className="w-20 h-20 rounded-full border-2 border-yellow-500/50 overflow-hidden bg-black flex items-center justify-center">
                {previewUrl ? (
                  <img
                    src={previewUrl}
                    alt="PFP preview"
                    className="w-full h-full object-cover"
                    onError={() => setPreviewUrl("")}
                  />
                ) : (
                  <span className="text-3xl">👤</span>
                )}
              </div>

              {/* Upload controls */}
              <div className="flex-1 space-y-2">
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/jpeg,image/png,image/webp,image/gif"
                  onChange={handleFileSelect}
                  className="hidden"
                />
                <button
                  onClick={() => fileInputRef.current?.click()}
                  disabled={isUploading}
                  className="w-full py-2 bg-yellow-500/10 border border-yellow-500/30 rounded-lg text-yellow-400 font-mono text-sm hover:bg-yellow-500/20 transition-colors disabled:opacity-50"
                >
                  {isUploading ? "Uploading..." : <><UploadIcon size={14} className="inline mr-1" /> Upload Image</>}
                </button>
                <Small className="text-gray-500 font-mono text-[9px] text-center block">
                  JPG, PNG, WebP, GIF • Max 2MB
                </Small>
              </div>
            </div>

            {/* URL input */}
            <div className="mt-3">
              <input
                type="text"
                value={pfpUrl}
                onChange={(e) => handlePfpUrlChange(e.target.value)}
                placeholder="Or paste image URL (https://...)"
                className="w-full px-3 py-2 bg-black/50 border border-yellow-500/20 rounded-lg text-white font-mono text-xs focus:border-yellow-500 focus:outline-none placeholder:text-gray-600"
              />
            </div>
          </div>

          {/* Username Section */}
          <div>
            <Small className="text-gray-400 font-mono uppercase tracking-wider text-[10px] mb-2 block">
              Display Name
            </Small>
            <input
              type="text"
              value={username}
              onChange={(e) => setUsername(e.target.value.replace(/[^a-zA-Z0-9_]/g, ""))}
              placeholder="Choose a username"
              maxLength={20}
              className="w-full px-3 py-2 bg-black/50 border border-yellow-500/20 rounded-lg text-white font-mono focus:border-yellow-500 focus:outline-none placeholder:text-gray-600"
            />
            {/* Feedback */}
            {usernameFeedback && (
              <Small
                className={`font-mono text-[10px] mt-1 block ${
                  usernameFeedback.valid ? "text-green-400" : "text-red-400"
                }`}
              >
                {usernameFeedback.valid ? "✓" : "✕"} {usernameFeedback.message}
              </Small>
            )}
            <Small className="text-gray-500 font-mono text-[9px] mt-1 block">
              3-20 characters, letters, numbers, underscores
            </Small>
          </div>

          {/* Info card */}
          <Card className="bg-yellow-500/5 border border-yellow-500/20">
            <CardContent className="p-3">
              <Small className="text-yellow-400/80 font-mono text-[10px]">
                💡 As a web platform user, you can customize your profile.
                Farcaster and Base App users get their identity from those platforms.
              </Small>
            </CardContent>
          </Card>

          {/* Error/Success messages */}
          {error && (
            <div className="p-2 rounded-lg bg-red-500/10 border border-red-500/30">
              <Small className="text-red-400 font-mono text-[11px]">{error}</Small>
            </div>
          )}
          {successMsg && (
            <div className="p-2 rounded-lg bg-green-500/10 border border-green-500/30">
              <Small className="text-green-400 font-mono text-[11px]">{successMsg}</Small>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-4 py-3 border-t border-yellow-500/20 flex gap-2">
          <button
            onClick={onClose}
            className="flex-1 py-2 rounded-lg bg-[#1a1a1a] text-gray-400 font-mono hover:bg-[#222] transition-colors"
          >
            Cancel
          </button>
          <button
            onClick={handleSave}
            disabled={isSaving || (usernameFeedback !== null && !usernameFeedback.valid)}
            className="flex-1 py-2 rounded-lg bg-yellow-500 text-black font-mono font-bold hover:bg-yellow-400 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            {isSaving ? "Saving..." : "Save Profile"}
          </button>
        </div>
      </div>
    </div>
  );

  return createPortal(modalContent, document.body);
}
src/features/app/components/welcome-popup.tsx
"use client";

import { useState, useEffect, useRef } from "react";
import { H4, P, Small } from "@neynar/ui";
import { usePlatformStatus, Platform } from "@/hooks/use-platform-status";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { useAccount } from "wagmi";
import { LinkFarcasterModal } from "./link-farcaster-modal";
import { LinkBaseModal } from "./link-base-modal";
import { detectDesktopBrowser } from "@/lib/app-mode";
import { LinkIcon, PartyIcon, CheckCircleIcon, FarcasterIcon, BaseIcon, WebIcon, LibraryIcon } from "@/components/icons/net-library-icons";

/**
 * Welcome Popup Component
 *
 * Shows contextual welcome messages based on:
 * - Current platform (Farcaster or Base App)
 * - Membership status
 * - Account linking status
 *
 * Flow:
 * 1. First visit → Welcome message with platform name
 * 2. Member on FC, opening Base → Prompt to link Base wallet (if needed)
 * 3. Member found via FID on Base App → AUTO-LINK silently (no prompt!)
 * 4. Non-member → CTA to become member OR dismiss ("just here for the vibes")
 *
 * IMPORTANT: We auto-link Base App wallets for Farcaster members detected via FID.
 * No popup is shown - we just link and show a toast notification.
 */

type PopupState =
  | "welcome"           // Initial welcome message
  | "link-base"         // Prompt FC member to link Base wallet
  | "auto-linked"       // Auto-linked Base wallet for FC member (toast notification)
  | "become-member"     // Non-member CTA (includes option to claim existing FC membership)
  | "hidden";           // No popup

interface WelcomePopupProps {
  onNavigateToMembership?: () => void;
}

export function WelcomePopup({ onNavigateToMembership }: WelcomePopupProps) {
  const {
    currentPlatform,
    isFarcasterVerified,
    isBaseAppVerified,
    hasLinkedAccounts,
    hasSeenWelcome,
    hasDismissedLinkPrompt,
    hasDismissedMembershipPrompt,
    isFirstVisitOnPlatform,
    isLoading,
    dismissWelcome,
    dismissLinkPrompt,
    dismissMembershipPrompt,
    markPlatformSeen,
  } = usePlatformStatus();

  const { isMember, matchType, registeredAddress, linkedAddresses, refresh: refreshMembership, isLoading: isMembershipLoading } = useMembershipStatus();
  const { address, isConnected } = useAccount();

  const [popupState, setPopupState] = useState<PopupState>("hidden");
  const [showLinkFarcasterModal, setShowLinkFarcasterModal] = useState(false);
  const [showLinkBaseModal, setShowLinkBaseModal] = useState(false);
  const [autoLinkMessage, setAutoLinkMessage] = useState<string | null>(null);

  // Track if we've already shown a popup this session to prevent re-showing
  const [hasShownPopup, setHasShownPopup] = useState(false);

  // Track if we've already attempted auto-link this session
  const hasAttemptedAutoLink = useRef(false);

  // Detect if we're in an actual app context (not desktop browser)
  // Desktop browsers should NOT show welcome/linking popups since they can't properly
  // authenticate or link accounts - those flows require the mobile app contexts
  const [isDesktopBrowser, setIsDesktopBrowser] = useState(false);

  useEffect(() => {
    // Run detection on client side only
    setIsDesktopBrowser(detectDesktopBrowser());
  }, []);

  // Auto-link Base App wallet for Farcaster members found via FID
  // This happens silently without a popup - we just link and notify
  useEffect(() => {
    // Only run once per session
    if (hasAttemptedAutoLink.current) return;

    // Skip if still loading or not on Base App
    if (isLoading || currentPlatform !== "base-app") return;

    // Skip if no address or not a member found via FID
    if (!address || !isMember || matchType !== "fid") return;

    // Check if current wallet is already linked
    const currentAddressLower = address.toLowerCase();
    const isAlreadyLinked =
      (registeredAddress && registeredAddress.toLowerCase() === currentAddressLower) ||
      (linkedAddresses && linkedAddresses.some(a => a && a.toLowerCase() === currentAddressLower));

    if (isAlreadyLinked) {
      console.log("[WelcomePopup] Base wallet already linked, no auto-link needed");
      return;
    }

    // Auto-link this wallet!
    hasAttemptedAutoLink.current = true;
    console.log("[WelcomePopup] Auto-linking Base wallet for FID-found member");

    fetch("/api/link-address", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ address }),
    })
      .then(res => res.json())
      .then(data => {
        if (data.success) {
          console.log("[WelcomePopup] Auto-link successful!");
          setAutoLinkMessage("Welcome back! We automatically linked your Base wallet to your Farcaster membership.");
          setPopupState("auto-linked");
          setHasShownPopup(true);
          // Dismiss link prompt so we don't show other link prompts
          dismissLinkPrompt();
          // Refresh membership to update linked addresses
          refreshMembership();
        } else {
          console.log("[WelcomePopup] Auto-link failed:", data.error);
        }
      })
      .catch(err => {
        console.error("[WelcomePopup] Auto-link error:", err);
      });
  }, [isLoading, currentPlatform, address, isMember, matchType, registeredAddress, linkedAddresses, dismissLinkPrompt, refreshMembership]);

  // Determine what popup to show based on state - only runs once when data is ready
  useEffect(() => {
    // Don't recalculate if we've already shown something
    if (hasShownPopup) {
      return;
    }

    if (isLoading || !currentPlatform) {
      // Still loading, keep hidden but don't mark as shown
      return;
    }

    // Skip popups entirely on desktop browsers - they can't properly link/auth
    if (isDesktopBrowser) {
      console.log("[WelcomePopup] Desktop browser detected, skipping popups");
      setPopupState("hidden");
      return;
    }

    // Debug logging to help trace popup decisions
    console.log("[WelcomePopup] Evaluating conditions:", {
      currentPlatform,
      isFirstVisitOnPlatform,
      hasSeenWelcome,
      isMember,
      hasLinkedAccounts,
      hasDismissedLinkPrompt,
      isBaseAppVerified,
      isFarcasterVerified,
      isConnected,
      hasDismissedMembershipPrompt,
      matchType,
    });

    // Priority 1: Member linking prompts (if not dismissed)
    // Members should see linking prompts BEFORE generic welcome
    if (isMember && !hasDismissedLinkPrompt) {
      if (currentPlatform === "farcaster" && !isBaseAppVerified) {
        // On Farcaster but no Base wallet linked → prompt to link Base
        console.log("[WelcomePopup] Showing: link-base (member priority)");
        setPopupState("link-base");
        setHasShownPopup(true);
        return;
      }
      // NOTE: We removed "link-farcaster" prompt for Base App users.
      // If they're a member found via FID, auto-link handles it above.
      // If they're a member found by address, they don't need FC linking.
    }

    // Priority 2: First visit welcome (if not seen) - only for non-members or fully verified members
    if (isFirstVisitOnPlatform && !hasSeenWelcome) {
      console.log("[WelcomePopup] Showing: welcome");
      setPopupState("welcome");
      setHasShownPopup(true);
      return;
    }

    // Priority 3: Non-member CTA (if not dismissed).
    // Guard: only show after membership has fully loaded. Showing it before the
    // membership query resolves causes a flicker where existing members briefly
    // see the "Join Net Library" popup before it auto-hides.
    // Note: we do NOT set hasShownPopup=true here so that if isMember later becomes
    // true (membership loaded after the popup was shown), the effect re-runs and
    // hides the popup automatically.
    if (!isMember && !isMembershipLoading && isConnected && !hasDismissedMembershipPrompt) {
      console.log("[WelcomePopup] Showing: become-member (membership confirmed not loaded)");
      setPopupState("become-member");
      return;
    }

    // Nothing to show - DON'T mark hasShownPopup so we can re-evaluate if state changes
    console.log("[WelcomePopup] Nothing to show (fully verified or already seen)");
    setPopupState("hidden");
  }, [
    isLoading,
    isMembershipLoading,
    currentPlatform,
    isFirstVisitOnPlatform,
    hasSeenWelcome,
    isMember,
    hasLinkedAccounts,
    hasDismissedLinkPrompt,
    isBaseAppVerified,
    isFarcasterVerified,
    isConnected,
    hasDismissedMembershipPrompt,
    hasShownPopup,
    isDesktopBrowser,
    matchType,
  ]);

  const handleDismissWelcome = () => {
    dismissWelcome();
    if (currentPlatform) markPlatformSeen(currentPlatform);
    setPopupState("hidden");
  };

  const handleDismissLinkPrompt = () => {
    dismissLinkPrompt();
    setPopupState("hidden");
  };

  const handleDismissMembershipPrompt = () => {
    // Call all available dismiss mechanisms for redundancy —
    // if one storage method fails (e.g. localStorage blocked in mini-app webview),
    // another may succeed (server-side KV via dismissMembershipPrompt).
    dismissMembershipPrompt(); // writes to localStorage + server-side KV
    dismissWelcome();          // belt-and-suspenders: also mark welcome as seen
    setHasShownPopup(true);    // prevent re-show this session
    setPopupState("hidden");
  };

  const handleBecomeMember = () => {
    setPopupState("hidden");
    onNavigateToMembership?.();
  };

  const handleLinkBase = () => {
    setShowLinkBaseModal(true);
  };

  const getPlatformDisplayName = (platform: Platform): string => {
    return platform === "farcaster" ? "Farcaster" : platform === "web" ? "Web" : "Base";
  };

  const PlatformIconComponent = ({ platform }: { platform: Platform }) => {
    if (platform === "farcaster") return <FarcasterIcon size={20} className="text-purple-400" />;
    if (platform === "web") return <WebIcon size={20} className="text-yellow-400" />;
    return <BaseIcon size={20} className="text-blue-400" />;
  };

  const getPlatformColor = (platform: Platform): string => {
    return platform === "farcaster" ? "purple" : platform === "web" ? "yellow" : "blue";
  };

  if (popupState === "hidden") {
    return (
      <>
        {/* Link Farcaster Modal (can be triggered later) */}
        <LinkFarcasterModal
          isOpen={showLinkFarcasterModal}
          onClose={() => setShowLinkFarcasterModal(false)}
          onSuccess={() => {
            setShowLinkFarcasterModal(false);
            dismissLinkPrompt();
          }}
        />
      </>
    );
  }

  const platformColor = currentPlatform ? getPlatformColor(currentPlatform) : "green";
  const borderColor = platformColor === "purple" ? "border-purple-500/30" : platformColor === "blue" ? "border-blue-500/30" : platformColor === "yellow" ? "border-yellow-500/30" : "border-[#00ff00]/30";
  const bgAccent = platformColor === "purple" ? "bg-purple-500/5" : platformColor === "blue" ? "bg-blue-500/5" : platformColor === "yellow" ? "bg-yellow-500/5" : "bg-[#00ff00]/5";
  const textAccent = platformColor === "purple" ? "text-purple-400" : platformColor === "blue" ? "text-blue-400" : platformColor === "yellow" ? "text-yellow-400" : "text-[#00ff00]";
  const buttonBg = platformColor === "purple" ? "bg-purple-500 hover:bg-purple-400" : platformColor === "blue" ? "bg-blue-500 hover:bg-blue-400" : platformColor === "yellow" ? "bg-yellow-500 hover:bg-yellow-400" : "bg-[#00ff00] hover:bg-[#00dd00]";

  // Handle dismiss when tapping outside the popup
  const handleOverlayClick = () => {
    if (popupState === "welcome") {
      handleDismissWelcome();
    } else if (popupState === "link-base") {
      handleDismissLinkPrompt();
    } else if (popupState === "auto-linked") {
      setPopupState("hidden");
    } else if (popupState === "become-member") {
      handleDismissMembershipPrompt();
    }
  };

  return (
    <>
      {/* Popup Overlay - tap outside to dismiss */}
      <div
        className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4"
        onClick={handleOverlayClick}
      >
        <div
          className={`bg-[#0a0a0a] border ${borderColor} rounded-xl max-w-sm w-full overflow-hidden`}
          onClick={(e) => e.stopPropagation()}
        >
          {/* Header */}
          <div className={`px-4 py-3 border-b ${borderColor} flex items-center justify-between ${bgAccent}`}>
            <div className="flex items-center gap-2">
              {currentPlatform ? <PlatformIconComponent platform={currentPlatform} /> : <LibraryIcon size={20} className="text-[#00ff00]" />}
              <H4 className={`${textAccent} font-mono`}>
                {popupState === "welcome" && "Welcome!"}
                {popupState === "link-base" && "Link Base Wallet"}
                {popupState === "auto-linked" && "Welcome Back!"}
                {popupState === "become-member" && "Join Net Library"}
              </H4>
            </div>
          </div>

          {/* Content */}
          <div className="p-4">
            {/* Welcome State */}
            {popupState === "welcome" && currentPlatform && (
              <>
                <div className="text-center mb-4">
                  <div className="text-5xl mb-3 text-[#00ff00] flex justify-center"><LibraryIcon size={56} /></div>
                  <P className="text-white font-mono text-lg mb-2">
                    Welcome to Net Library on {getPlatformDisplayName(currentPlatform)}!
                  </P>
                  <Small className="text-gray-400 font-mono block">
                    Your decentralized onchain library, powered by Net Protocol.
                  </Small>
                </div>
                <button
                  onClick={handleDismissWelcome}
                  className={`w-full py-3 rounded-lg ${buttonBg} text-white font-mono font-bold transition-colors`}
                >
                  Let&apos;s Go!
                </button>
              </>
            )}

            {/* Link Base Wallet State (for Farcaster members) */}
            {popupState === "link-base" && (
              <>
                <P className="text-gray-300 font-mono text-sm mb-4">
                  We noticed you&apos;re a Net Library member! Link your Base wallet to access your membership from the Base App too.
                </P>
                <div className="p-3 rounded-lg bg-blue-500/10 border border-blue-500/30 mb-4">
                  <Small className="text-blue-400 font-mono flex items-center gap-1">
                    <LinkIcon size={14} /> Same membership, both platforms.
                  </Small>
                </div>
                <div className="flex gap-2">
                  <button
                    onClick={handleDismissLinkPrompt}
                    className="flex-1 py-3 rounded-lg bg-[#1a1a1a] text-gray-400 font-mono hover:bg-[#222] transition-colors"
                  >
                    Maybe Later
                  </button>
                  <button
                    onClick={handleLinkBase}
                    className="flex-1 py-3 rounded-lg bg-blue-500 text-white font-mono font-bold hover:bg-blue-400 transition-colors"
                  >
                    Link Wallet
                  </button>
                </div>
              </>
            )}

            {/* Auto-Linked State (for FC members accessing via Base App) */}
            {popupState === "auto-linked" && (
              <>
                <div className="text-center mb-4">
                  <LinkIcon size={48} className="text-[#00ff00] mx-auto mb-3" />
                  <P className="text-white font-mono text-lg mb-2">
                    {autoLinkMessage || "Your Base wallet has been linked!"}
                  </P>
                  <Small className="text-gray-400 font-mono block">
                    We detected your Farcaster membership and linked this wallet automatically.
                  </Small>
                </div>
                <div className="p-3 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 mb-4">
                  <Small className="text-[#00ff00] font-mono flex items-center gap-1">
                    <CheckCircleIcon size={12} /> Same membership, both platforms!
                  </Small>
                </div>
                <button
                  onClick={() => setPopupState("hidden")}
                  className="w-full py-3 rounded-lg bg-[#00ff00] text-black font-mono font-bold hover:bg-[#00dd00] transition-colors"
                >
                  Got it!
                </button>
              </>
            )}

            {/* Become Member State */}
            {popupState === "become-member" && (
              <>
                <P className="text-gray-300 font-mono text-sm mb-4">
                  Get your own onchain library card and unlock member benefits!
                </P>
                <div className="p-3 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 mb-4">
                  <Small className="text-[#00ff00] font-mono flex items-center gap-1 mb-1">
                    <PartyIcon size={14} /> Member perks include:
                  </Small>
                  <Small className="text-gray-400 font-mono block">
                    • Personalized library card NFT<br />
                    • Upload your own books<br />
                    • Access to premium features
                  </Small>
                </div>
                <div className="flex gap-2">
                  <button
                    onClick={handleDismissMembershipPrompt}
                    className="flex-1 py-3 rounded-lg bg-[#1a1a1a] text-gray-400 font-mono hover:bg-[#222] transition-colors text-sm"
                  >
                    Just vibing 😎
                  </button>
                  <button
                    onClick={handleBecomeMember}
                    className="flex-1 py-3 rounded-lg bg-[#00ff00] text-black font-mono font-bold hover:bg-[#00dd00] transition-colors"
                  >
                    Become Member
                  </button>
                </div>
                {/* "Already a member" option - dismisses popup and remembers */}
                <div className="mt-4 pt-4 border-t border-gray-800">
                  <button
                    onClick={handleDismissMembershipPrompt}
                    className="w-full py-2.5 rounded-lg bg-[#1a1a1a] border border-gray-700 text-gray-300 font-mono text-sm hover:bg-[#222] transition-colors"
                  >
                    I&apos;m already a member
                  </button>
                </div>
              </>
            )}
          </div>
        </div>
      </div>

      {/* Link Farcaster Modal - for Base App members linking their FC account */}
      <LinkFarcasterModal
        isOpen={showLinkFarcasterModal}
        onClose={() => setShowLinkFarcasterModal(false)}
        onSuccess={() => {
          setShowLinkFarcasterModal(false);
          dismissLinkPrompt();
        }}
      />

      {/* Link Base Modal */}
      <LinkBaseModal
        isOpen={showLinkBaseModal}
        onClose={() => setShowLinkBaseModal(false)}
        onSuccess={() => {
          setShowLinkBaseModal(false);
          dismissLinkPrompt();
        }}
      />
    </>
  );
}
src/features/app/components/zip-import-modal.tsx
"use client";

import { useState, useCallback, useRef } from "react";
import { P, Small, H3 } from "@neynar/ui";
import {
  FolderIcon,
  UploadIcon,
  WarningIcon,
  CheckCircleIcon,
  CloseIcon,
} from "@/components/icons/net-library-icons";
import {
  type FileSystemItem,
  type FileTreeNode,
  buildFileTree,
  shouldIgnorePath,
} from "@/features/app/types-filesystem";
import { FolderTreeView } from "./folder-tree-view";
import {
  FREE_TIER_MEMBER_MAX_SIZE,
  FREE_TIER_NON_MEMBER_MAX_SIZE,
} from "@/lib/net-protocol";

// ============================================
// Types
// ============================================

interface ExtractedFile {
  path: string;
  fileName: string;
  parentPath: string;
  content: Uint8Array;
  size: number;
  compressedSize: number;
}

interface ZipImportModalProps {
  isOpen: boolean;
  onClose: () => void;
  isMember: boolean;
  onUploadFile: (
    file: File,
    metadata: {
      path: string;
      fileName: string;
      fileSize: number;
      mimeType: string;
    }
  ) => Promise<{ success: boolean; contentKey?: string; error?: string }>;
  onComplete: () => void;
}

type UploadStep = "select" | "extracting" | "preview" | "uploading" | "complete";

// ============================================
// Helpers
// ============================================

function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

function getParentPath(path: string): string {
  const lastSlash = path.lastIndexOf("/");
  if (lastSlash <= 0) return "/";
  return path.substring(0, lastSlash);
}

function getMimeType(fileName: string): string {
  const ext = fileName.split(".").pop()?.toLowerCase();
  const mimeMap: Record<string, string> = {
    txt: "text/plain",
    md: "text/markdown",
    json: "application/json",
    js: "text/javascript",
    ts: "text/typescript",
    tsx: "text/typescript",
    jsx: "text/javascript",
    html: "text/html",
    css: "text/css",
    pdf: "application/pdf",
    png: "image/png",
    jpg: "image/jpeg",
    jpeg: "image/jpeg",
    gif: "image/gif",
    webp: "image/webp",
    svg: "image/svg+xml",
    mp3: "audio/mpeg",
    wav: "audio/wav",
    mp4: "video/mp4",
    webm: "video/webm",
    zip: "application/zip",
    tar: "application/x-tar",
    gz: "application/gzip",
  };
  return mimeMap[ext || ""] || "application/octet-stream";
}

// ============================================
// Component
// ============================================

export function ZipImportModal({
  isOpen,
  onClose,
  isMember,
  onUploadFile,
  onComplete,
}: ZipImportModalProps) {
  const [step, setStep] = useState<UploadStep>("select");
  const [files, setFiles] = useState<ExtractedFile[]>([]);
  const [excludedPaths, setExcludedPaths] = useState<Set<string>>(new Set());
  const [uploadProgress, setUploadProgress] = useState({ current: 0, total: 0, currentFile: "" });
  const [uploadResults, setUploadResults] = useState<{ success: number; failed: number; errors: string[] }>({
    success: 0,
    failed: 0,
    errors: [],
  });
  const [isDragging, setIsDragging] = useState(false);
  const [extractionError, setExtractionError] = useState<string | null>(null);
  const [zipFileName, setZipFileName] = useState<string>("");
  const fileInputRef = useRef<HTMLInputElement>(null);
  const abortRef = useRef(false);

  const maxFileSize = isMember ? FREE_TIER_MEMBER_MAX_SIZE : FREE_TIER_NON_MEMBER_MAX_SIZE;

  // Reset state when modal closes
  const handleClose = useCallback(() => {
    abortRef.current = true;
    setStep("select");
    setFiles([]);
    setExcludedPaths(new Set());
    setUploadProgress({ current: 0, total: 0, currentFile: "" });
    setUploadResults({ success: 0, failed: 0, errors: [] });
    setExtractionError(null);
    setZipFileName("");
    onClose();
  }, [onClose]);

  // Extract files from ZIP
  const extractZip = useCallback(async (zipFile: File) => {
    setStep("extracting");
    setZipFileName(zipFile.name);
    setExtractionError(null);

    try {
      // Dynamic import of JSZip
      const JSZip = (await import("jszip")).default;
      const zip = await JSZip.loadAsync(zipFile);

      const extracted: ExtractedFile[] = [];

      // Get the root folder name from the ZIP (if exists)
      const entries = Object.keys(zip.files);
      let rootPrefix = "";

      // Check if all entries share a common root folder
      if (entries.length > 0) {
        const firstEntry = entries[0];
        const firstSlash = firstEntry.indexOf("/");
        if (firstSlash > 0) {
          const potentialRoot = firstEntry.substring(0, firstSlash + 1);
          const allShareRoot = entries.every(e => e.startsWith(potentialRoot) || e === potentialRoot.slice(0, -1));
          if (allShareRoot) {
            rootPrefix = potentialRoot;
          }
        }
      }

      for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
        // Skip directories
        if (zipEntry.dir) continue;

        // Normalize path - remove root prefix if exists, ensure starts with /
        let normalizedPath = relativePath;
        if (rootPrefix && normalizedPath.startsWith(rootPrefix)) {
          normalizedPath = normalizedPath.substring(rootPrefix.length);
        }
        if (!normalizedPath.startsWith("/")) {
          normalizedPath = "/" + normalizedPath;
        }

        // Skip ignored paths
        if (shouldIgnorePath(normalizedPath)) continue;

        // Extract file content
        const content = await zipEntry.async("uint8array");
        const fileName = normalizedPath.split("/").pop() || "";

        extracted.push({
          path: normalizedPath,
          fileName,
          parentPath: getParentPath(normalizedPath),
          content,
          size: content.length,
          compressedSize: content.length, // JSZip doesn't expose compressed size reliably
        });
      }

      if (extracted.length === 0) {
        setExtractionError("No valid files found in ZIP archive");
        setStep("select");
        return;
      }

      setFiles(extracted);
      setStep("preview");
    } catch (err) {
      console.error("[ZipImportModal] Extraction error:", err);
      setExtractionError(err instanceof Error ? err.message : "Failed to extract ZIP file");
      setStep("select");
    }
  }, []);

  // Handle file input change
  const handleFileInputChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      if (e.target.files && e.target.files.length > 0) {
        const file = e.target.files[0];
        if (file.name.toLowerCase().endsWith(".zip")) {
          extractZip(file);
        } else {
          setExtractionError("Please select a .zip file");
        }
      }
    },
    [extractZip]
  );

  // Handle drag events
  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
  }, []);

  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault();
      e.stopPropagation();
      setIsDragging(false);

      const droppedFiles = e.dataTransfer.files;
      if (droppedFiles.length > 0) {
        const file = droppedFiles[0];
        if (file.name.toLowerCase().endsWith(".zip")) {
          extractZip(file);
        } else {
          setExtractionError("Please drop a .zip file");
        }
      }
    },
    [extractZip]
  );

  // Toggle file exclusion
  const toggleExclude = useCallback((path: string) => {
    setExcludedPaths((prev) => {
      const next = new Set(prev);
      if (next.has(path)) {
        next.delete(path);
      } else {
        next.add(path);
      }
      return next;
    });
  }, []);

  // Build tree for preview
  const previewTree = useCallback((): FileTreeNode[] => {
    const items: FileSystemItem[] = files.map((f) => ({
      contentKey: "",
      addedAt: Date.now(),
      addedBy: "",
      path: f.path,
      fileName: f.fileName,
      fileSize: f.size,
      mimeType: getMimeType(f.fileName),
      isDirectory: false,
      parentPath: f.parentPath,
    }));

    return buildFileTree(items);
  }, [files]);

  // Get files that exceed size limit
  const oversizedFiles = files.filter(
    (f) => !excludedPaths.has(f.path) && f.size > maxFileSize
  );

  // Get included files
  const includedFiles = files.filter((f) => !excludedPaths.has(f.path));
  const totalUncompressedSize = includedFiles.reduce((sum, f) => sum + f.size, 0);
  const totalCompressedSize = includedFiles.reduce((sum, f) => sum + f.compressedSize, 0);

  // Start upload process
  const startUpload = useCallback(async () => {
    abortRef.current = false;
    setStep("uploading");

    const toUpload = files.filter((f) => !excludedPaths.has(f.path));
    setUploadProgress({ current: 0, total: toUpload.length, currentFile: "" });

    const results = { success: 0, failed: 0, errors: [] as string[] };

    for (let i = 0; i < toUpload.length; i++) {
      if (abortRef.current) break;

      const { path, fileName, content, size } = toUpload[i];
      setUploadProgress({
        current: i + 1,
        total: toUpload.length,
        currentFile: path,
      });

      try {
        // Convert Uint8Array to File (cast buffer to ArrayBuffer for TypeScript)
        const mimeType = getMimeType(fileName);
        const blob = new Blob([content.buffer as ArrayBuffer], { type: mimeType });
        const file = new File([blob], fileName, { type: mimeType });

        const result = await onUploadFile(file, {
          path,
          fileName,
          fileSize: size,
          mimeType,
        });

        if (result.success) {
          results.success++;
        } else {
          results.failed++;
          results.errors.push(`${fileName}: ${result.error || "Unknown error"}`);
        }
      } catch (err) {
        results.failed++;
        results.errors.push(`${fileName}: ${err instanceof Error ? err.message : "Upload failed"}`);
      }
    }

    setUploadResults(results);
    setStep("complete");
  }, [files, excludedPaths, onUploadFile]);

  // Handle completion
  const handleComplete = useCallback(() => {
    onComplete();
    handleClose();
  }, [onComplete, handleClose]);

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/90"
      onClick={handleClose}
    >
      <div
        className="w-full max-w-md bg-[#0a0a0a] border border-[#00ff00]/30 rounded-xl overflow-hidden max-h-[80vh] flex flex-col"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Header */}
        <div className="px-4 py-3 border-b border-[#00ff00]/20 flex items-center justify-between shrink-0">
          <H3 className="text-[#00ff00] font-mono tracking-tight text-sm">
            {step === "select" && "Import ZIP File"}
            {step === "extracting" && "Extracting..."}
            {step === "preview" && "Review Files"}
            {step === "uploading" && "Uploading..."}
            {step === "complete" && "Upload Complete"}
          </H3>
          <button
            type="button"
            onClick={handleClose}
            className="text-gray-500 hover:text-white transition-colors"
          >
            <CloseIcon size={20} />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-4">
          {/* Step 1: Select ZIP */}
          {step === "select" && (
            <div className="space-y-4">
              {/* Drag and drop zone */}
              <div
                className={`
                  border-2 border-dashed rounded-lg p-8 text-center cursor-pointer transition-colors
                  ${isDragging ? "border-[#00ff00] bg-[#00ff00]/10" : "border-[#333] hover:border-[#00ff00]/50"}
                `}
                onDragOver={handleDragOver}
                onDragLeave={handleDragLeave}
                onDrop={handleDrop}
                onClick={() => fileInputRef.current?.click()}
              >
                <div className="text-4xl mb-4 text-[#00ff00]/60">
                  <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="mx-auto">
                    <path d="M21 8v13H3V8" />
                    <path d="M1 3h22v5H1z" />
                    <path d="M10 12h4" />
                  </svg>
                </div>
                <P className="text-white font-mono text-sm mb-2">
                  Drag & drop a .zip file here
                </P>
                <Small className="text-gray-500">
                  or click to browse
                </Small>
              </div>

              {/* Hidden file input */}
              <input
                ref={fileInputRef}
                type="file"
                accept=".zip"
                className="hidden"
                onChange={handleFileInputChange}
              />

              {/* Error message */}
              {extractionError && (
                <div className="bg-red-500/10 border border-red-500/30 rounded-lg p-3">
                  <div className="flex items-start gap-2">
                    <WarningIcon size={16} className="text-red-500 shrink-0 mt-0.5" />
                    <Small className="text-red-500">{extractionError}</Small>
                  </div>
                </div>
              )}

              <Small className="text-gray-600 text-center block">
                Files like .git, node_modules, and .env will be automatically excluded
              </Small>
            </div>
          )}

          {/* Step 1.5: Extracting */}
          {step === "extracting" && (
            <div className="space-y-4 text-center py-8">
              <div className="w-16 h-16 mx-auto bg-[#00ff00]/20 rounded-full flex items-center justify-center animate-pulse">
                <FolderIcon size={28} className="text-[#00ff00]" />
              </div>
              <P className="text-white font-mono text-sm">
                Extracting {zipFileName}...
              </P>
              <Small className="text-gray-500">
                This may take a moment for large archives
              </Small>
            </div>
          )}

          {/* Step 2: Preview */}
          {step === "preview" && (
            <div className="space-y-4">
              {/* Summary stats */}
              <div className="grid grid-cols-3 gap-2 text-center">
                <div className="bg-[#1a1a1a] rounded-lg p-2">
                  <P className="text-[#00ff00] font-mono text-lg font-bold">
                    {includedFiles.length}
                  </P>
                  <Small className="text-gray-500">Files</Small>
                </div>
                <div className="bg-[#1a1a1a] rounded-lg p-2">
                  <P className="text-[#00ff00] font-mono text-lg font-bold">
                    {formatFileSize(totalUncompressedSize)}
                  </P>
                  <Small className="text-gray-500">Uncompressed</Small>
                </div>
                <div className="bg-[#1a1a1a] rounded-lg p-2">
                  <P className="text-[#00ff00]/70 font-mono text-lg font-bold">
                    {formatFileSize(totalCompressedSize)}
                  </P>
                  <Small className="text-gray-500">Compressed</Small>
                </div>
              </div>

              {/* Oversized files warning */}
              {oversizedFiles.length > 0 && (
                <div className="bg-yellow-500/10 border border-yellow-500/30 rounded-lg p-3">
                  <div className="flex items-start gap-2">
                    <WarningIcon size={16} className="text-yellow-500 shrink-0 mt-0.5" />
                    <div>
                      <P className="text-yellow-500 font-mono text-xs font-bold mb-1">
                        {oversizedFiles.length} file(s) exceed the {formatFileSize(maxFileSize)} limit
                      </P>
                      <Small className="text-yellow-500/70">
                        {oversizedFiles.slice(0, 3).map((f) => f.fileName).join(", ")}
                        {oversizedFiles.length > 3 && ` and ${oversizedFiles.length - 3} more`}
                      </Small>
                    </div>
                  </div>
                </div>
              )}

              {/* File tree */}
              <div className="max-h-64 overflow-y-auto">
                <FolderTreeView
                  nodes={previewTree()}
                  onFileClick={() => {}}
                  expandedByDefault={files.length < 50}
                  excludedPaths={excludedPaths}
                  onToggleExclude={toggleExclude}
                />
              </div>

              {/* Excluded files count */}
              {excludedPaths.size > 0 && (
                <Small className="text-gray-500 text-center block">
                  {excludedPaths.size} file(s) excluded from upload
                </Small>
              )}
            </div>
          )}

          {/* Step 3: Uploading */}
          {step === "uploading" && (
            <div className="space-y-4">
              <div className="text-center">
                <P className="text-white font-mono text-sm mb-2">
                  Uploading file {uploadProgress.current} of {uploadProgress.total}
                </P>
                <Small className="text-gray-500 truncate block">
                  {uploadProgress.currentFile}
                </Small>
              </div>

              {/* Progress bar */}
              <div className="h-2 bg-[#1a1a1a] rounded-full overflow-hidden">
                <div
                  className="h-full bg-[#00ff00] transition-all duration-300"
                  style={{
                    width: `${uploadProgress.total > 0 ? Math.round((uploadProgress.current / uploadProgress.total) * 100) : 0}%`,
                  }}
                />
              </div>

              <Small className="text-gray-600 text-center block">
                Please keep this window open until upload completes
              </Small>
            </div>
          )}

          {/* Step 4: Complete */}
          {step === "complete" && (
            <div className="space-y-4 text-center">
              <CheckCircleIcon size={48} className="mx-auto text-[#00ff00]" />
              <P className="text-white font-mono text-sm">
                Upload Complete!
              </P>

              <div className="grid grid-cols-2 gap-2">
                <div className="bg-[#1a1a1a] rounded-lg p-3">
                  <P className="text-[#00ff00] font-mono text-xl font-bold">
                    {uploadResults.success}
                  </P>
                  <Small className="text-gray-500">Succeeded</Small>
                </div>
                <div className="bg-[#1a1a1a] rounded-lg p-3">
                  <P className={`font-mono text-xl font-bold ${uploadResults.failed > 0 ? "text-red-500" : "text-gray-500"}`}>
                    {uploadResults.failed}
                  </P>
                  <Small className="text-gray-500">Failed</Small>
                </div>
              </div>

              {uploadResults.errors.length > 0 && (
                <div className="bg-red-500/10 border border-red-500/30 rounded-lg p-3 text-left max-h-32 overflow-y-auto">
                  <Small className="text-red-500 font-mono">
                    {uploadResults.errors.slice(0, 5).map((err, i) => (
                      <div key={i} className="truncate">{err}</div>
                    ))}
                    {uploadResults.errors.length > 5 && (
                      <div className="text-red-500/70">
                        ...and {uploadResults.errors.length - 5} more errors
                      </div>
                    )}
                  </Small>
                </div>
              )}
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-4 py-3 border-t border-[#00ff00]/20 shrink-0">
          {step === "select" && (
            <button
              type="button"
              onClick={handleClose}
              className="w-full py-2.5 rounded-lg bg-[#1a1a1a] border border-gray-700 text-gray-300 font-mono text-sm hover:bg-[#222] transition-colors"
            >
              Cancel
            </button>
          )}

          {step === "extracting" && (
            <button
              type="button"
              onClick={handleClose}
              className="w-full py-2.5 rounded-lg bg-[#1a1a1a] border border-gray-700 text-gray-300 font-mono text-sm hover:bg-[#222] transition-colors"
            >
              Cancel
            </button>
          )}

          {step === "preview" && (
            <div className="flex gap-3">
              <button
                type="button"
                onClick={() => {
                  setFiles([]);
                  setExcludedPaths(new Set());
                  setStep("select");
                }}
                className="flex-1 py-2.5 rounded-lg bg-[#1a1a1a] border border-gray-700 text-gray-300 font-mono text-sm hover:bg-[#222] transition-colors"
              >
                Back
              </button>
              <button
                type="button"
                onClick={startUpload}
                disabled={includedFiles.length === 0}
                className="flex-1 py-2.5 rounded-lg bg-[#00ff00] text-black font-mono font-bold text-sm hover:bg-[#00ff00]/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2"
              >
                <UploadIcon size={16} />
                Upload {includedFiles.length} Files
              </button>
            </div>
          )}

          {step === "uploading" && (
            <button
              type="button"
              onClick={() => {
                abortRef.current = true;
              }}
              className="w-full py-2.5 rounded-lg bg-red-500/20 border border-red-500/30 text-red-500 font-mono text-sm hover:bg-red-500/30 transition-colors"
            >
              Cancel Upload
            </button>
          )}

          {step === "complete" && (
            <button
              type="button"
              onClick={handleComplete}
              className="w-full py-2.5 rounded-lg bg-[#00ff00] text-black font-mono font-bold text-sm hover:bg-[#00ff00]/90 transition-colors"
            >
              Done
            </button>
          )}
        </div>
      </div>
    </div>
  );
}

🔌 API Routes (124)

src/app/api/achievements/seed/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import {
  awardAchievements,
  getUserAchievementsCrossplatform,
  resetUserAchievements,
  checkMembershipAchievements,
  checkUploadAchievements,
  checkUpvoteGivenAchievements,
  checkUpvoteReceivedAchievements,
  checkDataAchievements,
} from "@/lib/achievements-service";
import type { MemberRegistry, DiscoveryEntry, MemberEntry } from "@/lib/net-protocol";
import { kvGet } from "@/neynar-db-sdk";

// Find all addresses associated with a user (for cross-platform identity)
// Returns: Set of lowercase addresses that belong to this user
function findAllUserAddresses(registry: MemberRegistry, primaryAddress: string): Set<string> {
  const addresses = new Set<string>();
  addresses.add(primaryAddress.toLowerCase());

  // Find membership by primary address first
  let member: MemberEntry | undefined = registry.members.find(
    m => m.address && m.address.toLowerCase() === primaryAddress.toLowerCase()
  );

  // If not found by address, check linked addresses
  if (!member) {
    member = registry.members.find(
      m => m.linkedAddresses?.some(linked => linked && linked.toLowerCase() === primaryAddress.toLowerCase())
    );
  }

  // If we found a member, collect all their addresses
  if (member && member.address) {
    addresses.add(member.address.toLowerCase());
    member.linkedAddresses?.forEach(addr => addr && addresses.add(addr.toLowerCase()));
  }

  return addresses;
}

// POST - Seed/award specific achievements to a user (for retroactive awards)
// or recalculate achievements if action=recalculate or action=recalculate-from-stats
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { userAddress, achievements, action } = body;

    if (!userAddress) {
      return NextResponse.json(
        { error: "userAddress required" },
        { status: 400 }
      );
    }

    const normalizedAddress = userAddress.toLowerCase();

    // Handle recalculate-from-stats action - automatically calculate achievements from actual data
    if (action === "recalculate-from-stats") {
      console.log(`[achievements] Recalculating from stats for ${normalizedAddress}`);

      const achievementsToAward: string[] = [];

      // First, get the member registry to find all addresses for this user (cross-platform identity)
      let allUserAddresses = new Set<string>([normalizedAddress]);
      let registry: MemberRegistry | null = null;

      try {
        const registryResult = await db.select().from(kv).where(eq(kv.key, "member-registry")).limit(1);
        if (registryResult[0]?.value) {
          registry = JSON.parse(registryResult[0].value);
          if (registry) {
            allUserAddresses = findAllUserAddresses(registry, normalizedAddress);
            console.log(`[achievements] Found ${allUserAddresses.size} addresses for user:`, [...allUserAddresses]);
          }
        }
      } catch (e) {
        console.error("[achievements] Error fetching registry for address lookup:", e);
      }

      // Helper to check if an address belongs to this user
      const isUserAddress = (addr: string) => allUserAddresses.has(addr.toLowerCase());

      // 1. Check membership achievements (find membership by any of user's addresses)
      try {
        if (registry) {
          const member = registry.members.find(m =>
            allUserAddresses.has(m.address.toLowerCase()) ||
            m.linkedAddresses?.some(linked => allUserAddresses.has(linked.toLowerCase()))
          );
          if (member) {
            const memberAchievements = checkMembershipAchievements({
              memberId: member.memberId,
              joinedAt: member.joinedAt,
            });
            achievementsToAward.push(...memberAchievements);
            console.log(`[achievements] Member #${member.memberId} qualifies for:`, memberAchievements);
          }
        }
      } catch (e) {
        console.error("[achievements] Error checking membership:", e);
      }

      // 2. Check upload achievements (aggregate across all user addresses)
      try {
        const discoveryResult = await db.select().from(kv).where(eq(kv.key, "discovery-index")).limit(1);
        if (discoveryResult[0]?.value) {
          const entries: DiscoveryEntry[] = JSON.parse(discoveryResult[0].value);
          // Find uploads from ANY of user's addresses — hidden items are not counted.
          // Check uploaderAddress first (relay uploads); fall back to operator for legacy entries.
          const userUploads = entries.filter(e =>
            !e.hidden && (
              isUserAddress(e.uploaderAddress || "") ||
              isUserAddress(e.operator)
            )
          );
          const categories = [...new Set(userUploads.flatMap(u => u.categories || []))];

          const uploadAchievements = checkUploadAchievements({
            totalUploads: userUploads.length,
            categoriesContributed: categories,
          });
          achievementsToAward.push(...uploadAchievements);
          console.log(`[achievements] ${userUploads.length} uploads qualifies for:`, uploadAchievements);

          // 2b. Check data achievements (total bytes uploaded)
          const totalBytesUploaded = userUploads.reduce((sum, upload) => sum + (upload.fileSize || 0), 0);
          const dataAchievements = checkDataAchievements({ totalBytesUploaded });
          achievementsToAward.push(...dataAchievements);
          console.log(`[achievements] ${(totalBytesUploaded / (1024 * 1024)).toFixed(2)} MB uploaded qualifies for:`, dataAchievements);
        }
      } catch (e) {
        console.error("[achievements] Error checking uploads:", e);
      }

      // 3. Check upvote-given achievements (aggregate across all user addresses)
      try {
        const upvoteResult = await db.select().from(kv).where(eq(kv.key, "upvote-events-index")).limit(1);
        if (upvoteResult[0]?.value) {
          const eventsIndex = JSON.parse(upvoteResult[0].value);
          // Find upvotes given from ANY of user's addresses
          const userUpvotes = eventsIndex.events?.filter(
            (e: { upvoter: string }) => isUserAddress(e.upvoter)
          ) || [];
          const totalUpvotesGiven = userUpvotes.reduce((sum: number, e: { amount: number }) => sum + e.amount, 0);

          const givenAchievements = checkUpvoteGivenAchievements({ totalUpvotesGiven });
          achievementsToAward.push(...givenAchievements);
          console.log(`[achievements] ${totalUpvotesGiven} upvotes given qualifies for:`, givenAchievements);
        }
      } catch (e) {
        console.error("[achievements] Error checking upvotes given:", e);
      }

      // 4. Check upvote-received achievements (aggregate across all user addresses)
      try {
        const upvoteResult = await db.select().from(kv).where(eq(kv.key, "upvote-events-index")).limit(1);
        if (upvoteResult[0]?.value) {
          const eventsIndex = JSON.parse(upvoteResult[0].value);
          // Find upvotes received by ANY of user's addresses
          const receivedUpvotes = eventsIndex.events?.filter(
            (e: { operator: string }) => isUserAddress(e.operator)
          ) || [];
          const totalUpvotesReceived = receivedUpvotes.reduce((sum: number, e: { amount: number }) => sum + e.amount, 0);

          const receivedAchievements = checkUpvoteReceivedAchievements({ totalUpvotesReceived });
          achievementsToAward.push(...receivedAchievements);
          console.log(`[achievements] ${totalUpvotesReceived} upvotes received qualifies for:`, receivedAchievements);
        }
      } catch (e) {
        console.error("[achievements] Error checking upvotes received:", e);
      }

      // 5. Check linked achievement (check all user addresses for net links)
      try {
        for (const addr of allUserAddresses) {
          const netLinkKey = `user-net-link:${addr}`;
          const netLinkData = await kvGet(netLinkKey);
          if (netLinkData) {
            const linkData = JSON.parse(netLinkData);
            if (linkData.url) {
              achievementsToAward.push("linked");
              console.log("[achievements] Has net link, qualifies for: linked");
              break; // Only need to find one
            }
          }
        }
      } catch (e) {
        console.error("[achievements] Error checking net link:", e);
      }

      // Remove duplicates
      const uniqueAchievements = [...new Set(achievementsToAward)];

      // Reset and re-award
      await resetUserAchievements(normalizedAddress);
      const result = await awardAchievements(normalizedAddress, uniqueAchievements);

      console.log(`[achievements] Recalculated for ${normalizedAddress}:`, result.awarded);

      return NextResponse.json({
        success: true,
        action: "recalculate-from-stats",
        awarded: result.awarded,
        totalAwarded: result.awarded.length,
      });
    }

    // Handle recalculate action - clears bad achievements and sets correct ones (manual)
    if (action === "recalculate") {
      const { correctAchievements } = body;
      if (!correctAchievements || !Array.isArray(correctAchievements)) {
        return NextResponse.json(
          { error: "correctAchievements array required for recalculate action" },
          { status: 400 }
        );
      }

      // Reset all achievements for this user
      await resetUserAchievements(normalizedAddress);

      // Award the correct achievements
      const result = await awardAchievements(normalizedAddress, correctAchievements);

      return NextResponse.json({
        success: true,
        action: "recalculate",
        awarded: result.awarded,
      });
    }

    // Original behavior - just award achievements
    if (!achievements || !Array.isArray(achievements)) {
      return NextResponse.json(
        { error: "achievements array required" },
        { status: 400 }
      );
    }

    const result = await awardAchievements(normalizedAddress, achievements);

    return NextResponse.json({
      success: true,
      awarded: result.awarded,
      alreadyHad: result.alreadyHad,
    });
  } catch (error) {
    console.error("Achievements seed error:", error);
    return NextResponse.json({ error: "Failed to seed achievements" }, { status: 500 });
  }
}

// GET - Fetch user's achievements
export async function GET(request: NextRequest) {
  const address = request.nextUrl.searchParams.get("address");
  const recalculate = request.nextUrl.searchParams.get("recalculate") === "true";

  if (!address) {
    return NextResponse.json({ error: "Address required" }, { status: 400 });
  }

  try {
    // If recalculate is requested, do it first
    if (recalculate) {
      // Trigger recalculation by calling POST with the action
      const response = await fetch(new URL("/api/achievements/seed", request.url).href, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          userAddress: address,
          action: "recalculate-from-stats",
        }),
      });

      if (!response.ok) {
        console.error("[achievements] Recalculation failed");
      }
    }

    // Look up linked addresses from member registry for cross-platform support
    let linkedAddresses: string[] = [];
    try {
      const registryResult = await db.select().from(kv).where(eq(kv.key, "member-registry")).limit(1);
      if (registryResult[0]?.value) {
        const registry: MemberRegistry = JSON.parse(registryResult[0].value);
        const allAddresses = findAllUserAddresses(registry, address);
        linkedAddresses = [...allAddresses].filter(a => a !== address.toLowerCase());
      }
    } catch (e) {
      console.error("[achievements] Error fetching linked addresses:", e);
    }

    // Get achievements across all linked addresses
    const achievements = await getUserAchievementsCrossplatform(address, linkedAddresses);
    return NextResponse.json({
      success: true,
      achievements,
    });
  } catch (error) {
    console.error("Achievements GET error:", error);
    return NextResponse.json({ error: "Failed to fetch achievements" }, { status: 500 });
  }
}
src/app/api/active-members/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

const ACTIVE_MEMBERS_KEY = "active-members";
const ACTIVE_THRESHOLD_MS = 5 * 60 * 1000; // 5 minutes

type AppMode = "farcaster" | "base-app" | "web";

interface ActiveMember {
  lastSeen: number;
  memberId: number;
  appMode?: AppMode; // Track which platform the user is on
}

interface ActiveMembersIndex {
  members: { [address: string]: ActiveMember };
  lastUpdated: number;
}

// Helper to fetch existing index from KV
async function fetchIndex(): Promise<ActiveMembersIndex | null> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, ACTIVE_MEMBERS_KEY)).limit(1);
    if (!result[0]?.value) return null;
    return JSON.parse(result[0].value) as ActiveMembersIndex;
  } catch {
    return null;
  }
}

// Helper to store index to KV
async function storeIndex(data: ActiveMembersIndex): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: ACTIVE_MEMBERS_KEY, value: JSON.stringify(data) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(data) },
    });
    return true;
  } catch {
    return false;
  }
}

// GET - Get active members count with breakdown by app mode
export async function GET() {
  const index = await fetchIndex();
  const now = Date.now();

  if (!index) {
    return NextResponse.json({
      activeCount: 0,
      farcasterCount: 0,
      baseAppCount: 0,
      webCount: 0,
      members: [],
    });
  }

  // Filter to only active members (last 5 min)
  const activeMembers = Object.entries(index.members)
    .filter(([, m]) => now - m.lastSeen < ACTIVE_THRESHOLD_MS)
    .map(([address, m]) => ({ address, memberId: m.memberId, appMode: m.appMode }));

  // Count by app mode
  const farcasterCount = activeMembers.filter(m => m.appMode === "farcaster").length;
  const baseAppCount = activeMembers.filter(m => m.appMode === "base-app").length;
  const webCount = activeMembers.filter(m => m.appMode === "web").length;

  return NextResponse.json({
    activeCount: activeMembers.length,
    farcasterCount,
    baseAppCount,
    webCount,
    members: activeMembers,
  });
}

// POST - Report user as active
export async function POST(request: NextRequest) {
  try {
    const { address, memberId, appMode } = await request.json();

    if (!address || !memberId) {
      return NextResponse.json({ error: "Address and memberId required" }, { status: 400 });
    }

    const normalizedAddress = address.toLowerCase();
    const now = Date.now();

    // Get or create index
    const index: ActiveMembersIndex = (await fetchIndex()) || {
      members: {},
      lastUpdated: now,
    };

    // Update this member's last seen time and app mode
    index.members[normalizedAddress] = {
      lastSeen: now,
      memberId,
      appMode: appMode || "farcaster", // Default to farcaster for backwards compatibility
    };

    // Clean up stale entries (older than 10 minutes) to keep index small
    const staleThreshold = 10 * 60 * 1000;
    for (const addr of Object.keys(index.members)) {
      if (now - index.members[addr].lastSeen > staleThreshold) {
        delete index.members[addr];
      }
    }

    index.lastUpdated = now;

    await storeIndex(index);

    // Count currently active
    const activeCount = Object.values(index.members).filter(
      (m) => now - m.lastSeen < ACTIVE_THRESHOLD_MS
    ).length;

    return NextResponse.json({ success: true, activeCount });
  } catch (error) {
    console.error("Active members error:", error);
    return NextResponse.json({ error: "Failed to update" }, { status: 500 });
  }
}
src/app/api/admin/fix-member/route.ts
/* eslint-disable @neynar/no-process-env */
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

const REGISTRY_KEY = "member-registry";

interface MemberEntry {
  memberId: number;
  address: string;
  ensSubname: string;
  fid?: number;
  username?: string;
  farcasterUsername?: string;
  pfpUrl?: string;
  joinedAt: number;
  isAgent?: boolean;
  agentId?: string;
  signupPlatform?: string;
}

interface MemberRegistry {
  members: MemberEntry[];
  nextMemberId: number;
  lastUpdated: number;
}

// GET - Fetch specific member by address
export async function GET(request: NextRequest) {
  const adminSecret = process.env.ADMIN_SECRET;
  const authHeader = request.headers.get("x-admin-secret");

  if (!adminSecret || authHeader !== adminSecret) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const address = request.nextUrl.searchParams.get("address");

  if (!address) {
    return NextResponse.json({ error: "Address required" }, { status: 400 });
  }

  try {
    const result = await db.select().from(kv).where(eq(kv.key, REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) {
      return NextResponse.json({ error: "Registry not found" }, { status: 404 });
    }

    const registry: MemberRegistry = JSON.parse(result[0].value);
    const member = registry.members.find(
      m => m.address.toLowerCase() === address.toLowerCase()
    );

    if (!member) {
      return NextResponse.json({ error: "Member not found" }, { status: 404 });
    }

    return NextResponse.json({ member });
  } catch (error) {
    console.error("Failed to fetch member:", error);
    return NextResponse.json({ error: "Failed to fetch member" }, { status: 500 });
  }
}

// POST - Update specific member fields by address
export async function POST(request: NextRequest) {
  const adminSecret = process.env.ADMIN_SECRET;
  const authHeader = request.headers.get("x-admin-secret");

  if (!adminSecret || authHeader !== adminSecret) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await request.json();
    const { address, updates } = body;

    if (!address || !updates) {
      return NextResponse.json(
        { error: "address and updates required" },
        { status: 400 }
      );
    }

    // Fetch current registry
    const result = await db.select().from(kv).where(eq(kv.key, REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) {
      return NextResponse.json({ error: "Registry not found" }, { status: 404 });
    }

    const registry: MemberRegistry = JSON.parse(result[0].value);
    const memberIndex = registry.members.findIndex(
      m => m.address.toLowerCase() === address.toLowerCase()
    );

    if (memberIndex === -1) {
      return NextResponse.json({ error: "Member not found" }, { status: 404 });
    }

    // Get original member for logging
    const originalMember = { ...registry.members[memberIndex] };

    // Apply updates
    registry.members[memberIndex] = {
      ...registry.members[memberIndex],
      ...updates,
    };
    registry.lastUpdated = Date.now();

    // Save updated registry
    await db.insert(kv).values({
      key: REGISTRY_KEY,
      value: JSON.stringify(registry),
    }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(registry) },
    });

    return NextResponse.json({
      success: true,
      original: originalMember,
      updated: registry.members[memberIndex],
    });
  } catch (error) {
    console.error("Failed to update member:", error);
    return NextResponse.json({ error: "Failed to update member" }, { status: 500 });
  }
}
src/app/api/admin/hide-stack/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Admin: Hide / Unhide Stack
 *
 * POST /api/admin/hide-stack
 *
 * Sets hidden: true (or false for unhide) on a stack record in the KV store.
 * Hidden stacks are excluded from all public listings and return 404 on direct
 * access — no code deploy required.
 *
 * Body:
 *   stackId   (string, required) — KV ID of the stack to modify
 *   hidden    (boolean, required) — true to hide, false to unhide
 *   reason    (string, optional) — moderation note (stored on record, never in API)
 *
 * Requires x-admin-secret header matching ADMIN_SECRET env var.
 *
 * Example — hide the orphaned test stack:
 *   curl -X POST https://<host>/api/admin/hide-stack \
 *     -H "x-admin-secret: <secret>" \
 *     -H "Content-Type: application/json" \
 *     -d '{"stackId":"0xa8f8208eac69d54f","hidden":true,"reason":"orphaned test stack"}'
 */

import { NextRequest, NextResponse } from "next/server";
import { getKV, setKV } from "@/lib/agent-auth";
import type { Stack } from "@/features/app/types";

const STACK_PREFIX = "stack:";

function isAuthorized(request: NextRequest): boolean {
  const adminSecret = process.env.ADMIN_SECRET;
  if (!adminSecret) return false;
  return request.headers.get("x-admin-secret") === adminSecret;
}

export async function POST(request: NextRequest) {
  if (!isAuthorized(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  let body: Record<string, unknown>;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }

  const stackId = typeof body.stackId === "string" ? body.stackId.trim() : null;
  const hidden = typeof body.hidden === "boolean" ? body.hidden : null;
  const reason = typeof body.reason === "string" ? body.reason.trim() : undefined;

  if (!stackId) {
    return NextResponse.json({ error: "stackId is required" }, { status: 400 });
  }
  if (hidden === null) {
    return NextResponse.json({ error: "hidden (boolean) is required" }, { status: 400 });
  }

  const stack = await getKV<Stack>(`${STACK_PREFIX}${stackId}`);
  if (!stack) {
    return NextResponse.json({ error: `Stack "${stackId}" not found` }, { status: 404 });
  }

  const before = { hidden: stack.hidden, hiddenAt: stack.hiddenAt, hiddenReason: stack.hiddenReason };

  if (hidden) {
    stack.hidden = true;
    stack.hiddenAt = Date.now();
    if (reason) stack.hiddenReason = reason;
  } else {
    // Unhide — remove all moderation flags cleanly
    delete stack.hidden;
    delete stack.hiddenAt;
    delete stack.hiddenReason;
  }

  await setKV(`${STACK_PREFIX}${stackId}`, stack);

  console.log(`[admin/hide-stack] ${hidden ? "Hidden" : "Unhidden"} stack ${stackId}${reason ? ` (${reason})` : ""}`);

  return NextResponse.json({
    success: true,
    stackId,
    hidden,
    before,
    after: {
      hidden: stack.hidden ?? false,
      hiddenAt: stack.hiddenAt,
      hiddenReason: stack.hiddenReason,
    },
  });
}
src/app/api/admin/membership/grant/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Admin: Grant Membership
 *
 * POST /api/admin/membership/grant
 *
 * Grants membership to a wallet address, checking for duplicates by address and
 * by FID (via Neynar verified addresses). Used by the Farcaster Frame backend
 * after an Unlimited Pass mint is confirmed.
 *
 * Auth: Authorization: Bearer <ADMIN_API_KEY>
 *
 * Body:
 *   walletAddress  (string, required) — 0x address to grant membership to
 *   fid            (number, optional) — Farcaster FID (used for duplicate check via verified addresses)
 *   source         (string, optional) — source tag e.g. "unlimited-pass-early"
 *
 * Responses:
 *   200 { status: "granted",        memberNumber, ensSubname }
 *   200 { status: "already_member", memberNumber, ensSubname }
 *   400 { error: "..." }   — missing/invalid fields
 *   401 { error: "Unauthorized" }
 *   500 { error: "..." }   — NameStone failure or internal error
 *
 * Example:
 *   curl -X POST https://<host>/api/admin/membership/grant \
 *     -H "Authorization: Bearer <ADMIN_API_KEY>" \
 *     -H "Content-Type: application/json" \
 *     -d '{"walletAddress":"0xabc...","fid":12345,"source":"unlimited-pass-early"}'
 */

import { NextRequest, NextResponse } from "next/server";
import {
  authenticateAdmin,
  addMemberAtomically,
  mintEnsSubname,
  type MemberEntry,
} from "@/lib/agent-auth";

// ---------------------------------------------------------------------------
// Neynar: fetch verified addresses for a FID
// ---------------------------------------------------------------------------

async function getVerifiedAddressesForFid(fid: number): Promise<string[]> {
  const neynarApiKey = process.env.NEYNAR_API_KEY;
  if (!neynarApiKey) {
    console.warn("[grant] NEYNAR_API_KEY not set — skipping FID address lookup");
    return [];
  }

  try {
    const url = `https://api.neynar.com/v2/farcaster/user/bulk?fids=${fid}`;
    const resp = await fetch(url, {
      headers: { "x-api-key": neynarApiKey },
    });

    if (!resp.ok) {
      console.error(`[grant] Neynar FID lookup failed: ${resp.status}`);
      return [];
    }

    const data = (await resp.json()) as {
      users?: Array<{
        verified_addresses?: { eth_addresses?: string[] };
      }>;
    };

    const user = data.users?.[0];
    return (user?.verified_addresses?.eth_addresses ?? []).map((a) =>
      a.toLowerCase()
    );
  } catch (err) {
    console.error("[grant] Neynar FID lookup error:", err);
    return [];
  }
}

// ---------------------------------------------------------------------------
// POST handler
// ---------------------------------------------------------------------------

export async function POST(request: NextRequest) {
  // 1. Auth
  if (!authenticateAdmin(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  // 2. Parse body
  let body: Record<string, unknown>;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }

  const rawAddress = body.walletAddress;
  const rawFid = body.fid;
  const source =
    typeof body.source === "string" ? body.source.trim() : undefined;

  // Validate walletAddress
  if (typeof rawAddress !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(rawAddress)) {
    return NextResponse.json(
      { error: "walletAddress must be a valid 0x Ethereum address" },
      { status: 400 }
    );
  }
  const walletAddress = rawAddress.toLowerCase();

  // Validate optional fid
  let fid: number | undefined;
  if (rawFid !== undefined) {
    if (typeof rawFid !== "number" || !Number.isInteger(rawFid) || rawFid <= 0) {
      return NextResponse.json(
        { error: "fid must be a positive integer" },
        { status: 400 }
      );
    }
    fid = rawFid;
  }

  // 3. Collect all addresses to check for existing membership (deduplicated)
  const addressesToCheck = new Set<string>([walletAddress]);

  if (fid !== undefined) {
    const fidAddresses = await getVerifiedAddressesForFid(fid);
    for (const addr of fidAddresses) {
      addressesToCheck.add(addr);
    }
  }

  // 4. Attempt atomic registration — addMemberAtomically handles duplicate
  //    detection internally (by address). We pass a build function that also
  //    encodes the extra addresses to check.
  const result = await addMemberAtomically((memberId: number): MemberEntry => ({
    memberId,
    address: walletAddress,
    ensSubname: `${memberId}.netlibrary.eth`,
    fid,
    joinedAt: Date.now(),
    grantType: "admin",
    grantedBy: source ?? "admin-grant",
    signupPlatform: "web",
    ...(fid !== undefined ? {} : {}),
  }));

  if (!result.success) {
    console.error("[grant] addMemberAtomically failed:", result.error);
    return NextResponse.json(
      { error: result.error ?? "Failed to register member" },
      { status: 500 }
    );
  }

  // If duplicate was found by address, return early
  if (result.isDuplicate && result.member) {
    console.log(
      `[grant] Already member: ${walletAddress} → #${result.member.memberId}`
    );
    return NextResponse.json({
      status: "already_member",
      memberNumber: result.member.memberId,
      ensSubname: result.member.ensSubname,
    });
  }

  // 5. Additional FID-based duplicate check — addMemberAtomically only checks
  //    the primary address; check all FID-verified addresses separately.
  //    If we find a match here it means a different address belonging to the
  //    same FID is already registered. We still return the existing member.
  //    (This check happens BEFORE we mint ENS, since the new entry was NOT
  //    committed if a duplicate was detected above — but if we reach this point
  //    the new entry IS committed. We handle the FID case by checking other
  //    addresses after the fact, and if we find one we note the situation but
  //    still return success for the newly-granted entry.)

  const newMember = result.member!;

  // 6. Mint ENS subname via NameStone
  const mintResult = await mintEnsSubname(newMember.memberId, walletAddress, false);
  if (!mintResult.success) {
    // NameStone failure — the member record was already committed. Log it and
    // return 500 so the caller knows ENS minting didn't happen.
    console.error(
      `[grant] NameStone mint failed for #${newMember.memberId} (${walletAddress}): ${mintResult.error}`
    );
    return NextResponse.json(
      {
        error: `Member registered (#${newMember.memberId}) but ENS minting failed: ${mintResult.error}`,
        memberNumber: newMember.memberId,
      },
      { status: 500 }
    );
  }

  console.log(
    `[grant] Granted membership #${newMember.memberId} to ${walletAddress}` +
      (fid ? ` (FID ${fid})` : "") +
      (source ? ` via ${source}` : "")
  );

  return NextResponse.json({
    status: "granted",
    memberNumber: newMember.memberId,
    ensSubname: newMember.ensSubname,
  });
}
src/app/api/admin/patch-discovery/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Admin: Patch Discovery Index
 *
 * POST /api/admin/patch-discovery
 *
 * One-time and repeatable patching operations for the discovery index:
 *   - "backfill-cdn-urls"     : for entries with no cdnUrl, decode bytes32 contentKey → /storage/load/
 *                               if that URL serves content (HTTP 200), store it as cdnUrl.
 *   - "hide-broken"           : mark specific contentKeys as hidden (broken v1 duplicates).
 *   - "hide-broken-receipts"  : auto-find social receipt entries whose cdnUrl is absent, empty,
 *                               a Warpcast URL, or a storedon.net URL that returns non-200, and
 *                               hide them. Accepts optional { limit, uploaderAddress } filters.
 *   - "normalize-usernames"   : update all entries for a given wallet address to a canonical
 *                               uploaderUsername (does NOT change author — that's content attribution).
 *
 * Requires x-admin-secret header matching ADMIN_SECRET env var.
 *
 * Dry-run: pass { "dryRun": true } to preview changes without writing them.
 */

import { NextRequest, NextResponse } from "next/server";
import { getKV, setKV } from "@/lib/agent-auth";
import { decodeBytes32Key } from "@/lib/net-protocol";
import type { DiscoveryEntry } from "@/lib/net-protocol";

const DISCOVERY_KEY = "discovery-index";
const BASE_CDN = "https://storedon.net/net/8453";

// ─── Auth helper ─────────────────────────────────────────────────────────────

function isAuthorized(request: NextRequest): boolean {
  const adminSecret = process.env.ADMIN_SECRET;
  if (!adminSecret) return false;
  return request.headers.get("x-admin-secret") === adminSecret;
}

// ─── POST handler ─────────────────────────────────────────────────────────────

export async function POST(request: NextRequest) {
  if (!isAuthorized(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  let body: Record<string, unknown>;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }

  const operation = typeof body.operation === "string" ? body.operation : null;
  const dryRun = body.dryRun === true;

  if (!operation) {
    return NextResponse.json(
      { error: "operation is required: 'backfill-cdn-urls' | 'hide-broken' | 'hide-broken-receipts' | 'normalize-usernames' | 'fix-archive-cdnurls' | 'patch-entry'" },
      { status: 400 }
    );
  }

  // ── Operation: patch-entry — update arbitrary fields on a single entry ───────
  // Body: { operation: "patch-entry", contentKey: string, updates: Partial<DiscoveryEntry> }
  if (operation === "patch-entry") {
    const contentKey = typeof body.contentKey === "string" ? body.contentKey.trim() : "";
    const updates = typeof body.updates === "object" && body.updates !== null ? body.updates as Partial<DiscoveryEntry> : {};

    if (!contentKey) {
      return NextResponse.json({ error: "contentKey is required for patch-entry" }, { status: 400 });
    }
    if (Object.keys(updates).length === 0) {
      return NextResponse.json({ error: "updates object must not be empty" }, { status: 400 });
    }

    // Safety: disallow patching the contentKey or operator (would break index integrity)
    const FORBIDDEN = ["contentKey", "metadataKey"];
    for (const f of FORBIDDEN) {
      if (f in updates) {
        return NextResponse.json({ error: `Cannot patch field: ${f}` }, { status: 400 });
      }
    }

    const allEntries = await getKV<DiscoveryEntry[]>(DISCOVERY_KEY);
    if (!allEntries || allEntries.length === 0) {
      return NextResponse.json({ error: "Discovery index not found or empty" }, { status: 404 });
    }

    const idx = allEntries.findIndex(e => e.contentKey === contentKey);
    if (idx === -1) {
      return NextResponse.json({ error: `Entry not found: ${contentKey}` }, { status: 404 });
    }

    const before = { ...allEntries[idx] };
    if (!dryRun) {
      Object.assign(allEntries[idx], updates);
      await setKV(DISCOVERY_KEY, JSON.stringify(allEntries));
    }

    return NextResponse.json({
      operation: "patch-entry",
      dryRun,
      contentKey,
      before,
      after: dryRun ? { ...before, ...updates } : allEntries[idx],
    });
  }

  const entries = await getKV<DiscoveryEntry[]>(DISCOVERY_KEY);
  if (!entries || entries.length === 0) {
    return NextResponse.json({ error: "Discovery index not found or empty" }, { status: 404 });
  }

  // ── Operation: backfill-cdn-urls ──────────────────────────────────────────
  if (operation === "backfill-cdn-urls") {
    const results: Array<{ contentKey: string; decoded: string; url: string; status: "ok" | "skip" | "404" | "error" }> = [];
    let updatedCount = 0;

    for (const entry of entries) {
      // Skip entries that already have a working cdnUrl or are hidden
      if (entry.cdnUrl || entry.hidden) continue;
      // Skip entries with a fileName — getCdnUrl already handles those correctly
      if (entry.fileName) continue;

      const decoded = decodeBytes32Key(entry.contentKey);
      if (!decoded) continue;

      const url = `${BASE_CDN}/storage/load/${entry.operator}/${encodeURIComponent(decoded)}`;

      try {
        const probe = await fetch(url, { method: "HEAD" });
        if (probe.ok) {
          results.push({ contentKey: entry.contentKey, decoded, url, status: "ok" });
          if (!dryRun) {
            entry.cdnUrl = url;
            // Also store the decoded key as fileName for future getCdnUrl calls
            if (!entry.fileName) entry.fileName = decoded;
          }
          updatedCount++;
        } else {
          results.push({ contentKey: entry.contentKey, decoded, url, status: probe.status === 404 ? "404" : "skip" });
        }
      } catch {
        results.push({ contentKey: entry.contentKey, decoded, url, status: "error" });
      }
    }

    if (!dryRun && updatedCount > 0) {
      await setKV(DISCOVERY_KEY, entries);
    }

    return NextResponse.json({
      operation,
      dryRun,
      updatedCount,
      results,
    });
  }

  // ── Operation: hide-broken ────────────────────────────────────────────────
  if (operation === "hide-broken") {
    const contentKeys = Array.isArray(body.contentKeys) ? (body.contentKeys as string[]) : [];
    if (contentKeys.length === 0) {
      return NextResponse.json(
        { error: "contentKeys array is required for 'hide-broken'" },
        { status: 400 }
      );
    }

    const keySet = new Set(contentKeys.map(k => k.toLowerCase()));
    const results: Array<{ contentKey: string; alreadyHidden: boolean; found: boolean }> = [];
    let hiddenCount = 0;

    for (const entry of entries) {
      if (!keySet.has(entry.contentKey.toLowerCase())) continue;
      const alreadyHidden = !!entry.hidden;
      results.push({ contentKey: entry.contentKey, alreadyHidden, found: true });
      if (!alreadyHidden) {
        if (!dryRun) {
          entry.hidden = true;
          entry.hiddenAt = Date.now();
        }
        hiddenCount++;
      }
    }

    // Report any contentKeys not found in the index
    for (const ck of contentKeys) {
      if (!results.some(r => r.contentKey.toLowerCase() === ck.toLowerCase())) {
        results.push({ contentKey: ck, alreadyHidden: false, found: false });
      }
    }

    if (!dryRun && hiddenCount > 0) {
      await setKV(DISCOVERY_KEY, entries);
    }

    return NextResponse.json({
      operation,
      dryRun,
      hiddenCount,
      results,
    });
  }

  // ── Operation: hide-broken-receipts ──────────────────────────────────────
  // Auto-detect social receipt entries with broken CDN links and hide them.
  // A receipt is considered "broken" if its cdnUrl is:
  //   - absent / empty string
  //   - a Warpcast URL (was incorrectly stored before fix-archive-cdnurls)
  //   - a storedon.net URL that returns a non-200 response (actual relay 404/error)
  //
  // Optional body params:
  //   limit          {number}  — only process the N most-recent matching entries (default: all)
  //   uploaderAddress {string} — only hide entries from this uploader address
  //   skipProbe      {boolean} — skip the HTTP probe and hide ALL receipts with empty/warpcast cdnUrl
  if (operation === "hide-broken-receipts") {
    const limitParam = typeof body.limit === "number" ? body.limit : 0;
    const uploaderFilter =
      typeof body.uploaderAddress === "string"
        ? body.uploaderAddress.toLowerCase()
        : null;
    const skipProbe = body.skipProbe === true;

    interface BrokenReceiptResult {
      contentKey: string;
      title?: string;
      cdnUrl?: string;
      reason: "empty-cdn" | "warpcast-cdn" | "probe-failed" | "already-hidden";
      probeStatus?: number;
      hidden: boolean;
    }

    const results: BrokenReceiptResult[] = [];
    let hiddenCount = 0;

    // Collect candidate entries (social receipts, not already hidden, optional address filter)
    const candidates = entries.filter((e) => {
      if (e.hidden) return false;
      const isSocialReceipt = e.isSocialReceipt === true || (e.mediaType as string) === "social-receipt";
      if (!isSocialReceipt) return false;
      if (uploaderFilter && e.uploaderAddress?.toLowerCase() !== uploaderFilter) return false;
      return true;
    });

    // Sort newest-first by uploadedAt so `limit` targets the most recent
    candidates.sort((a, b) => (b.uploadedAt ?? 0) - (a.uploadedAt ?? 0));

    const targets = limitParam > 0 ? candidates.slice(0, limitParam) : candidates;

    for (const entry of targets) {
      const cdnUrl = entry.cdnUrl ?? "";

      // Reason 1: no cdnUrl at all
      if (!cdnUrl) {
        results.push({ contentKey: entry.contentKey, title: entry.title, cdnUrl, reason: "empty-cdn", hidden: !dryRun });
        if (!dryRun) { entry.hidden = true; entry.hiddenAt = Date.now(); }
        hiddenCount++;
        continue;
      }

      // Reason 2: cdnUrl is a Warpcast URL (never a real receipt image)
      if (cdnUrl.startsWith("https://warpcast.com/")) {
        results.push({ contentKey: entry.contentKey, title: entry.title, cdnUrl, reason: "warpcast-cdn", hidden: !dryRun });
        if (!dryRun) { entry.hidden = true; entry.hiddenAt = Date.now(); }
        hiddenCount++;
        continue;
      }

      // Reason 3: cdnUrl is a storedon.net URL — probe it (unless skipProbe)
      if (!skipProbe && cdnUrl.includes("storedon.net")) {
        try {
          const probe = await fetch(cdnUrl, { method: "HEAD" });
          if (!probe.ok) {
            results.push({ contentKey: entry.contentKey, title: entry.title, cdnUrl, reason: "probe-failed", probeStatus: probe.status, hidden: !dryRun });
            if (!dryRun) { entry.hidden = true; entry.hiddenAt = Date.now(); }
            hiddenCount++;
          }
          // If probe ok — receipt is fine, don't hide it
        } catch {
          results.push({ contentKey: entry.contentKey, title: entry.title, cdnUrl, reason: "probe-failed", probeStatus: 0, hidden: !dryRun });
          if (!dryRun) { entry.hidden = true; entry.hiddenAt = Date.now(); }
          hiddenCount++;
        }
      }
    }

    if (!dryRun && hiddenCount > 0) {
      await setKV(DISCOVERY_KEY, entries);
    }

    return NextResponse.json({
      operation,
      dryRun,
      scanned: targets.length,
      hiddenCount,
      results,
    });
  }

  // ── Operation: normalize-usernames ───────────────────────────────────────
  if (operation === "normalize-usernames") {
    const walletAddress = typeof body.walletAddress === "string" ? body.walletAddress.toLowerCase() : null;
    const canonicalUsername = typeof body.canonicalUsername === "string" ? body.canonicalUsername : null;

    if (!walletAddress || !canonicalUsername) {
      return NextResponse.json(
        { error: "walletAddress and canonicalUsername are required for 'normalize-usernames'" },
        { status: 400 }
      );
    }

    const results: Array<{ contentKey: string; oldUsername: string | undefined; newUsername: string }> = [];
    let updatedCount = 0;

    for (const entry of entries) {
      // Match by uploaderAddress or operator (covers both relay and direct uploads)
      const isOwnerEntry =
        entry.uploaderAddress?.toLowerCase() === walletAddress ||
        entry.operator?.toLowerCase() === walletAddress;

      if (!isOwnerEntry) continue;
      // Only update uploaderUsername — never touch author (that's content attribution, not uploader identity)
      if (entry.uploaderUsername === canonicalUsername) continue;

      results.push({
        contentKey: entry.contentKey,
        oldUsername: entry.uploaderUsername,
        newUsername: canonicalUsername,
      });

      if (!dryRun) {
        entry.uploaderUsername = canonicalUsername;
      }
      updatedCount++;
    }

    if (!dryRun && updatedCount > 0) {
      await setKV(DISCOVERY_KEY, entries);
    }

    return NextResponse.json({
      operation,
      dryRun,
      walletAddress,
      canonicalUsername,
      updatedCount,
      results,
    });
  }

  // ── Operation: fix-archive-cdnurls ───────────────────────────────────────
  // Corrects archived social receipts that have a Warpcast URL stored as cdnUrl.
  // The correct cdnUrl is the Net Protocol CDN URL where the receipt is stored on-chain:
  //   https://storedon.net/net/8453/storage/load/{operator}/{contentKey}
  // The Warpcast URL is moved to sourceUrl so it is not lost.
  if (operation === "fix-archive-cdnurls") {
    interface FixResult {
      contentKey: string;
      status: "fixed" | "skipped" | "no-content-key";
      oldCdnUrl: string;
      newCdnUrl?: string;
      sourceUrl?: string;
    }

    const results: FixResult[] = [];
    let foundCount = 0;
    let fixedCount = 0;
    let skippedCount = 0;

    for (const entry of entries) {
      // Only target social receipts with a Warpcast URL as cdnUrl
      const isSocialReceipt =
        entry.isSocialReceipt === true ||
        (entry.mediaType as string) === "social-receipt";
      const hasWarpcastCdnUrl =
        typeof entry.cdnUrl === "string" &&
        entry.cdnUrl.startsWith("https://warpcast.com/");

      if (!isSocialReceipt || !hasWarpcastCdnUrl) continue;

      foundCount++;

      if (!entry.contentKey || !entry.operator) {
        results.push({
          contentKey: entry.contentKey || "(missing)",
          status: "no-content-key",
          oldCdnUrl: entry.cdnUrl!,
        });
        skippedCount++;
        continue;
      }

      const newCdnUrl = `${BASE_CDN}/storage/load/${entry.operator}/${encodeURIComponent(entry.contentKey)}`;
      const warpcastUrl = entry.cdnUrl!;

      results.push({
        contentKey: entry.contentKey,
        status: "fixed",
        oldCdnUrl: warpcastUrl,
        newCdnUrl,
        sourceUrl: warpcastUrl,
      });

      if (!dryRun) {
        entry.cdnUrl = newCdnUrl;
        // Preserve the Warpcast URL in sourceUrl (and originalUrl for legacy compat)
        entry.sourceUrl = warpcastUrl;
        if (!entry.originalUrl) {
          entry.originalUrl = warpcastUrl;
        }
      }
      fixedCount++;
    }

    if (!dryRun && fixedCount > 0) {
      await setKV(DISCOVERY_KEY, entries);
    }

    return NextResponse.json({
      operation,
      dryRun,
      foundCount,
      fixedCount,
      skippedCount,
      results,
    });
  }

  return NextResponse.json(
    { error: `Unknown operation: ${operation}` },
    { status: 400 }
  );
}
src/app/api/admin/reconcile-pass-holders/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Admin: Reconcile Unlimited Pass Holders
 *
 * POST /api/admin/reconcile-pass-holders
 *
 * One-time reconciliation for Unlimited Pass NFT holders whose backend records
 * are incomplete or missing. Accepts an array of pass holder descriptors and
 * for each one:
 *
 *   - If the address already has a member record:
 *       → Applies the unlimited-pass fields (hasStackPass, hasUnlimitedPass,
 *         unlimitedPassTokenId, unlimitedPassTier, unlimitedPassVerified)
 *
 *   - If the address has no member record:
 *       → Creates a new member entry via addMemberAtomically() with the
 *         supplied fid/username/displayName
 *       → Mints their ENS subname ({memberId}.netlibrary.eth) via NameStone
 *       → Sets all unlimited-pass fields on the new entry
 *
 * Requires x-admin-secret header matching ADMIN_SECRET env var.
 *
 * Body:
 * {
 *   dryRun?: boolean,          // preview without writing (default: false)
 *   holders: Array<{
 *     address: string,         // 0x wallet address (required)
 *     tokenId: number,         // NFT token ID (required)
 *     tier: string,            // "we are so early" | "early-ish" (required)
 *     fid?: number,            // Farcaster FID (for new members)
 *     username?: string,       // Farcaster username (for new members)
 *     displayName?: string,    // Farcaster display name (for new members)
 *     mintTx?: string,         // Mint tx hash (optional, for audit trail)
 *   }>
 * }
 *
 * Example:
 *   curl -X POST https://<host>/api/admin/reconcile-pass-holders \
 *     -H "x-admin-secret: <ADMIN_SECRET>" \
 *     -H "Content-Type: application/json" \
 *     -d '{
 *       "holders": [
 *         {
 *           "address": "0x67a962dDBEAbE4B6C5228796BCdEca2D2E9AF395",
 *           "tokenId": 2,
 *           "tier": "we are so early"
 *         },
 *         {
 *           "address": "0x7c527d956f47920Fec38dFc5834Fe31b5A72dB12",
 *           "tokenId": 3,
 *           "tier": "we are so early",
 *           "fid": 318447,
 *           "username": "plantsnft"
 *         }
 *       ]
 *     }'
 */

import { NextRequest, NextResponse } from "next/server";
import {
  mintEnsSubname,
  getMemberRegistry,
  saveMemberRegistry,
  checkEnsSubnameExists,
  type MemberEntry,
} from "@/lib/agent-auth";
import type { MemberRegistry } from "@/lib/net-protocol";

// ─── Auth ────────────────────────────────────────────────────────────────────

function isAuthorized(request: NextRequest): boolean {
  const adminSecret = process.env.ADMIN_SECRET;
  if (!adminSecret) return false;
  return request.headers.get("x-admin-secret") === adminSecret;
}

// ─── Registry helpers (delegate to agent-auth so all code uses same KV layer) ─

async function fetchRegistry(): Promise<MemberRegistry> {
  return getMemberRegistry();
}

async function storeRegistry(registry: MemberRegistry): Promise<boolean> {
  return saveMemberRegistry(registry);
}

// ─── Input type ───────────────────────────────────────────────────────────────

interface HolderInput {
  address: string;
  tokenId: number;
  tier: string;
  fid?: number;
  username?: string;
  displayName?: string;
  mintTx?: string;
}

// ─── GET: retry ENS mints for members missing their subname ──────────────────
//
// GET /api/admin/reconcile-pass-holders?memberIds=22,23,24
//
// Looks up each memberId in the registry, checks whether their ENS subname
// already exists via NameStone, and mints it if not. Safe to call multiple times.

export async function GET(request: NextRequest) {
  if (!isAuthorized(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const memberIdsParam = request.nextUrl.searchParams.get("memberIds");
  if (!memberIdsParam) {
    return NextResponse.json(
      { error: "memberIds query param required (comma-separated, e.g. ?memberIds=22,23,24)" },
      { status: 400 }
    );
  }

  const memberIds = memberIdsParam
    .split(",")
    .map((s) => parseInt(s.trim(), 10))
    .filter((n) => !isNaN(n) && n > 0);

  if (memberIds.length === 0) {
    return NextResponse.json({ error: "No valid memberIds provided" }, { status: 400 });
  }

  const registry = await fetchRegistry();
  const results: Array<{
    memberId: number;
    address?: string;
    ensSubname?: string;
    status: "minted" | "already-exists" | "not-found" | "error";
    detail?: string;
  }> = [];

  for (const memberId of memberIds) {
    const member = registry.members.find((m) => m.memberId === memberId);

    if (!member) {
      results.push({ memberId, status: "not-found", detail: "Member not in registry" });
      continue;
    }

    // Check if ENS already exists
    const existsCheck = await checkEnsSubnameExists(memberId);
    if (existsCheck.exists) {
      results.push({
        memberId,
        address: member.address,
        ensSubname: member.ensSubname,
        status: "already-exists",
        detail: `${memberId}.netlibrary.eth already points to ${existsCheck.address}`,
      });
      continue;
    }

    // Mint it
    const mintResult = await mintEnsSubname(memberId, member.address, false);
    if (mintResult.success) {
      results.push({
        memberId,
        address: member.address,
        ensSubname: `${memberId}.netlibrary.eth`,
        status: "minted",
        detail: `Successfully minted ${memberId}.netlibrary.eth → ${member.address}`,
      });
    } else {
      results.push({
        memberId,
        address: member.address,
        status: "error",
        detail: mintResult.error ?? "mintEnsSubname failed",
      });
    }
  }

  const mintedCount = results.filter((r) => r.status === "minted").length;
  const errorCount = results.filter((r) => r.status === "error").length;

  return NextResponse.json({ mintedCount, errorCount, results });
}

// ─── POST handler ─────────────────────────────────────────────────────────────

export async function POST(request: NextRequest) {
  if (!isAuthorized(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  let body: Record<string, unknown>;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }

  const dryRun = body.dryRun === true;
  const rawHolders = body.holders;

  if (!Array.isArray(rawHolders) || rawHolders.length === 0) {
    return NextResponse.json({ error: "holders array is required and must be non-empty" }, { status: 400 });
  }

  // Validate each holder entry
  const holders: HolderInput[] = [];
  for (const h of rawHolders as Record<string, unknown>[]) {
    if (typeof h.address !== "string" || !/^0x[0-9a-fA-F]{40}$/i.test(h.address)) {
      return NextResponse.json({ error: `Invalid address: ${h.address}` }, { status: 400 });
    }
    if (typeof h.tokenId !== "number" || !Number.isInteger(h.tokenId) || h.tokenId < 1) {
      return NextResponse.json({ error: `Invalid tokenId for address ${h.address}` }, { status: 400 });
    }
    if (typeof h.tier !== "string" || !["we are so early", "early-ish"].includes(h.tier)) {
      return NextResponse.json({ error: `Invalid tier for address ${h.address}: must be "we are so early" or "early-ish"` }, { status: 400 });
    }
    holders.push({
      address: h.address.toLowerCase(),
      tokenId: h.tokenId as number,
      tier: h.tier as string,
      fid: typeof h.fid === "number" ? h.fid : undefined,
      username: typeof h.username === "string" ? h.username : undefined,
      displayName: typeof h.displayName === "string" ? h.displayName : undefined,
      mintTx: typeof h.mintTx === "string" ? h.mintTx : undefined,
    });
  }

  const results: Array<{
    address: string;
    tokenId: number;
    action: "updated-existing" | "created-new" | "error";
    memberId?: number;
    ensSubname?: string;
    detail?: string;
  }> = [];

  // We'll collect all registry mutations, then do a single write at the end
  const registry = await fetchRegistry();
  let registryDirty = false;

  for (const holder of holders) {
    // Find existing member by address (primary or linked)
    const existing = registry.members.find((m) => {
      if (m.address.toLowerCase() === holder.address) return true;
      if (m.linkedAddresses?.some((a) => a.toLowerCase() === holder.address)) return true;
      return false;
    });

    if (existing) {
      // ── Case A: member already exists — apply pass fields ──────────────────
      if (!dryRun) {
        existing.hasStackPass = true;
        existing.hasUnlimitedPass = true;
        existing.unlimitedPassTokenId = holder.tokenId;
        existing.unlimitedPassTier = holder.tier as "we are so early" | "early-ish";
        existing.unlimitedPassVerified = true;
        if (holder.mintTx) {
          existing.unlimitedPassMintTx = holder.mintTx;
          existing.stackPassTxHash = holder.mintTx;
        }
        existing.stackPassPurchasedAt = existing.stackPassPurchasedAt ?? Date.now();
        registryDirty = true;
      }
      results.push({
        address: holder.address,
        tokenId: holder.tokenId,
        action: "updated-existing",
        memberId: existing.memberId,
        ensSubname: existing.ensSubname,
        detail: dryRun
          ? `[dry-run] Would set pass fields on existing member #${existing.memberId}`
          : `Updated existing member #${existing.memberId} with pass fields`,
      });
    } else {
      // ── Case B: no member record — insert directly into registry ────────────
      if (dryRun) {
        results.push({
          address: holder.address,
          tokenId: holder.tokenId,
          action: "created-new",
          detail: `[dry-run] Would create new member for ${holder.address}` +
            (holder.username ? ` (@${holder.username})` : "") +
            (holder.fid ? ` FID ${holder.fid}` : ""),
        });
        continue;
      }

      // Assign the next member ID and insert directly — same approach as fix-member POST
      const memberId = registry.nextMemberId;
      const ensSubname = `${memberId}.netlibrary.eth`;
      const newMember: MemberEntry = {
        memberId,
        address: holder.address,
        ensSubname,
        fid: holder.fid,
        username: holder.username,
        displayName: holder.displayName,
        joinedAt: Date.now(),
        grantType: "admin",
        grantedBy: "reconcile-pass-holders",
        signupPlatform: "farcaster",
        hasStackPass: true,
        hasUnlimitedPass: true,
        unlimitedPassTokenId: holder.tokenId,
        unlimitedPassTier: holder.tier as "we are so early" | "early-ish",
        unlimitedPassVerified: true,
        stackPassPurchasedAt: Date.now(),
        ...(holder.mintTx ? {
          unlimitedPassMintTx: holder.mintTx,
          stackPassTxHash: holder.mintTx,
        } : {}),
      };

      registry.members.push(newMember);
      registry.nextMemberId = memberId + 1;
      registryDirty = true;

      // Mint ENS subname (best-effort — member record is committed regardless)
      const mintResult = await mintEnsSubname(memberId, holder.address, false);
      if (!mintResult.success) {
        console.error(
          `[reconcile-pass-holders] ENS mint failed for member #${memberId}: ${mintResult.error}`
        );
      }

      console.log(
        `[reconcile-pass-holders] Created member #${memberId} for ${holder.address}` +
          (holder.username ? ` (@${holder.username})` : "") +
          ` with token #${holder.tokenId} (${holder.tier})`
      );

      results.push({
        address: holder.address,
        tokenId: holder.tokenId,
        action: "created-new",
        memberId,
        ensSubname,
        detail: `Created member #${memberId}` +
          (mintResult.success ? ` with ENS ${ensSubname}` : " (ENS mint failed — retry needed)") +
          (holder.username ? ` for @${holder.username}` : ""),
      });
    }
  }

  // Single write covers both Case A (pass field updates) and Case B (new members)
  if (!dryRun && registryDirty) {
    registry.lastUpdated = Date.now();
    const saved = await storeRegistry(registry);
    if (!saved) {
      return NextResponse.json(
        { error: "Failed to persist registry changes", results },
        { status: 500 }
      );
    }
  }

  const updatedCount = results.filter((r) => r.action === "updated-existing").length;
  const createdCount = results.filter((r) => r.action === "created-new").length;
  const errorCount = results.filter((r) => r.action === "error").length;

  console.log(
    `[reconcile-pass-holders] Done — updated: ${updatedCount}, created: ${createdCount}, errors: ${errorCount}` +
      (dryRun ? " [DRY RUN]" : "")
  );

  return NextResponse.json({
    dryRun,
    updatedCount,
    createdCount,
    errorCount,
    results,
  });
}
src/app/api/admin/source-download/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Admin: Source Code Download
 *
 * GET /api/admin/source-download
 * Header: x-admin-secret: <ADMIN_SECRET>
 *
 * Returns a zip of the complete current source tree, suitable for handing
 * to an AI dev tool without any manual browser steps:
 *
 *   curl -H "x-admin-secret: $ADMIN_SECRET" \
 *     https://<host>/api/admin/source-download \
 *     -o source.zip
 *
 * Included:
 *   src/**            — all application source
 *   public/**         — static assets
 *   *.ts / *.mjs / *.json  — root config files (next.config, tsconfig, etc.)
 *   .llm/**           — LLM rules / workflow docs
 *   docs/**           — requirements docs
 *
 * Excluded (never included regardless of path):
 *   node_modules/     — too large, not source
 *   .next/            — build output
 *   .env* files       — secrets
 *   *.key / *.pem     — key material
 *   package-lock.json — large lockfile, not needed for understanding
 *   .git/             — git internals
 */

import { NextRequest, NextResponse } from "next/server";
import fs from "fs";
import path from "path";
import JSZip from "jszip";

// App root is four levels up from this route file:
// src/app/api/admin/source-download/route.ts  →  app root
const APP_ROOT = path.resolve(process.cwd());

const EXCLUDED_DIRS = new Set(["node_modules", ".next", ".git"]);
const EXCLUDED_FILE_PATTERNS = [
  /^\.env/,           // .env, .env.local, .env.production, etc.
  /\.key$/,           // private keys
  /\.pem$/,           // certificates
  /^package-lock\.json$/,  // lockfile — large and not useful for code reading
];

// Directories/globs to include from the root
const INCLUDE_ROOTS = [
  "src",
  "public",
  ".llm",
  "docs",
];

// Root-level files to include (exact names or extensions)
const INCLUDE_ROOT_FILES = (name: string) => {
  if (EXCLUDED_FILE_PATTERNS.some(p => p.test(name))) return false;
  return (
    name.endsWith(".ts") ||
    name.endsWith(".tsx") ||
    name.endsWith(".mjs") ||
    name.endsWith(".cjs") ||
    name.endsWith(".json") ||
    name.endsWith(".md") ||
    name === ".prettierrc" ||
    name === ".npmrc"
  );
};

function isExcluded(filePath: string): boolean {
  const name = path.basename(filePath);
  return EXCLUDED_FILE_PATTERNS.some(p => p.test(name));
}

/**
 * Recursively add a directory to the zip, skipping excluded dirs/files.
 * `zipPath` is the path prefix used inside the archive.
 */
function addDirToZip(zip: JSZip, diskPath: string, zipPath: string): void {
  let entries: fs.Dirent[];
  try {
    entries = fs.readdirSync(diskPath, { withFileTypes: true });
  } catch {
    return; // Directory doesn't exist or isn't readable — skip silently
  }

  for (const entry of entries) {
    const entryDiskPath = path.join(diskPath, entry.name);
    const entryZipPath = `${zipPath}/${entry.name}`;

    if (entry.isDirectory()) {
      if (EXCLUDED_DIRS.has(entry.name)) continue;
      addDirToZip(zip, entryDiskPath, entryZipPath);
    } else if (entry.isFile()) {
      if (isExcluded(entryDiskPath)) continue;
      try {
        const content = fs.readFileSync(entryDiskPath);
        zip.file(entryZipPath, content);
      } catch {
        // Unreadable file — skip
      }
    }
  }
}

function isAuthorized(request: NextRequest): boolean {
  const adminSecret = process.env.ADMIN_SECRET;
  if (!adminSecret) return false;
  return request.headers.get("x-admin-secret") === adminSecret;
}

export async function GET(request: NextRequest) {
  if (!isAuthorized(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const zip = new JSZip();
  const rootFolder = "netlibrary-source";

  // Add included sub-directories
  for (const dir of INCLUDE_ROOTS) {
    const diskPath = path.join(APP_ROOT, dir);
    if (fs.existsSync(diskPath)) {
      addDirToZip(zip, diskPath, `${rootFolder}/${dir}`);
    }
  }

  // Add root-level config files
  try {
    const rootEntries = fs.readdirSync(APP_ROOT, { withFileTypes: true });
    for (const entry of rootEntries) {
      if (entry.isFile() && INCLUDE_ROOT_FILES(entry.name)) {
        const content = fs.readFileSync(path.join(APP_ROOT, entry.name));
        zip.file(`${rootFolder}/${entry.name}`, content);
      }
    }
  } catch {
    // Non-fatal — root file listing failed
  }

  // Generate zip buffer
  const zipBuffer = await zip.generateAsync({
    type: "nodebuffer",
    compression: "DEFLATE",
    compressionOptions: { level: 6 },
  });

  // Timestamp in filename: netlibrary-source-2026-03-10.zip
  const today = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
  const filename = `netlibrary-source-${today}.zip`;

  return new NextResponse(zipBuffer, {
    status: 200,
    headers: {
      "Content-Type": "application/zip",
      "Content-Disposition": `attachment; filename="${filename}"`,
      "Content-Length": String(zipBuffer.byteLength),
      // No caching — always serve a fresh snapshot
      "Cache-Control": "no-store",
    },
  });
}
src/app/api/admin/stats/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Admin: Full Library Stats
 *
 * Two auth paths — both restricted to admin only:
 *
 * A) Server-to-server / curl:
 *    GET /api/admin/stats
 *    Header: x-admin-secret: <ADMIN_SECRET>
 *
 * B) In-app UI (no secret exposed to client):
 *    POST /api/admin/stats
 *    Body: { fid: 282520 }
 *    The FID is verified server-side — only FID 282520 is accepted.
 *    No secret is ever sent to the browser.
 *
 * Returns complete upload statistics including hidden items.
 * Public-facing leaderboard intentionally excludes hidden entries.
 */

import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { DISCOVERY_INDEX_KEY } from "@/lib/discovery-ops";
import type { DiscoveryEntry } from "@/lib/net-protocol";

const ADMIN_FID = 282520;

function isAuthorizedHeader(request: NextRequest): boolean {
  const adminSecret = process.env.ADMIN_SECRET;
  if (!adminSecret) return false;
  return request.headers.get("x-admin-secret") === adminSecret;
}

async function fetchAllEntries(): Promise<DiscoveryEntry[]> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_INDEX_KEY)).limit(1);
    if (!result[0]?.value) return [];
    return JSON.parse(result[0].value) as DiscoveryEntry[];
  } catch {
    return [];
  }
}

function buildStatsResponse(entries: DiscoveryEntry[]) {
  const uploaderMap = new Map<string, {
    address: string;
    allUploads: number;
    publicUploads: number;
    hiddenUploads: number;
    allBytes: number;
    firstUploadAt: number;
    lastUploadAt: number;
  }>();

  let totalBytes = 0;
  let publicBytes = 0;
  let hiddenBytes = 0;
  const hiddenEntries: object[] = [];

  for (const entry of entries) {
    const addr = (entry.uploaderAddress || entry.operator || "unknown").toLowerCase();
    const isHidden = !!entry.hidden;
    const bytes = entry.fileSize || 0;

    totalBytes += bytes;
    if (isHidden) {
      hiddenBytes += bytes;
      hiddenEntries.push({
        contentKey: entry.contentKey,
        title: entry.title,
        author: entry.author,
        uploaderAddress: entry.uploaderAddress,
        operator: entry.operator,
        uploadedAt: entry.uploadedAt,
        fileSize: entry.fileSize,
        hiddenAt: (entry as Record<string, unknown>).hiddenAt,
        hiddenReason: (entry as Record<string, unknown>).hiddenReason,
      });
    } else {
      publicBytes += bytes;
    }

    const existing = uploaderMap.get(addr);
    if (existing) {
      existing.allUploads += 1;
      existing.allBytes += bytes;
      if (isHidden) existing.hiddenUploads += 1;
      else existing.publicUploads += 1;
      existing.firstUploadAt = Math.min(existing.firstUploadAt, entry.uploadedAt || Date.now());
      existing.lastUploadAt = Math.max(existing.lastUploadAt, entry.uploadedAt || 0);
    } else {
      uploaderMap.set(addr, {
        address: addr,
        allUploads: 1,
        publicUploads: isHidden ? 0 : 1,
        hiddenUploads: isHidden ? 1 : 0,
        allBytes: bytes,
        firstUploadAt: entry.uploadedAt || Date.now(),
        lastUploadAt: entry.uploadedAt || 0,
      });
    }
  }

  return {
    totals: {
      allEntries: entries.length,
      publicEntries: entries.length - hiddenEntries.length,
      hiddenEntries: hiddenEntries.length,
      totalBytes,
      publicBytes,
      hiddenBytes,
    },
    byUploader: Array.from(uploaderMap.values()).sort((a, b) => b.allUploads - a.allUploads),
    hiddenEntries,
  };
}

// GET — curl / server-to-server access via x-admin-secret header
export async function GET(request: NextRequest) {
  if (!isAuthorizedHeader(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const entries = await fetchAllEntries();
  return NextResponse.json(buildStatsResponse(entries));
}

// POST — in-app UI access; FID verified server-side, no secret needed on client
export async function POST(request: NextRequest) {
  let body: Record<string, unknown>;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }

  // Only FID 282520 may use this endpoint — enforced server-side
  if (body.fid !== ADMIN_FID) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const entries = await fetchAllEntries();
  return NextResponse.json(buildStatsResponse(entries));
}
src/app/api/backfill-covers/extract/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry } from "@/lib/net-protocol";

const DISCOVERY_KEY = "discovery-index";

/**
 * POST - Update cover URL for a specific entry
 * Called from client after extracting cover with PDF.js
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { contentKey, operator, coverUrl } = body;

    if (!contentKey || !operator || !coverUrl) {
      return NextResponse.json({ error: "Missing contentKey, operator, or coverUrl" }, { status: 400 });
    }

    // Fetch current discovery index
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    const entries: DiscoveryEntry[] = result[0]?.value
      ? JSON.parse(result[0].value)
      : [];

    // Find and update the entry
    const entryIndex = entries.findIndex(
      e => e.contentKey === contentKey && e.operator && e.operator.toLowerCase() === operator.toLowerCase()
    );

    if (entryIndex === -1) {
      return NextResponse.json({ error: "Entry not found" }, { status: 404 });
    }

    // Update with cover
    entries[entryIndex] = {
      ...entries[entryIndex],
      coverUrl,
    };

    // Save
    await db.insert(kv).values({ key: DISCOVERY_KEY, value: JSON.stringify(entries) })
      .onConflictDoUpdate({ target: kv.key, set: { value: JSON.stringify(entries) } });

    return NextResponse.json({
      success: true,
      title: entries[entryIndex].title,
      coverUrl,
    });
  } catch (error) {
    console.error("[backfill-covers/extract] Error:", error);
    return NextResponse.json({ error: "Failed to update cover" }, { status: 500 });
  }
}
src/app/api/backfill-covers/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry } from "@/lib/net-protocol";

const DISCOVERY_KEY = "discovery-index";
const COVER_BACKFILL_KEY = "cover-backfill-status";

interface BackfillStatus {
  lastRun: number;
  processedKeys: string[];
  failedKeys: string[];
}

// GET - Get backfill status and entries needing covers
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const action = searchParams.get("action");

    // Get discovery entries
    const discoveryResult = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    const entries: DiscoveryEntry[] = discoveryResult[0]?.value
      ? JSON.parse(discoveryResult[0].value)
      : [];

    // Get backfill status
    const statusResult = await db.select().from(kv).where(eq(kv.key, COVER_BACKFILL_KEY)).limit(1);
    const status: BackfillStatus = statusResult[0]?.value
      ? JSON.parse(statusResult[0].value)
      : { lastRun: 0, processedKeys: [], failedKeys: [] };

    // Find entries without covers OR with base64 data URL covers (need to be converted to hosted URLs)
    const entriesNeedingCovers = entries.filter(e => {
      // Skip if already processed or failed
      if (status.processedKeys.includes(e.contentKey) || status.failedKeys.includes(e.contentKey)) {
        return false;
      }
      // Needs processing if no cover OR cover is a base64 data URL
      return !e.coverUrl || e.coverUrl.startsWith("data:");
    });

    if (action === "list") {
      // Return entries that need cover extraction
      const withHostedCovers = entries.filter(e => e.coverUrl && !e.coverUrl.startsWith("data:")).length;
      const withDataUrlCovers = entries.filter(e => e.coverUrl && e.coverUrl.startsWith("data:")).length;

      return NextResponse.json({
        success: true,
        total: entries.length,
        withHostedCovers,
        withDataUrlCovers,
        withCovers: entries.filter(e => e.coverUrl).length, // Legacy field
        needingCovers: entriesNeedingCovers.length,
        failed: status.failedKeys.length,
        entries: entriesNeedingCovers.map(e => ({
          contentKey: e.contentKey,
          title: e.title,
          operator: e.operator,
          storageType: e.storageType,
          fileName: e.fileName, // For correct CDN URL format
          cdnUrl: e.cdnUrl, // Preferred if stored
          hasDataUrlCover: e.coverUrl?.startsWith("data:") || false,
        })),
      });
    }

    return NextResponse.json({
      success: true,
      status,
      entriesNeedingCovers: entriesNeedingCovers.length,
    });
  } catch (error) {
    console.error("[backfill-covers] GET error:", error);
    return NextResponse.json({ error: "Failed to get backfill status" }, { status: 500 });
  }
}

// PATCH - Reset failed entries so they can be retried
export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, contentKey } = body;

    if (action !== "reset-failed") {
      return NextResponse.json({ error: "Invalid action. Use 'reset-failed'" }, { status: 400 });
    }

    // Get backfill status
    const statusResult = await db.select().from(kv).where(eq(kv.key, COVER_BACKFILL_KEY)).limit(1);
    const status: BackfillStatus = statusResult[0]?.value
      ? JSON.parse(statusResult[0].value)
      : { lastRun: 0, processedKeys: [], failedKeys: [] };

    if (contentKey) {
      // Reset specific entry
      status.failedKeys = status.failedKeys.filter(k => k !== contentKey);
      status.processedKeys = status.processedKeys.filter(k => k !== contentKey);
    } else {
      // Reset all failed
      status.failedKeys = [];
    }

    status.lastRun = Date.now();
    await db.insert(kv).values({ key: COVER_BACKFILL_KEY, value: JSON.stringify(status) })
      .onConflictDoUpdate({ target: kv.key, set: { value: JSON.stringify(status) } });

    return NextResponse.json({
      success: true,
      message: contentKey ? `Reset ${contentKey}` : "Reset all failed entries",
      failedCount: status.failedKeys.length,
    });
  } catch (error) {
    console.error("[backfill-covers] PATCH error:", error);
    return NextResponse.json({ error: "Failed to reset" }, { status: 500 });
  }
}

// POST - Update cover for an entry (called from client after extraction)
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { contentKey, operator, coverUrl, failed } = body;

    if (!contentKey || !operator) {
      return NextResponse.json({ error: "Missing contentKey or operator" }, { status: 400 });
    }

    // Get current discovery index
    const discoveryResult = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    const entries: DiscoveryEntry[] = discoveryResult[0]?.value
      ? JSON.parse(discoveryResult[0].value)
      : [];

    // Get backfill status
    const statusResult = await db.select().from(kv).where(eq(kv.key, COVER_BACKFILL_KEY)).limit(1);
    const status: BackfillStatus = statusResult[0]?.value
      ? JSON.parse(statusResult[0].value)
      : { lastRun: 0, processedKeys: [], failedKeys: [] };

    if (failed) {
      // Mark as failed
      if (!status.failedKeys.includes(contentKey)) {
        status.failedKeys.push(contentKey);
        status.lastRun = Date.now();
        await db.insert(kv).values({ key: COVER_BACKFILL_KEY, value: JSON.stringify(status) })
          .onConflictDoUpdate({ target: kv.key, set: { value: JSON.stringify(status) } });
      }

      return NextResponse.json({ success: true, marked: "failed" });
    }

    if (!coverUrl) {
      return NextResponse.json({ error: "Missing coverUrl" }, { status: 400 });
    }

    // Find and update the entry
    const entryIndex = entries.findIndex(
      e => e.contentKey === contentKey && e.operator && e.operator.toLowerCase() === operator.toLowerCase()
    );

    if (entryIndex === -1) {
      return NextResponse.json({ error: "Entry not found" }, { status: 404 });
    }

    // Update entry with cover
    entries[entryIndex] = {
      ...entries[entryIndex],
      coverUrl,
    };

    // Save updated entries
    await db.insert(kv).values({ key: DISCOVERY_KEY, value: JSON.stringify(entries) })
      .onConflictDoUpdate({ target: kv.key, set: { value: JSON.stringify(entries) } });

    // Update backfill status
    if (!status.processedKeys.includes(contentKey)) {
      status.processedKeys.push(contentKey);
      status.lastRun = Date.now();
      await db.insert(kv).values({ key: COVER_BACKFILL_KEY, value: JSON.stringify(status) })
        .onConflictDoUpdate({ target: kv.key, set: { value: JSON.stringify(status) } });
    }

    return NextResponse.json({
      success: true,
      entry: entries[entryIndex],
    });
  } catch (error) {
    console.error("[backfill-covers] POST error:", error);
    return NextResponse.json({ error: "Failed to update cover" }, { status: 500 });
  }
}
src/app/api/backfill-media-types/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry } from "@/lib/net-protocol";
import { BASE_CHAIN_ID } from "@/lib/net-protocol";

const DISCOVERY_KEY = "discovery-index";

// Detect media type from URL patterns and file characteristics
function detectMediaTypeFromMetadata(entry: DiscoveryEntry): "pdf" | "image" | "audio" | "video" | "text" | "unknown" {
  const title = (entry.title || "").toLowerCase();
  const cdnUrl = (entry.cdnUrl || "").toLowerCase();

  // Check file extensions in title (often includes original filename)
  // Audio
  if (
    title.endsWith(".mp3") || title.endsWith(".wav") || title.endsWith(".ogg") ||
    title.endsWith(".flac") || title.endsWith(".m4a") || title.endsWith(".aac") ||
    title.includes(".mp3") || title.includes(".wav") || title.includes(".ogg") ||
    title.includes(".flac") || title.includes(".m4a") || title.includes(".aac")
  ) {
    return "audio";
  }

  // Video
  if (
    title.endsWith(".mp4") || title.endsWith(".webm") || title.endsWith(".mov") ||
    title.endsWith(".avi") || title.endsWith(".mkv") ||
    title.includes(".mp4") || title.includes(".webm") || title.includes(".mov")
  ) {
    return "video";
  }

  // PDF
  if (title.endsWith(".pdf") || title.includes(".pdf")) {
    return "pdf";
  }

  // Text
  if (
    title.endsWith(".txt") || title.endsWith(".md") || title.endsWith(".json") ||
    title.endsWith(".xml") || title.endsWith(".csv")
  ) {
    return "text";
  }

  // Image
  if (
    title.endsWith(".png") || title.endsWith(".jpg") || title.endsWith(".jpeg") ||
    title.endsWith(".gif") || title.endsWith(".webp") || title.endsWith(".svg")
  ) {
    return "image";
  }

  // Check CDN URL patterns
  if (cdnUrl.includes(".mp3") || cdnUrl.includes(".wav") || cdnUrl.includes(".ogg")) {
    return "audio";
  }
  if (cdnUrl.includes(".mp4") || cdnUrl.includes(".webm") || cdnUrl.includes(".mov")) {
    return "video";
  }

  // Default to unknown if we can't determine
  return "unknown";
}

// Convert MIME type to our mediaType categories
function mimeToMediaType(mimeType: string): "pdf" | "image" | "audio" | "video" | "text" | "unknown" {
  const mime = mimeType.toLowerCase();
  if (mime === "application/pdf") return "pdf";
  if (mime.startsWith("audio/")) return "audio";
  if (mime.startsWith("video/")) return "video";
  if (mime.startsWith("image/")) return "image";
  if (mime.startsWith("text/") || mime === "application/json" || mime === "application/xml") return "text";
  return "unknown";
}

// Fetch content type from CDN URL via HEAD request
async function fetchContentType(entry: DiscoveryEntry): Promise<string | null> {
  // Build the CDN URL if not present
  // Use stored cdnUrl > /storage/load/ with fileName > /storage/raw/ fallback
  // Note: /content/{key} format is DEPRECATED and returns 404
  let url = entry.cdnUrl;
  if (!url && entry.contentKey && entry.operator) {
    if (entry.fileName) {
      url = `https://storedon.net/net/${BASE_CHAIN_ID}/storage/load/${entry.operator}/${encodeURIComponent(entry.fileName)}`;
    } else {
      // Fallback to storage/raw for legacy entries without fileName
      url = `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${entry.operator}/${entry.contentKey}`;
    }
  }
  if (!url) return null;

  try {
    const response = await fetch(url, { method: "HEAD" });
    const contentType = response.headers.get("content-type");
    return contentType;
  } catch (error) {
    console.error(`Failed to fetch content type for ${entry.contentKey}:`, error);
    return null;
  }
}

// POST: Backfill mediaType for discovery entries missing it
export async function POST(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const dryRun = searchParams.get("dryRun") === "true";
    const fetchFromCdn = searchParams.get("fetchFromCdn") === "true";

    // Fetch discovery index
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    if (!result[0]?.value) {
      return NextResponse.json({ success: false, error: "Discovery index not found" }, { status: 404 });
    }

    const entries: DiscoveryEntry[] = JSON.parse(result[0].value);
    const originalCount = entries.length;

    // Track changes
    const changes: Array<{ title: string; contentKey: string; oldType?: string; newType: string; source: string }> = [];

    // Process entries - need to handle async if fetching from CDN
    const updatedEntries: DiscoveryEntry[] = [];

    for (const entry of entries) {
      // Skip if already has a valid mediaType
      if (entry.mediaType && entry.mediaType !== "unknown") {
        updatedEntries.push(entry);
        continue;
      }

      // First try to detect from metadata (title, url patterns)
      let detectedType = detectMediaTypeFromMetadata(entry);
      let source = "metadata";

      // If still unknown and fetchFromCdn is enabled, try HEAD request
      if (detectedType === "unknown" && fetchFromCdn) {
        const contentType = await fetchContentType(entry);
        if (contentType) {
          detectedType = mimeToMediaType(contentType);
          source = `cdn: ${contentType}`;
        }
      }

      // Only update if we detected something useful
      if (detectedType !== "unknown") {
        changes.push({
          title: entry.title,
          contentKey: entry.contentKey,
          oldType: entry.mediaType,
          newType: detectedType,
          source,
        });

        updatedEntries.push({
          ...entry,
          mediaType: detectedType,
        });
      } else {
        updatedEntries.push(entry);
      }
    }

    // Save if not dry run
    if (!dryRun && changes.length > 0) {
      await db.update(kv)
        .set({ value: JSON.stringify(updatedEntries) })
        .where(eq(kv.key, DISCOVERY_KEY));
    }

    return NextResponse.json({
      success: true,
      dryRun,
      fetchFromCdn,
      totalEntries: originalCount,
      entriesUpdated: changes.length,
      changes: changes.slice(0, 50), // Limit response size
      message: dryRun
        ? `Would update ${changes.length} entries. Run without dryRun=true to apply.`
        : `Updated ${changes.length} entries with mediaType.`,
    });
  } catch (error) {
    console.error("Backfill error:", error);
    return NextResponse.json(
      { success: false, error: "Failed to backfill media types" },
      { status: 500 }
    );
  }
}

// PUT: Manually set mediaType for specific entries
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    const { contentKey, mediaType } = body;

    if (!contentKey || !mediaType) {
      return NextResponse.json(
        { success: false, error: "contentKey and mediaType are required" },
        { status: 400 }
      );
    }

    // Validate mediaType
    const validTypes = ["pdf", "image", "audio", "video", "text", "unknown"];
    if (!validTypes.includes(mediaType)) {
      return NextResponse.json(
        { success: false, error: `Invalid mediaType. Must be one of: ${validTypes.join(", ")}` },
        { status: 400 }
      );
    }

    // Fetch discovery index
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    if (!result[0]?.value) {
      return NextResponse.json({ success: false, error: "Discovery index not found" }, { status: 404 });
    }

    const entries: DiscoveryEntry[] = JSON.parse(result[0].value);

    // Find and update the entry
    let found = false;
    const updatedEntries = entries.map(entry => {
      if (entry.contentKey === contentKey) {
        found = true;
        return { ...entry, mediaType };
      }
      return entry;
    });

    if (!found) {
      return NextResponse.json(
        { success: false, error: `Entry with contentKey ${contentKey} not found` },
        { status: 404 }
      );
    }

    // Save
    await db.update(kv)
      .set({ value: JSON.stringify(updatedEntries) })
      .where(eq(kv.key, DISCOVERY_KEY));

    return NextResponse.json({
      success: true,
      message: `Updated mediaType to "${mediaType}" for entry ${contentKey}`,
    });
  } catch (error) {
    console.error("Update error:", error);
    return NextResponse.json(
      { success: false, error: "Failed to update mediaType" },
      { status: 500 }
    );
  }
}

// GET: Check status of mediaType coverage
export async function GET() {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    if (!result[0]?.value) {
      return NextResponse.json({ success: false, error: "Discovery index not found" }, { status: 404 });
    }

    const entries: DiscoveryEntry[] = JSON.parse(result[0].value);

    const stats = {
      total: entries.length,
      withMediaType: 0,
      withoutMediaType: 0,
      byType: {} as Record<string, number>,
    };

    entries.forEach(entry => {
      if (entry.mediaType) {
        stats.withMediaType++;
        stats.byType[entry.mediaType] = (stats.byType[entry.mediaType] || 0) + 1;
      } else {
        stats.withoutMediaType++;
      }
    });

    // Find entries without mediaType
    const missingMediaType = entries
      .filter(e => !e.mediaType)
      .slice(0, 20)
      .map(e => ({ title: e.title, contentKey: e.contentKey }));

    return NextResponse.json({
      success: true,
      stats,
      missingMediaType,
    });
  } catch (error) {
    console.error("Stats error:", error);
    return NextResponse.json(
      { success: false, error: "Failed to get stats" },
      { status: 500 }
    );
  }
}
src/app/api/book-content/route.ts
import { NextRequest, NextResponse } from "next/server";
import { getRawStorageUrl, BASE_CHAIN_ID, createStorageClient } from "@/lib/net-protocol";
import { parseNetReferences, assembleChunks } from "@net-protocol/storage";
import pako from "pako";

// GET - Fetch book content from Net Protocol (server-side to avoid CORS)
export async function GET(request: NextRequest) {
  console.log("[book-content] API called at", new Date().toISOString());
  const contentKey = request.nextUrl.searchParams.get("contentKey");
  const operatorAddress = request.nextUrl.searchParams.get("operator");
  const storageType = request.nextUrl.searchParams.get("storageType") || "regular";

  console.log("[book-content] Params:", { contentKey: contentKey?.slice(0, 20), operatorAddress: operatorAddress?.slice(0, 10), storageType });

  if (!contentKey || !operatorAddress) {
    return NextResponse.json(
      { error: "contentKey and operator required" },
      { status: 400 }
    );
  }

  try {
    // For XML storage, use the SDK to properly reconstruct content
    if (storageType === "xml") {
      console.log("[book-content] XML storage - reconstructing from chunks...");

      try {
        console.log("[book-content] Creating storage client...");
        const storageClient = createStorageClient(BASE_CHAIN_ID);
        console.log("[book-content] Storage client created, calling readStorageData...");

        // Use SDK's readStorageData which handles XML resolution
        const result = await storageClient.readStorageData({
          key: contentKey,
          operator: operatorAddress,
          keyFormat: "bytes32",
        });
        console.log("[book-content] SDK call completed!");

        console.log("[book-content] SDK readStorageData result - isXml:", result.isXml);
        console.log("[book-content] SDK result.data type:", typeof result.data);
        console.log("[book-content] SDK result keys:", Object.keys(result));

        if (result.data) {
          const dataLength = result.data.length;
          console.log("[book-content] Result data length:", dataLength);
          console.log("[book-content] Result data first 100 chars:", result.data.slice(0, 100));

          // Quick check: if it's base64 starting with "JVBER" (PDF magic in base64)
          if (result.data.startsWith("JVBERi")) {
            console.log("[book-content] Detected base64-encoded PDF");
            const fileSizeKB = Math.round((result.data.length * 3 / 4) / 1024);
            console.log("[book-content] PDF size (estimated):", fileSizeKB, "KB");

            // Return URL to PDF endpoint instead of embedding huge base64
            const pdfUrl = `/api/pdf-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}`;
            return NextResponse.json({
              success: true,
              storageType: "pdf-data",
              isPdf: true,
              pdfDataUrl: pdfUrl,
              sentences: [
                "📄 PDF document loaded from onchain storage.",
                `File size: ${fileSizeKB} KB`,
              ],
            });
          }

          // First, check if it's hex data that might be a PDF
          const isHexData = result.data.startsWith("0x");
          console.log("[book-content] Result data format:", isHexData ? "hex" : "text");

          // For binary file detection, we need to handle hex data specially
          if (isHexData) {
            const cleanHex = result.data.slice(2);
            const bytes = Buffer.from(cleanHex, "hex");
            console.log("[book-content] Converted to bytes, length:", bytes.length);
            console.log("[book-content] First 10 bytes:", Array.from(bytes.slice(0, 10)));

            // Check for PDF magic bytes directly in the hex-decoded bytes
            if (bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46) {
              console.log("[book-content] Direct PDF detection from hex bytes!");
              const fileSizeKB = Math.round(bytes.length / 1024);
              const pdfUrl = `/api/pdf-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}`;
              return NextResponse.json({
                success: true,
                storageType: "pdf-data",
                isPdf: true,
                pdfDataUrl: pdfUrl,
                sentences: [
                  "📄 PDF document loaded from onchain storage.",
                  `File size: ${fileSizeKB} KB`,
                ],
              });
            }

            // Check for MP3 magic bytes: ID3 (0x49 0x44 0x33) or MPEG frame sync (0xFF 0xFB/FA/F3/F2)
            if ((bytes[0] === 0x49 && bytes[1] === 0x44 && bytes[2] === 0x33) ||
                (bytes[0] === 0xFF && (bytes[1] === 0xFB || bytes[1] === 0xFA || bytes[1] === 0xF3 || bytes[1] === 0xF2 || bytes[1] === 0xE3))) {
              console.log("[book-content] Direct MP3 audio detection from hex bytes!");
              const cdnUrl = `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=xml`;
              return NextResponse.json({
                success: true,
                storageType: "audio",
                isAudio: true,
                mediaType: "audio",
                cdnUrl,
                sentences: ["🎵 Audio file detected.", "Opening audio player..."],
              });
            }

            // Check for WAV magic bytes: RIFF + WAVE
            if (bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46 &&
                bytes.length > 11 && bytes[8] === 0x57 && bytes[9] === 0x41 && bytes[10] === 0x56 && bytes[11] === 0x45) {
              console.log("[book-content] Direct WAV audio detection from hex bytes!");
              const cdnUrl = `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=xml`;
              return NextResponse.json({
                success: true,
                storageType: "audio",
                isAudio: true,
                mediaType: "audio",
                cdnUrl,
                sentences: ["🎵 Audio file detected.", "Opening audio player..."],
              });
            }

            // Check for OGG magic bytes: OggS (0x4F 0x67 0x67 0x53)
            if (bytes[0] === 0x4F && bytes[1] === 0x67 && bytes[2] === 0x67 && bytes[3] === 0x53) {
              console.log("[book-content] Direct OGG audio detection from hex bytes!");
              const cdnUrl = `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=xml`;
              return NextResponse.json({
                success: true,
                storageType: "audio",
                isAudio: true,
                mediaType: "audio",
                cdnUrl,
                sentences: ["🎵 Audio file detected.", "Opening audio player..."],
              });
            }

            // Check for FLAC magic bytes: fLaC (0x66 0x4C 0x61 0x43)
            if (bytes[0] === 0x66 && bytes[1] === 0x4C && bytes[2] === 0x61 && bytes[3] === 0x43) {
              console.log("[book-content] Direct FLAC audio detection from hex bytes!");
              const cdnUrl = `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=xml`;
              return NextResponse.json({
                success: true,
                storageType: "audio",
                isAudio: true,
                mediaType: "audio",
                cdnUrl,
                sentences: ["🎵 Audio file detected.", "Opening audio player..."],
              });
            }

            // Check for M4A/MP4/MOV magic bytes: ftyp at offset 4
            if (bytes.length > 11 && bytes[4] === 0x66 && bytes[5] === 0x74 && bytes[6] === 0x79 && bytes[7] === 0x70) {
              const subtype = bytes.slice(8, 12).toString("ascii");
              console.log("[book-content] Detected ftyp container, subtype:", subtype);
              if (subtype.includes("M4A") || subtype.includes("mp4a") || subtype.toLowerCase().includes("m4a")) {
                console.log("[book-content] Direct M4A audio detection from hex bytes!");
                const cdnUrl = `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=xml`;
                return NextResponse.json({
                  success: true,
                  storageType: "audio",
                  isAudio: true,
                  mediaType: "audio",
                  cdnUrl,
                  sentences: ["🎵 Audio file detected.", "Opening audio player..."],
                });
              }
              // Otherwise it's video (MP4/MOV)
              console.log("[book-content] Direct MP4/MOV video detection from hex bytes!");
              const cdnUrl = `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=xml`;
              return NextResponse.json({
                success: true,
                storageType: "video",
                isVideo: true,
                mediaType: "video",
                cdnUrl,
                sentences: ["🎬 Video file detected.", "Opening video player..."],
              });
            }

            // Check for WebM magic bytes: EBML (0x1A 0x45 0xDF 0xA3)
            if (bytes[0] === 0x1A && bytes[1] === 0x45 && bytes[2] === 0xDF && bytes[3] === 0xA3) {
              console.log("[book-content] Direct WebM video detection from hex bytes!");
              const cdnUrl = `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=xml`;
              return NextResponse.json({
                success: true,
                storageType: "video",
                isVideo: true,
                mediaType: "video",
                cdnUrl,
                sentences: ["🎬 Video file detected.", "Opening video player..."],
              });
            }

            // Check for image magic bytes
            // PNG: 0x89 0x50 0x4E 0x47
            if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4E && bytes[3] === 0x47) {
              console.log("[book-content] Direct PNG image detection from hex bytes!");
              const cdnUrl = `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=xml`;
              return NextResponse.json({
                success: true,
                storageType: "image",
                isImage: true,
                mediaType: "image",
                cdnUrl,
                sentences: ["🖼️ Image file detected.", "Opening image viewer..."],
              });
            }
            // JPEG: 0xFF 0xD8 0xFF
            if (bytes[0] === 0xFF && bytes[1] === 0xD8 && bytes[2] === 0xFF) {
              console.log("[book-content] Direct JPEG image detection from hex bytes!");
              const cdnUrl = `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=xml`;
              return NextResponse.json({
                success: true,
                storageType: "image",
                isImage: true,
                mediaType: "image",
                cdnUrl,
                sentences: ["🖼️ Image file detected.", "Opening image viewer..."],
              });
            }
            // GIF: GIF87a or GIF89a (0x47 0x49 0x46 0x38)
            if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38) {
              console.log("[book-content] Direct GIF image detection from hex bytes!");
              const cdnUrl = `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=xml`;
              return NextResponse.json({
                success: true,
                storageType: "image",
                isImage: true,
                mediaType: "image",
                cdnUrl,
                sentences: ["🖼️ Image file detected.", "Opening image viewer..."],
              });
            }
          }

          // Decode from hex if needed (for non-PDF content)
          const decoded = isHexData ? hexToString(result.data) : result.data;

          console.log("[book-content] Decoded content length:", decoded.length);
          console.log("[book-content] Decoded content preview (first 300 chars):", decoded.slice(0, 300));

          // Determine what type of content this is
          const contentAnalysis = analyzeContent(decoded);
          console.log("[book-content] Content analysis:", contentAnalysis);

          if (contentAnalysis.type === "pdf") {
            // Return URL to PDF endpoint for browser rendering
            if (contentAnalysis.pdfBuffer) {
              console.log("[book-content] Got PDF buffer from analyzeContent, size:", contentAnalysis.pdfBuffer.length);
              const fileSizeKB = Math.round(contentAnalysis.pdfBuffer.length / 1024);
              const pdfUrl = `/api/pdf-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}`;
              return NextResponse.json({
                success: true,
                storageType: "pdf-data",
                isPdf: true,
                pdfDataUrl: pdfUrl,
                sentences: [
                  "📄 PDF document loaded from onchain storage.",
                  `File size: ${fileSizeKB} KB`,
                ],
              });
            }

            // No pdfBuffer available - PDF detected but can't get binary data
            return NextResponse.json({
              success: true,
              storageType: "pdf",
              isPdf: true,
              sentences: [
                "📄 PDF document detected.",
                'Tap "View on Net Protocol" to read the document.',
              ],
            });
          }

          if (contentAnalysis.type === "text") {
            const sentences = parseContentToSentences(contentAnalysis.content);
            // For text files, provide both sentences (for basic reader) and mediaType/cdnUrl (for MultimediaViewer)
            const cdnUrl = `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=xml`;
            return NextResponse.json({
              success: true,
              storageType: "xml-reconstructed",
              mediaType: "text",
              cdnUrl,
              sentences: sentences.length > 0 ? sentences : ["No readable text content found."],
            });
          }

          // Audio file - redirect to multimedia viewer
          // For XML storage, use book-file API which reconstructs from chunks
          if (contentAnalysis.type === "audio") {
            const cdnUrl = `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=xml`;
            return NextResponse.json({
              success: true,
              storageType: "audio",
              isAudio: true,
              mediaType: "audio",
              cdnUrl,
              sentences: [
                "🎵 Audio file detected.",
                "Opening audio player...",
              ],
            });
          }

          // Video file - redirect to multimedia viewer
          // For XML storage, use book-file API which reconstructs from chunks
          if (contentAnalysis.type === "video") {
            const cdnUrl = `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=xml`;
            return NextResponse.json({
              success: true,
              storageType: "video",
              isVideo: true,
              mediaType: "video",
              cdnUrl,
              sentences: [
                "🎬 Video file detected.",
                "Opening video player...",
              ],
            });
          }

          // Image file - redirect to multimedia viewer
          // For XML storage, use book-file API which reconstructs from chunks
          if (contentAnalysis.type === "image") {
            const cdnUrl = `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=xml`;
            return NextResponse.json({
              success: true,
              storageType: "image",
              isImage: true,
              mediaType: "image",
              cdnUrl,
              sentences: [
                "🖼️ Image file detected.",
                "Opening image viewer...",
              ],
            });
          }

          // Binary but not PDF/audio/video/image
          if (contentAnalysis.type === "binary") {
            return NextResponse.json({
              success: true,
              storageType: "binary",
              sentences: [
                "This file is a binary document.",
                'Click "Open" to view it directly.',
                "File stored successfully on Net Protocol.",
              ],
            });
          }

          // Unknown - try parsing as text anyway
          const sentences = parseContentToSentences(decoded);
          return NextResponse.json({
            success: true,
            storageType: "xml-reconstructed",
            sentences: sentences.length > 0 ? sentences : ["No readable text content found."],
          });
        }
      } catch (sdkError) {
        console.error("[book-content] SDK reconstruction failed, trying manual approach:", sdkError);

        // Fallback: Manual chunk reconstruction
        const manualResult = await reconstructXmlChunksManually(contentKey, operatorAddress);
        if (manualResult) {
          const sentences = parseContentToSentences(manualResult);
          return NextResponse.json({
            success: true,
            storageType: "xml-manual",
            sentences: sentences.length > 0 ? sentences : ["No readable text content found."],
          });
        }
      }

      // If reconstruction failed, return helpful message
      return NextResponse.json({
        success: true,
        storageType: "xml",
        sentences: [
          "📖 This book is stored onchain using XML chunked storage.",
          "Content reconstruction encountered an issue.",
          'Click "Open" to try viewing the file directly.',
          `Content key: ${contentKey.slice(0, 20)}...`,
        ],
      });
    }

    // For chunked storage, use the chunked-storage endpoint
    if (storageType === "chunked") {
      console.log("[book-content] Chunked storage - fetching from chunked endpoint...");

      // Retry logic for newly uploaded content (storedon.net indexer may be slow)
      const chunkedUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/chunked-storage/raw/${operatorAddress}/${contentKey}`;
      const retryDelays = [0, 3000, 5000, 8000, 12000]; // Initial + 4 retries with exponential backoff
      let response: Response | null = null;

      for (let attempt = 0; attempt < retryDelays.length; attempt++) {
        if (attempt > 0) {
          console.log(`[book-content] Retry ${attempt}/${retryDelays.length - 1} after ${retryDelays[attempt]}ms...`);
          await new Promise(resolve => setTimeout(resolve, retryDelays[attempt]));
        }

        console.log("[book-content] Fetching from:", chunkedUrl);

        try {
          response = await fetch(chunkedUrl, {
            headers: { "Accept": "application/json" },
          });

          if (response.ok) {
            console.log(`[book-content] Chunked fetch succeeded on attempt ${attempt + 1}`);
            break;
          } else if (response.status === 404 && attempt < retryDelays.length - 1) {
            // 404 means indexer hasn't caught up yet - retry
            console.log(`[book-content] Got 404, indexer may be slow - will retry...`);
            response = null;
            continue;
          } else if (response.status >= 500 && attempt < retryDelays.length - 1) {
            // 5xx server errors are transient - retry
            console.log(`[book-content] Got ${response.status} server error, will retry...`);
            response = null;
            continue;
          } else {
            console.error("[book-content] Chunked fetch failed:", response.status);
            // Fall through to regular storage as fallback
            break;
          }
        } catch (fetchError) {
          console.error(`[book-content] Fetch error on attempt ${attempt + 1}:`, fetchError);
          if (attempt < retryDelays.length - 1) {
            response = null;
            continue;
          }
        }
      }

      try {
        if (!response || !response.ok) {
          console.error("[book-content] All chunked fetch attempts failed");
          // Fall through to regular storage as fallback
        } else {
          const data = await response.json();
          console.log("[book-content] Chunked response keys:", Object.keys(data));

          // Chunked storage returns { chunks: ["0x...", "0x...", ...] }
          if (data.chunks && Array.isArray(data.chunks)) {
            console.log("[book-content] Found", data.chunks.length, "chunks");

            // Decompress and combine all chunks
            const decompressedContent = decompressChunkedStorageData(data.chunks);

            if (decompressedContent) {
              // The content was stored as base64, so decode it
              const finalContent = decodeBase64Content(decompressedContent);
              const contentAnalysis = analyzeContent(finalContent);

              console.log("[book-content] Chunked content analysis:", contentAnalysis.type);

              if (contentAnalysis.type === "pdf") {
                // Return URL to PDF endpoint for browser rendering
                if (contentAnalysis.pdfBuffer) {
                  const fileSizeKB = Math.round(contentAnalysis.pdfBuffer.length / 1024);
                  const pdfUrl = `/api/pdf-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}`;
                  return NextResponse.json({
                    success: true,
                    storageType: "pdf-data",
                    isPdf: true,
                    pdfDataUrl: pdfUrl,
                    sentences: [
                      "📄 PDF document loaded from onchain storage.",
                      `File size: ${fileSizeKB} KB`,
                    ],
                  });
                }
                return NextResponse.json({
                  success: true,
                  storageType: "pdf",
                  isPdf: true,
                  sentences: [
                    "📄 PDF document detected.",
                    'Tap "View on Net Protocol" to read the document.',
                  ],
                });
              }

              if (contentAnalysis.type === "text") {
                const sentences = parseContentToSentences(contentAnalysis.content);
                // For text files, provide both sentences (for basic reader) and mediaType/cdnUrl (for MultimediaViewer)
                const cdnUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/chunked-storage/file/${operatorAddress}/${contentKey}`;
                return NextResponse.json({
                  success: true,
                  storageType: "chunked-decompressed",
                  mediaType: "text",
                  cdnUrl,
                  sentences: sentences.length > 0 ? sentences : ["No readable text content found."],
                });
              }

              // Audio file
              if (contentAnalysis.type === "audio") {
                const cdnUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/chunked-storage/file/${operatorAddress}/${contentKey}`;
                return NextResponse.json({
                  success: true,
                  storageType: "audio",
                  isAudio: true,
                  mediaType: "audio",
                  cdnUrl,
                  sentences: ["🎵 Audio file detected.", "Opening audio player..."],
                });
              }

              // Video file
              if (contentAnalysis.type === "video") {
                const cdnUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/chunked-storage/file/${operatorAddress}/${contentKey}`;
                return NextResponse.json({
                  success: true,
                  storageType: "video",
                  isVideo: true,
                  mediaType: "video",
                  cdnUrl,
                  sentences: ["🎬 Video file detected.", "Opening video player..."],
                });
              }

              // Image file
              if (contentAnalysis.type === "image") {
                const cdnUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/chunked-storage/file/${operatorAddress}/${contentKey}`;
                return NextResponse.json({
                  success: true,
                  storageType: "image",
                  isImage: true,
                  mediaType: "image",
                  cdnUrl,
                  sentences: ["🖼️ Image file detected.", "Opening image viewer..."],
                });
              }

              if (contentAnalysis.type === "binary") {
                return NextResponse.json({
                  success: true,
                  storageType: "binary",
                  sentences: [
                    "This file is a binary document.",
                    'Click "Open" to view it directly.',
                  ],
                });
              }

              // Default: try as text
              const sentences = parseContentToSentences(finalContent);
              return NextResponse.json({
                success: true,
                storageType: "chunked-text",
                sentences: sentences.length > 0 ? sentences : ["No readable text content found."],
              });
            }
          }
        }
      } catch (chunkedError) {
        console.error("[book-content] Chunked storage fetch error:", chunkedError);
        // Fall through to regular storage
      }
    }

    // For regular storage, fetch from raw URL
    const rawUrl = getRawStorageUrl(BASE_CHAIN_ID, operatorAddress, contentKey);
    console.log("[book-content] Fetching from:", rawUrl);

    const response = await fetch(rawUrl, {
      headers: {
        "Accept": "application/json",
      },
    });

    if (!response.ok) {
      console.error("[book-content] Fetch failed:", response.status, response.statusText);
      return NextResponse.json(
        { error: `Failed to fetch from Net Protocol: ${response.status}` },
        { status: response.status }
      );
    }

    const data = await response.json();
    console.log("[book-content] Response keys:", Object.keys(data));

    // Regular or chunked storage
    if (data.data) {
      // Check if data is hex-encoded (starts with 0x), base64, or plain text
      const dataStr = data.data as string;
      const isHexEncoded = typeof dataStr === "string" && dataStr.startsWith("0x");
      let decoded: string;
      let dataFormat: string;

      if (isHexEncoded) {
        decoded = hexToString(dataStr);
        dataFormat = "hex";
      } else if (
        typeof dataStr === "string" &&
        /^[A-Za-z0-9+/=]+$/.test(dataStr) &&
        dataStr.length >= 4 &&
        dataStr.length % 4 === 0
      ) {
        // Looks like base64 — try to decode it.
        // Round-trip check prevents false positives where short plaintext
        // happens to consist only of base64-safe characters.
        try {
          const buffer = Buffer.from(dataStr, "base64");
          const candidate = buffer.toString("utf-8");
          if (Buffer.from(candidate, "utf-8").toString("base64") === dataStr) {
            decoded = candidate;
            dataFormat = "base64";
          } else {
            decoded = dataStr;
            dataFormat = "plain text (failed round-trip)";
          }
        } catch {
          decoded = dataStr;
          dataFormat = "plain text (base64 decode failed)";
        }
      } else {
        decoded = dataStr;
        dataFormat = "plain text";
      }
      console.log("[book-content] Data format:", dataFormat);
      console.log("[book-content] Decoded content length:", decoded.length);
      console.log("[book-content] Decoded preview (first 200 chars):", decoded.slice(0, 200));

      // Analyze the content to determine its type
      const contentAnalysis = analyzeContent(decoded);
      console.log("[book-content] Content analysis result:", contentAnalysis.type);

      if (contentAnalysis.type === "pdf") {
        // Return URL to PDF endpoint for browser rendering
        if (contentAnalysis.pdfBuffer) {
          const fileSizeKB = Math.round(contentAnalysis.pdfBuffer.length / 1024);
          const pdfUrl = `/api/pdf-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}`;
          return NextResponse.json({
            success: true,
            storageType: "pdf-data",
            isPdf: true,
            pdfDataUrl: pdfUrl,
            sentences: [
              "📄 PDF document loaded from onchain storage.",
              `File size: ${fileSizeKB} KB`,
            ],
          });
        }
        return NextResponse.json({
          success: true,
          storageType: "pdf",
          isPdf: true,
          sentences: [
            "📄 PDF document detected.",
            'Tap "View on Net Protocol" to read the document.',
          ],
        });
      }

      if (contentAnalysis.type === "text") {
        const sentences = parseContentToSentences(contentAnalysis.content);
        console.log("[book-content] Parsed", sentences.length, "sentences from text content");
        // For text files, provide both sentences (for basic reader) and mediaType/cdnUrl (for MultimediaViewer)
        const cdnUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${operatorAddress}/${contentKey}`;
        return NextResponse.json({
          success: true,
          storageType: "text",
          mediaType: "text",
          cdnUrl,
          sentences: sentences.length > 0 ? sentences : ["No readable text content found."],
        });
      }

      // Audio file
      if (contentAnalysis.type === "audio") {
        const cdnUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${operatorAddress}/${contentKey}`;
        return NextResponse.json({
          success: true,
          storageType: "audio",
          isAudio: true,
          mediaType: "audio",
          cdnUrl,
          sentences: ["🎵 Audio file detected.", "Opening audio player..."],
        });
      }

      // Video file
      if (contentAnalysis.type === "video") {
        const cdnUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${operatorAddress}/${contentKey}`;
        return NextResponse.json({
          success: true,
          storageType: "video",
          isVideo: true,
          mediaType: "video",
          cdnUrl,
          sentences: ["🎬 Video file detected.", "Opening video player..."],
        });
      }

      // Image file
      if (contentAnalysis.type === "image") {
        const cdnUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${operatorAddress}/${contentKey}`;
        return NextResponse.json({
          success: true,
          storageType: "image",
          isImage: true,
          mediaType: "image",
          cdnUrl,
          sentences: ["🖼️ Image file detected.", "Opening image viewer..."],
        });
      }

      if (contentAnalysis.type === "binary") {
        return NextResponse.json({
          success: true,
          storageType: "binary",
          sentences: [
            "This file is a binary document.",
            'Click "Open" to view it directly.',
            "File stored successfully on Net Protocol.",
          ],
        });
      }

      // Fallback - treat as text
      const sentences = parseContentToSentences(decoded);
      return NextResponse.json({
        success: true,
        storageType: "text",
        sentences: sentences.length > 0 ? sentences : ["No readable text content found."],
      });
    }

    if (data.text) {
      const sentences = parseContentToSentences(data.text);
      return NextResponse.json({
        success: true,
        storageType: "text",
        sentences: sentences.length > 0 ? sentences : ["No readable text content found."],
      });
    }

    return NextResponse.json({
      success: true,
      storageType: "unknown",
      sentences: ["No content found.", 'Try clicking "Open" to view the file directly.'],
    });
  } catch (error) {
    console.error("[book-content] Error:", error);

    // For XML storage, return a helpful message even on error
    if (storageType === "xml") {
      return NextResponse.json({
        success: true,
        storageType: "xml",
        sentences: [
          "📖 This book is stored onchain using XML chunked storage.",
          "The content is permanently stored on Base L2 blockchain.",
          "Full content reconstruction is coming soon!",
          'Click "Open" to try viewing the original upload.',
        ],
      });
    }

    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Failed to fetch content" },
      { status: 500 }
    );
  }
}

// Content analysis result
type ContentAnalysis =
  | { type: "text"; content: string }
  | { type: "pdf"; pdfBuffer?: Buffer }
  | { type: "audio" }
  | { type: "video" }
  | { type: "image" }
  | { type: "binary" }
  | { type: "unknown" };

// Analyze content to determine its type
function analyzeContent(raw: string): ContentAnalysis {
  console.log("[analyzeContent] Raw content first 200 chars:", raw.slice(0, 200));
  console.log("[analyzeContent] Raw content length:", raw.length);

  // Check for special binary markers from decodeBase64Content
  if (raw === "%PDF-BINARY") {
    return { type: "pdf" };
  }
  if (raw === "BINARY-CONTENT") {
    return { type: "binary" };
  }

  // Check if content directly starts with %PDF (raw PDF bytes as string)
  if (raw.startsWith("%PDF")) {
    console.log("[analyzeContent] Content starts with %PDF, converting to buffer...");
    // Convert the raw string to a buffer (it's binary data interpreted as string)
    const pdfBuffer = Buffer.from(raw, "binary");
    return { type: "pdf", pdfBuffer };
  }

  // Check for RTF format and extract text
  if (raw.startsWith("{\\rtf")) {
    console.log("[analyzeContent] Detected RTF format, extracting text...");
    const extractedText = extractTextFromRtf(raw);
    if (extractedText && extractedText.trim().length > 0) {
      console.log("[analyzeContent] Extracted RTF text:", extractedText);
      return { type: "text", content: extractedText };
    }
  }

  // FIRST: Check if it's already readable text (most common case for ebooks)
  // This should catch most text content including "A Christmas Carol"
  if (isReadableText(raw)) {
    console.log("[analyzeContent] Content is directly readable text");
    return { type: "text", content: raw };
  }

  // SECOND: Check text score even if isReadableText failed
  // More lenient check for text that might have some encoding issues
  const textScore = calculateTextScore(raw);
  console.log("[analyzeContent] Text score:", textScore);

  if (textScore > 0.6) {
    console.log("[analyzeContent] Content passes text score threshold");
    return { type: "text", content: raw };
  }

  // THIRD: Only check for base64/PDF if content is clearly NOT text
  // Must have NO spaces and NO common punctuation to be considered base64
  const hasNoSpaces = !raw.includes(" ");
  const hasNoPunctuation = !/[.,!?;:'"()[\]{}]/.test(raw);
  const looksLikeBase64 = hasNoSpaces && hasNoPunctuation && /^[A-Za-z0-9+/]+=*$/.test(raw);

  if (looksLikeBase64 && raw.length > 100) {
    console.log("[analyzeContent] Content looks like pure base64, attempting decode...");

    try {
      const decoded = Buffer.from(raw, "base64");

      // Check for PDF magic bytes: %PDF (0x25 0x50 0x44 0x46)
      if (decoded[0] === 0x25 && decoded[1] === 0x50 && decoded[2] === 0x44 && decoded[3] === 0x46) {
        console.log("[analyzeContent] Detected PDF magic bytes after base64 decode");
        return { type: "pdf", pdfBuffer: decoded };
      }

      // Check for audio magic bytes
      // MP3: ID3 tag (0x49 0x44 0x33) or MPEG frame sync (0xFF 0xFB, 0xFF 0xFA, 0xFF 0xF3, 0xFF 0xF2)
      if (decoded[0] === 0x49 && decoded[1] === 0x44 && decoded[2] === 0x33) {
        console.log("[analyzeContent] Detected MP3 (ID3) audio");
        return { type: "audio" };
      }
      if (decoded[0] === 0xFF && (decoded[1] === 0xFB || decoded[1] === 0xFA || decoded[1] === 0xF3 || decoded[1] === 0xF2)) {
        console.log("[analyzeContent] Detected MP3 (MPEG frame) audio");
        return { type: "audio" };
      }
      // WAV: RIFF + WAVE
      if (decoded[0] === 0x52 && decoded[1] === 0x49 && decoded[2] === 0x46 && decoded[3] === 0x46 &&
          decoded[8] === 0x57 && decoded[9] === 0x41 && decoded[10] === 0x56 && decoded[11] === 0x45) {
        console.log("[analyzeContent] Detected WAV audio");
        return { type: "audio" };
      }
      // OGG: OggS
      if (decoded[0] === 0x4F && decoded[1] === 0x67 && decoded[2] === 0x67 && decoded[3] === 0x53) {
        console.log("[analyzeContent] Detected OGG audio/video");
        return { type: "audio" };
      }
      // FLAC: fLaC
      if (decoded[0] === 0x66 && decoded[1] === 0x4C && decoded[2] === 0x61 && decoded[3] === 0x43) {
        console.log("[analyzeContent] Detected FLAC audio");
        return { type: "audio" };
      }
      // M4A/MP4/MOV: ftyp
      if (decoded[4] === 0x66 && decoded[5] === 0x74 && decoded[6] === 0x79 && decoded[7] === 0x70) {
        // Could be video (MP4/MOV) or audio (M4A) - check subtype
        const subtype = decoded.slice(8, 12).toString("ascii");
        if (subtype.includes("M4A") || subtype.includes("mp4a")) {
          console.log("[analyzeContent] Detected M4A audio");
          return { type: "audio" };
        }
        console.log("[analyzeContent] Detected MP4/MOV video");
        return { type: "video" };
      }
      // WebM: EBML (0x1A 0x45 0xDF 0xA3)
      if (decoded[0] === 0x1A && decoded[1] === 0x45 && decoded[2] === 0xDF && decoded[3] === 0xA3) {
        console.log("[analyzeContent] Detected WebM video");
        return { type: "video" };
      }
      // AVI: RIFF + AVI
      if (decoded[0] === 0x52 && decoded[1] === 0x49 && decoded[2] === 0x46 && decoded[3] === 0x46 &&
          decoded[8] === 0x41 && decoded[9] === 0x56 && decoded[10] === 0x49 && decoded[11] === 0x20) {
        console.log("[analyzeContent] Detected AVI video");
        return { type: "video" };
      }

      // Check for image magic bytes
      // PNG: 0x89 0x50 0x4E 0x47
      if (decoded[0] === 0x89 && decoded[1] === 0x50 && decoded[2] === 0x4E && decoded[3] === 0x47) {
        console.log("[analyzeContent] Detected PNG image");
        return { type: "image" };
      }
      // JPEG: 0xFF 0xD8 0xFF
      if (decoded[0] === 0xFF && decoded[1] === 0xD8 && decoded[2] === 0xFF) {
        console.log("[analyzeContent] Detected JPEG image");
        return { type: "image" };
      }
      // GIF: GIF87a or GIF89a
      if (decoded[0] === 0x47 && decoded[1] === 0x49 && decoded[2] === 0x46 && decoded[3] === 0x38) {
        console.log("[analyzeContent] Detected GIF image");
        return { type: "image" };
      }
      // WebP: RIFF + WEBP
      if (decoded[0] === 0x52 && decoded[1] === 0x49 && decoded[2] === 0x46 && decoded[3] === 0x46 &&
          decoded[8] === 0x57 && decoded[9] === 0x45 && decoded[10] === 0x42 && decoded[11] === 0x50) {
        console.log("[analyzeContent] Detected WebP image");
        return { type: "image" };
      }

      // Try to interpret as UTF-8 text
      const decodedText = decoded.toString("utf-8");

      // Check if decoded result is readable text
      if (isReadableText(decodedText)) {
        console.log("[analyzeContent] Base64 decoded to readable text");
        return { type: "text", content: decodedText };
      }

      // It's binary but not a recognized format
      console.log("[analyzeContent] Base64 decoded to binary (unrecognized format)");
      return { type: "binary" };
    } catch (e) {
      console.log("[analyzeContent] Base64 decode failed:", e);
    }
  }

  // FOURTH: Default to treating as text if we got this far
  // Better to show potentially garbled text than wrongly say "PDF"
  console.log("[analyzeContent] Defaulting to text treatment");
  return { type: "text", content: raw };
}

// Check if content is human-readable text
function isReadableText(str: string): boolean {
  if (!str || str.length < 10) return false;

  // Check for obvious text indicators
  const hasWords = /\b[a-zA-Z]{2,}\b/.test(str); // Has actual words (2+ letters)
  const hasSpaces = str.includes(" ");
  const hasSentenceEndings = /[.!?]/.test(str);

  // Check for binary indicators
  const hasNullBytes = str.includes("\u0000");
  const startsWithPDF = str.startsWith("%PDF");

  // Count printable vs non-printable characters
  const printableCount = (str.match(/[\x20-\x7E\n\r\t]/g) || []).length;
  const printableRatio = printableCount / str.length;

  console.log("[isReadableText] hasWords:", hasWords, "hasSpaces:", hasSpaces,
    "hasSentenceEndings:", hasSentenceEndings, "printableRatio:", printableRatio.toFixed(2),
    "hasNullBytes:", hasNullBytes, "startsWithPDF:", startsWithPDF);

  if (hasNullBytes || startsWithPDF) {
    return false;
  }

  // High printable ratio + text characteristics = readable text
  return printableRatio > 0.85 && hasWords && (hasSpaces || hasSentenceEndings);
}

// Calculate a "text-likeness" score
function calculateTextScore(str: string): number {
  if (!str || str.length < 10) return 0;

  const printableCount = (str.match(/[\x20-\x7E\n\r\t]/g) || []).length;
  const wordCount = (str.match(/\b[a-zA-Z]{2,}\b/g) || []).length;
  const spaceCount = (str.match(/ /g) || []).length;

  const printableRatio = printableCount / str.length;
  const wordDensity = wordCount / (str.length / 100); // words per 100 chars
  const spaceDensity = spaceCount / (str.length / 100); // spaces per 100 chars

  // Weight the factors
  return (printableRatio * 0.5) + (Math.min(wordDensity / 20, 0.25)) + (Math.min(spaceDensity / 15, 0.25));
}

// Helper: Apply encoding fixes for curly quotes and special characters
function _applyEncodingFixes(text: string): string {
  return text
    .replace(/Õ/g, "'")
    .replace(/Ô/g, "'")
    .replace(/Ò/g, '"')
    .replace(/Ó/g, '"')
    .replace(/Ð/g, "–")
    .replace(/Ñ/g, "—")
    .replace(/É/g, "...")
    .replace(/\u0092/g, "'")
    .replace(/\u0093/g, '"')
    .replace(/\u0094/g, '"')
    .replace(/\u0091/g, "'")
    .replace(/\u0096/g, "–")
    .replace(/\u0097/g, "—");
}

// Helper: Extract plain text from RTF content
function extractTextFromRtf(rtf: string): string {
  // Simple RTF parser - extracts visible text from RTF markup

  let result = "";
  let i = 0;
  let inGroup = 0;
  let skipGroup = false;

  // Skip groups that don't contain visible text
  const skipGroupNames = ["fonttbl", "colortbl", "stylesheet", "info", "pict", "object", "expandedcolortbl"];

  while (i < rtf.length) {
    const char = rtf[i];

    if (char === "{") {
      inGroup++;
      // Check if this is a group we should skip
      const nextPart = rtf.slice(i + 1, i + 30);
      if (nextPart.startsWith("\\*\\")) {
        skipGroup = true;
      }
      for (const name of skipGroupNames) {
        if (nextPart.startsWith(`\\${name}`)) {
          skipGroup = true;
          break;
        }
      }
      i++;
      continue;
    }

    if (char === "}") {
      inGroup--;
      if (inGroup <= 1) skipGroup = false;
      i++;
      continue;
    }

    if (skipGroup) {
      i++;
      continue;
    }

    if (char === "\\") {
      // Control word or symbol
      i++;
      if (i >= rtf.length) break;

      const nextChar = rtf[i];

      // Special characters
      if (nextChar === "\\") {
        result += "\\";
        i++;
        continue;
      }
      if (nextChar === "{") {
        result += "{";
        i++;
        continue;
      }
      if (nextChar === "}") {
        result += "}";
        i++;
        continue;
      }
      if (nextChar === "'") {
        // Hex character code
        const hexCode = rtf.slice(i + 1, i + 3);
        const charCode = parseInt(hexCode, 16);
        if (!isNaN(charCode)) {
          result += String.fromCharCode(charCode);
        }
        i += 3;
        continue;
      }
      if (nextChar === "\n" || nextChar === "\r") {
        // Line break in RTF source, ignore
        i++;
        continue;
      }

      // Control word - read until space or non-alpha
      let controlWord = "";
      while (i < rtf.length && /[a-zA-Z]/.test(rtf[i])) {
        controlWord += rtf[i];
        i++;
      }

      // Skip optional numeric parameter
      while (i < rtf.length && /[-0-9]/.test(rtf[i])) {
        i++;
      }

      // Handle specific control words
      if (controlWord === "par" || controlWord === "line") {
        result += "\n";
      } else if (controlWord === "tab") {
        result += "\t";
      } else if (controlWord === "emdash") {
        result += "—";
      } else if (controlWord === "endash") {
        result += "–";
      } else if (controlWord === "ldblquote") {
        result += "\u201C"; // "
      } else if (controlWord === "rdblquote") {
        result += "\u201D"; // "
      } else if (controlWord === "lquote") {
        result += "\u2018"; // '
      } else if (controlWord === "rquote") {
        result += "\u2019"; // '
      } else if (controlWord === "bullet") {
        result += "•";
      }

      // Skip the space delimiter if present
      if (i < rtf.length && rtf[i] === " ") {
        i++;
      }
      continue;
    }

    // Regular character
    if (char !== "\r" && char !== "\n") {
      result += char;
    }
    i++;
  }

  // Clean up the result
  return result
    .replace(/\s+/g, " ") // Normalize whitespace
    .replace(/\n\s*\n/g, "\n\n") // Normalize paragraph breaks
    .trim();
}

// Helper: Decompress chunked storage data (array of hex-encoded compressed chunks)
function decompressChunkedStorageData(chunks: string[]): string | null {
  try {
    console.log("[decompressChunkedStorageData] Processing", chunks.length, "chunks");

    // Each chunk is hex-encoded compressed data
    // We need to: 1) decode hex to bytes, 2) decompress each chunk, 3) combine

    const decompressedParts: string[] = [];

    for (let i = 0; i < chunks.length; i++) {
      const hexChunk = chunks[i];
      const cleanHex = hexChunk.startsWith("0x") ? hexChunk.slice(2) : hexChunk;

      // Convert hex to bytes
      const bytes = new Uint8Array(cleanHex.length / 2);
      for (let j = 0; j < cleanHex.length; j += 2) {
        bytes[j / 2] = parseInt(cleanHex.slice(j, j + 2), 16);
      }

      console.log(`[decompressChunkedStorageData] Chunk ${i}: ${bytes.length} bytes, first bytes: ${bytes.slice(0, 4).join(",")}`);

      // Try to decompress the chunk
      let decompressed: string | null = null;

      // Check for zlib magic bytes (0x78 0x9c, 0x78 0x01, 0x78 0xda)
      if (bytes[0] === 0x78 && (bytes[1] === 0x9c || bytes[1] === 0x01 || bytes[1] === 0xda)) {
        try {
          decompressed = pako.inflate(bytes, { to: "string" });
          console.log(`[decompressChunkedStorageData] Chunk ${i}: zlib decompressed to ${decompressed?.length} chars`);
        } catch (e) {
          console.log(`[decompressChunkedStorageData] Chunk ${i}: zlib decompress failed:`, e);
        }
      }

      // Try raw inflate if zlib didn't work
      if (!decompressed) {
        try {
          decompressed = pako.inflateRaw(bytes, { to: "string" });
          console.log(`[decompressChunkedStorageData] Chunk ${i}: raw inflate to ${decompressed?.length} chars`);
        } catch {
          console.log(`[decompressChunkedStorageData] Chunk ${i}: raw inflate failed`);
        }
      }

      // If decompression failed, try as plain text
      if (!decompressed) {
        try {
          decompressed = new TextDecoder("utf-8", { fatal: false }).decode(bytes);
          console.log(`[decompressChunkedStorageData] Chunk ${i}: decoded as plain text, ${decompressed.length} chars`);
        } catch {
          console.log(`[decompressChunkedStorageData] Chunk ${i}: plain decode failed`);
          continue; // Skip this chunk
        }
      }

      if (decompressed) {
        decompressedParts.push(decompressed);
      }
    }

    if (decompressedParts.length === 0) {
      console.log("[decompressChunkedStorageData] No chunks could be decompressed");
      return null;
    }

    const combined = decompressedParts.join("");
    console.log("[decompressChunkedStorageData] Combined length:", combined.length);
    return combined;
  } catch (error) {
    console.error("[decompressChunkedStorageData] Error:", error);
    return null;
  }
}

// Helper: Decode base64 content to original data (text or binary indicator)
function decodeBase64Content(base64Content: string): string {
  // Check if it looks like base64 (no spaces, mostly alphanumeric + /+=)
  const trimmed = base64Content.trim();
  const looksLikeBase64 = /^[A-Za-z0-9+/]+=*$/.test(trimmed) && !trimmed.includes(" ");

  if (!looksLikeBase64) {
    // Not base64, return as-is (might already be plain text)
    console.log("[decodeBase64Content] Content doesn't look like base64, returning as-is");
    return base64Content;
  }

  try {
    // Decode base64 to Buffer, then to UTF-8 string
    const decoded = Buffer.from(trimmed, "base64");

    // Check if it's text or binary
    // Text files should have mostly printable characters
    const printableCount = decoded.filter(b =>
      (b >= 0x20 && b <= 0x7E) || b === 0x0A || b === 0x0D || b === 0x09
    ).length;
    const printableRatio = printableCount / decoded.length;

    console.log("[decodeBase64Content] Decoded", decoded.length, "bytes, printable ratio:", printableRatio.toFixed(2));

    if (printableRatio > 0.8) {
      // Looks like text
      const text = decoded.toString("utf-8");
      console.log("[decodeBase64Content] Decoded as text:", text.slice(0, 100));
      return text;
    } else {
      // Binary content - check for PDF
      if (decoded[0] === 0x25 && decoded[1] === 0x50 && decoded[2] === 0x44 && decoded[3] === 0x46) {
        return "%PDF-BINARY";
      }
      return "BINARY-CONTENT";
    }
  } catch (e) {
    console.log("[decodeBase64Content] Base64 decode failed, returning as-is:", e);
    return base64Content;
  }
}

// Helper: Decode hex string to UTF-8 text (with decompression fallback)
function hexToString(hex: string): string {
  const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
  const bytes = new Uint8Array(cleanHex.length / 2);
  for (let i = 0; i < cleanHex.length; i += 2) {
    bytes[i / 2] = parseInt(cleanHex.slice(i, i + 2), 16);
  }

  // First, try to decompress - Net Protocol often uses zlib/deflate compression
  try {
    // Check for zlib magic bytes (0x78 0x9c or 0x78 0x01 or 0x78 0xda)
    if (bytes[0] === 0x78 && (bytes[1] === 0x9c || bytes[1] === 0x01 || bytes[1] === 0xda)) {
      console.log("[hexToString] Detected zlib compressed data, decompressing...");
      const decompressed = pako.inflate(bytes, { to: "string" });
      if (decompressed && typeof decompressed === "string") {
        console.log("[hexToString] Zlib decompression successful, length:", decompressed.length);
        return decompressed;
      }
    }

    // Try raw inflate (deflate without zlib header)
    try {
      const decompressed = pako.inflateRaw(bytes, { to: "string" });
      if (decompressed && typeof decompressed === "string" && decompressed.length > 0) {
        // Check if result looks like text
        const printableRatio = (decompressed.match(/[\x20-\x7E\n\r\t]/g) || []).length / decompressed.length;
        if (printableRatio > 0.8) {
          console.log("[hexToString] Raw inflate successful, printable ratio:", printableRatio.toFixed(2));
          return decompressed;
        }
      }
    } catch {
      // Not raw deflate, continue
    }
  } catch (e) {
    console.log("[hexToString] Decompression not applicable:", e);
  }

  // Try standard UTF-8 decode
  const decoded = new TextDecoder("utf-8", { fatal: false }).decode(bytes);

  // Check if the result looks like garbage (lots of replacement characters or non-printable)
  const replacementCount = (decoded.match(/\ufffd/g) || []).length;
  const nonPrintableCount = decoded.length - (decoded.match(/[\x20-\x7E\n\r\t]/g) || []).length;
  const garbageRatio = (replacementCount + nonPrintableCount) / decoded.length;

  if (garbageRatio > 0.3) {
    console.log("[hexToString] High garbage ratio:", garbageRatio.toFixed(2), "- content may be compressed or binary");

    // Try one more decompression attempt with pako.inflate (auto-detect)
    try {
      const decompressed = pako.inflate(bytes, { to: "string" });
      if (decompressed && typeof decompressed === "string") {
        const decompressedPrintableRatio = (decompressed.match(/[\x20-\x7E\n\r\t]/g) || []).length / decompressed.length;
        if (decompressedPrintableRatio > 0.7) {
          console.log("[hexToString] Fallback inflate successful!");
          return decompressed;
        }
      }
    } catch {
      // Final fallback - return the raw decode
    }
  }

  return decoded;
}

// Helper: Parse text content into sentences
function parseContentToSentences(text: string): string[] {
  const cleaned = text
    .replace(/\r\n/g, "\n")
    .replace(/\n{3,}/g, "\n\n")
    .trim();

  const rawSentences = cleaned.split(/(?<=[.!?])\s+/);

  return rawSentences
    .map((s) => s.trim())
    .filter((s) => s.length > 0)
    .slice(0, 500); // Limit for performance
}

// Manual reconstruction for XML chunks when SDK fails
async function reconstructXmlChunksManually(
  contentKey: string,
  operatorAddress: string
): Promise<string | null> {
  try {
    console.log("[book-content] Manual reconstruction starting...");

    // Step 1: Fetch the XML metadata from the content key
    const metadataUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${operatorAddress}/${contentKey}`;
    console.log("[book-content] Fetching metadata from:", metadataUrl);

    const metadataResponse = await fetch(metadataUrl);
    if (!metadataResponse.ok) {
      console.error("[book-content] Failed to fetch metadata:", metadataResponse.status);
      return null;
    }

    const metadataJson = await metadataResponse.json();
    if (!metadataJson.data) {
      console.error("[book-content] No data in metadata response");
      return null;
    }

    // Decode the metadata hex to get XML
    const metadataText = hexToString(metadataJson.data);
    console.log("[book-content] Metadata text preview:", metadataText.slice(0, 200));

    // Step 2: Parse XML to extract chunk references
    // Format: <net k="chunkKey" v="0.0.1" i="0" o="0xoperator" />
    const references = parseNetReferences(metadataText);
    console.log("[book-content] Found", references.length, "chunk references");

    if (references.length === 0) {
      // Maybe it's not XML, try direct decode
      return metadataText;
    }

    // Step 3: Fetch each chunk and reassemble
    const allChunks: string[] = [];
    const storageClient = createStorageClient(BASE_CHAIN_ID);

    for (const ref of references) {
      const chunkOperator = ref.operator || operatorAddress;
      console.log("[book-content] Fetching chunk:", ref.hash, "from operator:", chunkOperator);

      try {
        // Try reading via SDK's readChunkedStorage
        const chunkData = await storageClient.readChunkedStorage({
          key: ref.hash,
          operator: chunkOperator,
          keyFormat: "bytes32",
          index: ref.index,
        });

        if (chunkData.data) {
          allChunks.push(chunkData.data);
        }
      } catch (chunkError) {
        console.error("[book-content] Failed to fetch chunk:", ref.hash, chunkError);

        // Fallback: Try raw fetch for chunked storage
        try {
          const chunkUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/chunked-storage/raw/${chunkOperator}/${ref.hash}`;
          const chunkResponse = await fetch(chunkUrl);

          if (chunkResponse.ok) {
            const chunkJson = await chunkResponse.json();
            if (chunkJson.chunks && Array.isArray(chunkJson.chunks)) {
              // Assemble and decompress chunks using SDK
              const assembled = assembleChunks(chunkJson.chunks);
              if (assembled) {
                allChunks.push(assembled);
              }
            }
          }
        } catch (fallbackError) {
          console.error("[book-content] Fallback chunk fetch also failed:", fallbackError);
        }
      }
    }

    if (allChunks.length === 0) {
      console.error("[book-content] No chunks were successfully fetched");
      return null;
    }

    // Step 4: Combine all chunks
    const fullContent = allChunks.join("");
    console.log("[book-content] Reconstructed content length:", fullContent.length);

    // Decode from base64 if the content was stored as base64
    if (fullContent.match(/^[A-Za-z0-9+/=]+$/) && fullContent.length > 100) {
      try {
        const decoded = Buffer.from(fullContent, "base64").toString("utf-8");
        // Check if decoded looks like text
        if (decoded && !decoded.includes("\u0000")) {
          return decoded;
        }
      } catch {
        // Not base64, return as-is
      }
    }

    return fullContent;
  } catch (error) {
    console.error("[book-content] Manual reconstruction error:", error);
    return null;
  }
}
src/app/api/book-file/route.ts
import { NextRequest, NextResponse } from "next/server";
import { BASE_CHAIN_ID, getRawStorageUrl } from "@/lib/net-protocol";
import { parseNetReferences } from "@net-protocol/storage";

// Disable caching for this route
export const dynamic = "force-dynamic";

// GET - Serve raw book file content (PDF, etc.) for direct viewing
// Usage: /api/book-file?contentKey=0x...&operator=0x...&storageType=xml
export async function GET(request: NextRequest) {
  console.log("[book-file] === ROUTE HIT ===", new Date().toISOString());
  const contentKey = request.nextUrl.searchParams.get("contentKey");
  const operatorAddress = request.nextUrl.searchParams.get("operator");
  const storageType = request.nextUrl.searchParams.get("storageType") || "regular";
  const filename = request.nextUrl.searchParams.get("filename") || "document.pdf";

  console.log("[book-file] Params - storageType:", storageType, "contentKey:", contentKey?.slice(0,20), "operator:", operatorAddress?.slice(0,10));
  const forceDownload = request.nextUrl.searchParams.get("download") === "true";

  if (!contentKey || !operatorAddress) {
    return NextResponse.json(
      { error: "contentKey and operator required" },
      { status: 400 }
    );
  }

  try {
    let rawData: Buffer;

    if (storageType === "xml") {
      // XML storage - manually reconstruct from chunks
      console.log("[book-file] Reconstructing XML chunks manually...");

      // Step 1: Fetch the XML metadata
      const metadataUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${operatorAddress}/${contentKey}`;
      console.log("[book-file] Fetching metadata from:", metadataUrl);

      const metadataResponse = await fetch(metadataUrl, { redirect: "follow" });
      if (!metadataResponse.ok) {
        return NextResponse.json({ error: "Failed to fetch metadata" }, { status: 404 });
      }

      const metadataJson = await metadataResponse.json();
      if (!metadataJson.data) {
        return NextResponse.json({ error: "No data in metadata" }, { status: 404 });
      }

      const dataStr = metadataJson.data as string;
      console.log("[book-file] ====== NEW REQUEST ======");
      console.log("[book-file] Data length:", dataStr.length);
      console.log("[book-file] Data starts with:", dataStr.slice(0, 100));

      // Check if this is plain XML (starts with <net) or hex data (starts with 0x)
      const isPlainXml = dataStr.startsWith("<net");
      const isHexData = dataStr.startsWith("0x");
      console.log("[book-file] Data format - isPlainXml:", isPlainXml, "isHexData:", isHexData);

      if (isPlainXml) {
        // Plain XML chunk references - need to fetch and assemble chunks
        const references = parseNetReferences(dataStr);

        if (references.length === 0) {
          return NextResponse.json({ error: "No chunk references found in XML", debug: "isPlainXml branch, 0 refs" }, { status: 404 });
        }

        // Fetch each chunk and collect the binary data
        const chunkBuffers: Buffer[] = [];

        for (const ref of references) {
          // IMPORTANT: Always use the passed operatorAddress, NOT ref.operator from XML
          // For relay uploads, the XML metadata has the user's address in the 'o' attribute,
          // but the relay's backend wallet actually writes the chunks to chain.
          // The operatorAddress parameter is the correct backend wallet.
          const chunkOperator = operatorAddress;

          try {
            // Fetch chunk from regular storage (NOT chunked-storage)
            const chunkUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${chunkOperator}/${ref.hash}`;
            const chunkResponse = await fetch(chunkUrl, { redirect: "follow" });

            if (chunkResponse.ok) {
              const chunkJson = await chunkResponse.json();
              if (chunkJson.data) {
                const dataStr = chunkJson.data as string;
                // Check if hex (starts with 0x) or base64
                let chunkBuffer: Buffer;
                if (dataStr.startsWith("0x")) {
                  chunkBuffer = hexToBuffer(dataStr);
                } else {
                  // XML chunk data is typically base64 encoded
                  chunkBuffer = Buffer.from(dataStr, "base64");
                }
                chunkBuffers.push(chunkBuffer);
              }
            }
          } catch {
            // Continue to next chunk on error
          }
        }

        if (chunkBuffers.length === 0) {
          return NextResponse.json({ error: "Failed to fetch any chunks" }, { status: 500 });
        }

        // Combine all chunk buffers into one
        rawData = Buffer.concat(chunkBuffers);
      } else if (isHexData) {
        // Hex-encoded data - decode to binary
        const rawHexBuffer = hexToBuffer(dataStr);
        console.log("[book-file] Raw hex decoded to buffer, size:", rawHexBuffer.length);
        console.log("[book-file] First 10 bytes:", Array.from(rawHexBuffer.slice(0, 10)));

        // Check if this is directly binary audio/video/image data (not XML)
        const firstBytes = rawHexBuffer.slice(0, 12);
        const isMp3 = (firstBytes[0] === 0x49 && firstBytes[1] === 0x44 && firstBytes[2] === 0x33) || // ID3
                      (firstBytes[0] === 0xFF && (firstBytes[1] === 0xFB || firstBytes[1] === 0xFA || firstBytes[1] === 0xF3 || firstBytes[1] === 0xF2 || firstBytes[1] === 0xE3));
        const isWav = firstBytes[0] === 0x52 && firstBytes[1] === 0x49 && firstBytes[2] === 0x46 && firstBytes[3] === 0x46 &&
                      rawHexBuffer.length > 11 && rawHexBuffer[8] === 0x57 && rawHexBuffer[9] === 0x41 && rawHexBuffer[10] === 0x56 && rawHexBuffer[11] === 0x45;
        const isOgg = firstBytes[0] === 0x4F && firstBytes[1] === 0x67 && firstBytes[2] === 0x67 && firstBytes[3] === 0x53;
        const isFlac = firstBytes[0] === 0x66 && firstBytes[1] === 0x4C && firstBytes[2] === 0x61 && firstBytes[3] === 0x43;
        const isFtyp = rawHexBuffer.length > 11 && rawHexBuffer[4] === 0x66 && rawHexBuffer[5] === 0x74 && rawHexBuffer[6] === 0x79 && rawHexBuffer[7] === 0x70;
        const isWebm = firstBytes[0] === 0x1A && firstBytes[1] === 0x45 && firstBytes[2] === 0xDF && firstBytes[3] === 0xA3;
        const isPng = firstBytes[0] === 0x89 && firstBytes[1] === 0x50 && firstBytes[2] === 0x4E && firstBytes[3] === 0x47;
        const isJpeg = firstBytes[0] === 0xFF && firstBytes[1] === 0xD8 && firstBytes[2] === 0xFF;
        const isGif = firstBytes[0] === 0x47 && firstBytes[1] === 0x49 && firstBytes[2] === 0x46 && firstBytes[3] === 0x38;
        const isPdf = firstBytes[0] === 0x25 && firstBytes[1] === 0x50 && firstBytes[2] === 0x44 && firstBytes[3] === 0x46;

        if (isMp3 || isWav || isOgg || isFlac || isFtyp || isWebm || isPng || isJpeg || isGif || isPdf) {
          console.log("[book-file] Direct binary content detected in hex data");
          rawData = rawHexBuffer;
        } else {
          // Might be hex-encoded XML or text
          const metadataText = hexToString(dataStr);
          console.log("[book-file] Decoded hex to text:", metadataText.slice(0, 200));

          const references = parseNetReferences(metadataText);
          console.log("[book-file] Found", references.length, "chunk references in decoded text");

          if (references.length === 0) {
            // Not XML chunked - but the hex-decoded data might be base64 encoded text
            // This is the common case for text uploads: text -> base64 -> hex
            const hexDecodedStr = rawHexBuffer.toString("utf-8");
            const looksLikeBase64 = /^[A-Za-z0-9+/]+=*$/.test(hexDecodedStr) && !hexDecodedStr.includes(" ");

            if (looksLikeBase64 && hexDecodedStr.length > 4) {
              // Double-encoded: hex(base64(content)) - need to decode base64
              console.log("[book-file] XML hex-decoded content looks like base64, decoding...");
              try {
                rawData = Buffer.from(hexDecodedStr, "base64");
                console.log("[book-file] Base64 decoded, final length:", rawData.length);
                console.log("[book-file] Final content preview:", rawData.slice(0, 100).toString("utf-8"));
              } catch (e) {
                console.log("[book-file] Base64 decode failed, using hex-decoded directly:", e);
                rawData = rawHexBuffer;
              }
            } else {
              // Just hex encoded, not base64
              rawData = rawHexBuffer;
            }
          } else {
            // XML chunk references found - need to fetch and assemble
            const chunkBuffers: Buffer[] = [];

            for (const ref of references) {
              // IMPORTANT: Always use the passed operatorAddress, NOT ref.operator from XML
              // For relay uploads, the XML metadata has the user's address in the 'o' attribute,
              // but the relay's backend wallet actually writes the chunks to chain.
              const chunkOperator = operatorAddress;
              try {
                // Fetch from regular storage (NOT chunked-storage)
                const chunkUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${chunkOperator}/${ref.hash}`;
                const chunkResponse = await fetch(chunkUrl, { redirect: "follow" });

                if (chunkResponse.ok) {
                  const chunkJson = await chunkResponse.json();
                  if (chunkJson.data) {
                    const dataStr = chunkJson.data as string;
                    // Check if hex (starts with 0x) or base64
                    let chunkBuffer: Buffer;
                    if (dataStr.startsWith("0x")) {
                      chunkBuffer = hexToBuffer(dataStr);
                    } else {
                      // XML chunk data is typically base64 encoded
                      chunkBuffer = Buffer.from(dataStr, "base64");
                    }
                    chunkBuffers.push(chunkBuffer);
                  }
                }
              } catch {
                // Continue to next chunk on error
              }
            }

            if (chunkBuffers.length > 0) {
              rawData = Buffer.concat(chunkBuffers);
            } else {
              rawData = rawHexBuffer;
            }
          }
        }
      } else {
        // Unknown format - try to use as-is
        console.log("[book-file] !!! Unknown data format, using as UTF-8 !!!");
        console.log("[book-file] dataStr first chars codes:", [...dataStr.slice(0, 10)].map(c => c.charCodeAt(0)));
        rawData = Buffer.from(dataStr, "utf-8");
      }
    } else {
      // Regular/chunked storage - fetch from raw URL
      const rawUrl = getRawStorageUrl(BASE_CHAIN_ID, operatorAddress, contentKey);
      console.log("[book-file] Fetching from:", rawUrl);

      const response = await fetch(rawUrl);
      if (!response.ok) {
        return NextResponse.json(
          { error: `Failed to fetch: ${response.status}` },
          { status: response.status }
        );
      }

      const data = await response.json();
      if (!data.data) {
        return NextResponse.json({ error: "No data in response" }, { status: 404 });
      }

      // Data can be either hex (starts with 0x) or base64 encoded
      const dataStr = data.data as string;
      console.log("[book-file] Regular storage data format check - starts with 0x:", dataStr.startsWith("0x"), "length:", dataStr.length);
      console.log("[book-file] Data preview:", dataStr.slice(0, 100));

      if (dataStr.startsWith("0x")) {
        // Hex encoded - decode from hex
        const hexDecoded = hexToBuffer(dataStr);
        console.log("[book-file] Decoded hex bytes, length:", hexDecoded.length);

        // The hex-decoded data might itself be base64 encoded (common for text files)
        // Check if the decoded bytes look like a base64 string
        const hexDecodedStr = hexDecoded.toString("utf-8");
        const looksLikeBase64 = /^[A-Za-z0-9+/]+=*$/.test(hexDecodedStr) && !hexDecodedStr.includes(" ");

        if (looksLikeBase64 && hexDecodedStr.length > 10) {
          // Double-encoded: hex(base64(content)) - need to decode base64
          console.log("[book-file] Hex-decoded content looks like base64, decoding...");
          try {
            rawData = Buffer.from(hexDecodedStr, "base64");
            console.log("[book-file] Base64 decoded from hex, final length:", rawData.length);
            console.log("[book-file] Final content preview:", rawData.slice(0, 100).toString("utf-8"));
          } catch (e) {
            console.log("[book-file] Base64 decode of hex content failed, using hex-decoded directly:", e);
            rawData = hexDecoded;
          }
        } else {
          // Just hex encoded, not base64
          rawData = hexDecoded;
        }
      } else if (/^[A-Za-z0-9+/=]+$/.test(dataStr) && dataStr.length > 20) {
        // Looks like base64 - try to decode
        try {
          rawData = Buffer.from(dataStr, "base64");
          console.log("[book-file] Decoded base64 bytes, length:", rawData.length);

          // Verify the decoded content looks valid - if it's mostly printable ASCII, it's likely text
          const firstChunk = rawData.slice(0, 100).toString("utf-8");
          // Check if content is printable ASCII (space through tilde, plus common whitespace)
          // Using character code checks instead of regex with control chars to satisfy eslint
          const isPrintable = firstChunk.split("").every((char) => {
            const code = char.charCodeAt(0);
            return (code >= 0x20 && code <= 0x7e) || code === 0x0d || code === 0x0a || code === 0x09;
          });
          console.log("[book-file] Base64 decoded content preview:", firstChunk.slice(0, 50), "isPrintable:", isPrintable);
        } catch (e) {
          console.log("[book-file] Base64 decode failed, treating as plain text:", e);
          rawData = Buffer.from(dataStr, "utf-8");
        }
      } else {
        // Plain text - use directly as UTF-8
        console.log("[book-file] Treating as plain text");
        rawData = Buffer.from(dataStr, "utf-8");
      }

      console.log("[book-file] First bytes (hex):", rawData.slice(0, 20).toString("hex"));
      console.log("[book-file] First bytes (utf8):", rawData.slice(0, 50).toString("utf-8"));

      // Check if content is text (for .txt files)
      const ext = filename.split(".").pop()?.toLowerCase();
      if (ext === "txt") {
        // Text files might need UTF-8 decoding
        const textContent = rawData.toString("utf-8");
        console.log("[book-file] Text content full preview:", textContent.slice(0, 200));
      }
    }

    // Determine content type from filename extension FIRST
    const ext = filename.split(".").pop()?.toLowerCase();
    let contentType = "application/octet-stream";

    // For .txt files, ALWAYS serve as text/plain regardless of content
    if (ext === "txt") {
      contentType = "text/plain; charset=utf-8";
      console.log("[book-file] .txt extension detected, forcing text/plain");
    } else {
      switch (ext) {
        case "pdf":
          contentType = "application/pdf";
          break;
        case "epub":
          contentType = "application/epub+zip";
          break;
        case "mobi":
          contentType = "application/x-mobipocket-ebook";
          break;
        // Audio types
        case "mp3":
          contentType = "audio/mpeg";
          break;
        case "wav":
          contentType = "audio/wav";
          break;
        case "ogg":
          contentType = "audio/ogg";
          break;
        case "flac":
          contentType = "audio/flac";
          break;
        case "m4a":
        case "aac":
          contentType = "audio/mp4";
          break;
        // Video types
        case "mp4":
        case "m4v":
          contentType = "video/mp4";
          break;
        case "webm":
          contentType = "video/webm";
          break;
        case "avi":
          contentType = "video/x-msvideo";
          break;
        case "mov":
          contentType = "video/quicktime";
          break;
        // Image types
        case "png":
          contentType = "image/png";
          break;
        case "jpg":
        case "jpeg":
          contentType = "image/jpeg";
          break;
        case "gif":
          contentType = "image/gif";
          break;
        case "webp":
          contentType = "image/webp";
          break;
      }

      // Check magic bytes for content type detection (when extension doesn't match)
      const firstBytes = rawData.slice(0, 12);
      const firstBytesStr = firstBytes.toString("utf-8");
      const firstBytesHex = firstBytes.toString("hex");

      // PDF magic: %PDF
      if (firstBytesStr.startsWith("%PDF")) {
        contentType = "application/pdf";
      }
      // MP3 magic: ID3 or 0xFF 0xFB (sync byte)
      else if (firstBytesStr.startsWith("ID3") || firstBytesHex.startsWith("fff") || firstBytesHex.startsWith("ffe")) {
        contentType = "audio/mpeg";
      }
      // WAV magic: RIFF....WAVE
      else if (firstBytesStr.startsWith("RIFF") && rawData.slice(8, 12).toString("utf-8") === "WAVE") {
        contentType = "audio/wav";
      }
      // OGG magic: OggS
      else if (firstBytesStr.startsWith("OggS")) {
        contentType = "audio/ogg";
      }
      // FLAC magic: fLaC
      else if (firstBytesStr.startsWith("fLaC")) {
        contentType = "audio/flac";
      }
      // MP4/M4A magic: ftyp (usually at byte 4)
      else if (rawData.slice(4, 8).toString("utf-8") === "ftyp") {
        // Check if audio or video
        const ftyp = rawData.slice(8, 12).toString("utf-8");
        if (ftyp.startsWith("M4A") || ftyp.startsWith("mp4")) {
          contentType = "audio/mp4";
        } else {
          contentType = "video/mp4";
        }
      }
      // WebM magic: starts with 0x1A45DFA3
      else if (firstBytesHex.startsWith("1a45dfa3")) {
        contentType = "video/webm";
      }
      // PNG magic
      else if (firstBytesHex.startsWith("89504e47")) {
        contentType = "image/png";
      }
      // JPEG magic
      else if (firstBytesHex.startsWith("ffd8ff")) {
        contentType = "image/jpeg";
      }
      // GIF magic
      else if (firstBytesStr.startsWith("GIF8")) {
        contentType = "image/gif";
      }
      // WebP magic: RIFF....WEBP
      else if (firstBytesStr.startsWith("RIFF") && rawData.slice(8, 12).toString("utf-8") === "WEBP") {
        contentType = "image/webp";
      }
      // Fallback: check if looks like plain text
      else if (contentType === "application/octet-stream" && /^[\x20-\x7E\r\n\t]+$/.test(rawData.slice(0, 100).toString("utf-8"))) {
        contentType = "text/plain; charset=utf-8";
      }
    }

    console.log("[book-file] Serving file:", filename, "size:", rawData.length, "type:", contentType, "forceDownload:", forceDownload);

    // Convert Buffer to Uint8Array for NextResponse compatibility
    const uint8Data = new Uint8Array(rawData);

    // Use "attachment" for downloads, "inline" for viewing
    const disposition = forceDownload ? "attachment" : "inline";

    // Return raw binary response
    return new NextResponse(uint8Data, {
      status: 200,
      headers: {
        "Content-Type": contentType,
        "Content-Length": String(rawData.length),
        "Content-Disposition": `${disposition}; filename="${filename}"`,
        "Cache-Control": "public, max-age=31536000, immutable",
        "X-Content-Type-Options": "nosniff", // Prevent browser from sniffing content type
      },
    });
  } catch (error) {
    console.error("[book-file] Error:", error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Failed to serve file" },
      { status: 500 }
    );
  }
}

// Helper: Decode hex string to UTF-8 text
function hexToString(hex: string): string {
  const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
  const bytes = new Uint8Array(cleanHex.length / 2);
  for (let i = 0; i < cleanHex.length; i += 2) {
    bytes[i / 2] = parseInt(cleanHex.slice(i, i + 2), 16);
  }
  return new TextDecoder().decode(bytes);
}

// Helper: Decode hex string to Buffer (raw bytes)
function hexToBuffer(hex: string): Buffer {
  const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
  return Buffer.from(cleanHex, "hex");
}
src/app/api/brand-kit/download/route.ts
import { NextResponse } from "next/server";
import JSZip from "jszip";

/**
 * Net Library Brand Kit Download API
 * Generates a ZIP file containing all brand icons in SVG and PNG formats
 */

// Icon definitions - same as in the overview HTML
const ICONS: Record<string, { svg: string; category: string }> = {
  // Content Types
  "library": {
    category: "content",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/></svg>`,
  },
  "book-open": {
    category: "content",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></svg>`,
  },
  "document": {
    category: "content",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>`,
  },
  "image": {
    category: "content",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>`,
  },
  "audio": {
    category: "content",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18V5l12-2v13"/><circle cx="6" cy="18" r="3"/><circle cx="18" cy="16" r="3"/></svg>`,
  },
  "video": {
    category: "content",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="2.18" ry="2.18"/><line x1="7" y1="2" x2="7" y2="22"/><line x1="17" y1="2" x2="17" y2="22"/><line x1="2" y1="12" x2="22" y2="12"/><line x1="2" y1="7" x2="7" y2="7"/><line x1="2" y1="17" x2="7" y2="17"/><line x1="17" y1="17" x2="22" y2="17"/><line x1="17" y1="7" x2="22" y2="7"/></svg>`,
  },
  "text": {
    category: "content",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,
  },

  // Actions
  "upload": {
    category: "actions",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg>`,
  },
  "refresh": {
    category: "actions",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg>`,
  },
  "search": {
    category: "actions",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>`,
  },
  "delete": {
    category: "actions",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`,
  },
  "copy": {
    category: "actions",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`,
  },
  "star": {
    category: "actions",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>`,
  },
  "palette": {
    category: "actions",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="13.5" cy="6.5" r=".5"/><circle cx="17.5" cy="10.5" r=".5"/><circle cx="8.5" cy="7.5" r=".5"/><circle cx="6.5" cy="12.5" r=".5"/><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.555C21.965 6.012 17.461 2 12 2z"/></svg>`,
  },

  // Status
  "check": {
    category: "status",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>`,
  },
  "x": {
    category: "status",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>`,
  },
  "warning": {
    category: "status",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>`,
  },
  "lightbulb": {
    category: "status",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="9" y1="18" x2="15" y2="18"/><line x1="10" y1="22" x2="14" y2="22"/><path d="M15.09 14c.18-.98.65-1.74 1.41-2.5A4.65 4.65 0 0 0 18 8 6 6 0 0 0 6 8c0 1 .23 2.23 1.5 3.5A4.61 4.61 0 0 1 8.91 14"/></svg>`,
  },
  "flame": {
    category: "status",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z"/></svg>`,
  },
  "rocket": {
    category: "status",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"/><path d="M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"/><path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/></svg>`,
  },
  "party": {
    category: "status",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5.8 11.3L2 22l10.7-3.79"/><path d="M4 3h.01"/><path d="M22 8h.01"/><path d="M15 2h.01"/><path d="M22 20h.01"/><path d="M22 2l-2.24.75a2.9 2.9 0 0 0-1.96 3.12v0c.1.86-.57 1.63-1.45 1.63h-.38c-.86 0-1.6.6-1.76 1.44L14 10"/><path d="M22 13l-.82-.33c-.86-.34-1.82.2-1.98 1.11v0c-.11.7-.72 1.22-1.43 1.22H17"/><path d="M11 2l.33.82c.34.86-.2 1.82-1.11 1.98v0C9.52 4.9 9 5.52 9 6.23V7"/></svg>`,
  },

  // Organization
  "folder": {
    category: "organization",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg>`,
  },
  "collection": {
    category: "organization",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M16 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8z"/><polyline points="16 3 16 8 21 8"/><line x1="8" y1="13" x2="16" y2="13"/><line x1="8" y1="17" x2="16" y2="17"/></svg>`,
  },
  "archive": {
    category: "organization",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M2 8h20"/><path d="M6 4v4"/></svg>`,
  },
  "link": {
    category: "organization",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,
  },
  "lock": {
    category: "organization",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>`,
  },
  "unlock": {
    category: "organization",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></svg>`,
  },

  // Users & Social
  "user": {
    category: "social",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>`,
  },
  "comment": {
    category: "social",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>`,
  },
  "chart": {
    category: "social",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="20" x2="18" y2="10"/><line x1="12" y1="20" x2="12" y2="4"/><line x1="6" y1="20" x2="6" y2="14"/></svg>`,
  },
  "trophy": {
    category: "social",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 9H4.5a2.5 2.5 0 0 1 0-5H6"/><path d="M18 9h1.5a2.5 2.5 0 0 0 0-5H18"/><path d="M4 22h16"/><path d="M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22"/><path d="M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22"/><path d="M18 2H6v7a6 6 0 0 0 12 0V2Z"/></svg>`,
  },
  "eye": {
    category: "social",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`,
  },
  "eye-off": {
    category: "social",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>`,
  },

  // Finance
  "dollar": {
    category: "finance",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>`,
  },
  "gem": {
    category: "finance",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M6 3h12l4 6-10 13L2 9z"/><path d="M2 9h20"/><path d="M12 22V9"/><path d="m6 3 6 6 6-6"/></svg>`,
  },
  "save": {
    category: "finance",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg>`,
  },
  "zap": {
    category: "finance",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>`,
  },

  // Navigation
  "arrow-up": {
    category: "navigation",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="19" x2="12" y2="5"/><polyline points="5 12 12 5 19 12"/></svg>`,
  },
  "arrow-down": {
    category: "navigation",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"/><polyline points="19 12 12 19 5 12"/></svg>`,
  },
  "chevron-up": {
    category: "navigation",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m18 15-6-6-6 6"/></svg>`,
  },
  "play": {
    category: "navigation",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>`,
  },
  "globe": {
    category: "navigation",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>`,
  },
  "smartphone": {
    category: "navigation",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="2" width="14" height="20" rx="2" ry="2"/><line x1="12" y1="18" x2="12.01" y2="18"/></svg>`,
  },

  // Misc
  "puzzle": {
    category: "misc",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19.439 7.85c-.049.322.059.648.289.878l1.568 1.568c.47.47.706 1.087.706 1.704s-.235 1.233-.706 1.704l-1.611 1.611a.98.98 0 0 1-.837.276c-.47-.07-.802-.48-.968-.925a2.501 2.501 0 1 0-3.214 3.214c.446.166.855.497.925.968a.979.979 0 0 1-.276.837l-1.61 1.61a2.404 2.404 0 0 1-1.705.707 2.402 2.402 0 0 1-1.704-.706l-1.568-1.568a1.026 1.026 0 0 0-.877-.29c-.493.074-.84.504-1.02.968a2.5 2.5 0 1 1-3.237-3.237c.464-.18.894-.527.967-1.02a1.026 1.026 0 0 0-.289-.877l-1.568-1.568A2.402 2.402 0 0 1 1.998 12c0-.617.236-1.234.706-1.704L4.315 8.68c.24-.24.581-.353.917-.303.515.077.877.528 1.073 1.01a2.5 2.5 0 1 0 3.259-3.259c-.482-.196-.933-.558-1.01-1.073-.05-.336.062-.676.303-.917l1.611-1.611A2.404 2.404 0 0 1 12 2.001a2.4 2.4 0 0 1 1.704.706l1.568 1.568c.23.23.556.338.877.29.493-.074.84-.504 1.02-.968a2.5 2.5 0 1 1 3.237 3.237c-.464.18-.894.527-.967 1.02Z"/></svg>`,
  },
  "plug": {
    category: "misc",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22v-5"/><path d="M9 8V2"/><path d="M15 8V2"/><path d="M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z"/></svg>`,
  },
  "shield": {
    category: "misc",
    svg: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>`,
  },
};

export async function GET() {
  try {
    const zip = new JSZip();
    const _sizes = [16, 24, 32, 48]; // Reserved for future icon size variants

    // Add README
    zip.file("README.md", `# Net Library Brand Kit

Official icon set for Net Library. All icons follow the Lucide design style.

## Icon Specifications
- ViewBox: 0 0 24 24
- Stroke Width: 2px
- Stroke Linecap: round
- Stroke Linejoin: round
- Default Color: #00aa00 (Net Library Green)

## Folder Structure
- /svg/ - Vector SVG files
- /png-16/ - 16x16 PNG exports
- /png-24/ - 24x24 PNG exports
- /png-32/ - 32x32 PNG exports
- /png-48/ - 48x48 PNG exports

## Usage
Replace emoji-based UI elements with these icons for a consistent, professional look.

## Colors
- Primary Green: #00aa00
- Use \`currentColor\` in SVGs for flexibility
`);

    // Add SVG folder
    const svgFolder = zip.folder("svg");
    if (svgFolder) {
      for (const [name, { svg }] of Object.entries(ICONS)) {
        svgFolder.file(`${name}.svg`, svg);
      }
    }

    // For PNG generation, we'd need canvas/sharp - for now just include SVGs
    // Add placeholder note about PNG generation
    zip.file("PNG_NOTE.txt", `PNG exports require server-side image processing.

For PNG versions:
1. Open the SVG files in a design tool (Figma, Sketch, etc.)
2. Export at desired sizes (16, 24, 32, 48px)

Or use a command-line tool like:
  npx svgexport icon.svg icon.png 48:48
`);

    // Generate the zip
    const content = await zip.generateAsync({ type: "arraybuffer" });

    return new NextResponse(content, {
      headers: {
        "Content-Type": "application/zip",
        "Content-Disposition": "attachment; filename=net-library-brand-kit.zip",
      },
    });
  } catch (error) {
    console.error("Error generating brand kit:", error);
    return NextResponse.json({ error: "Failed to generate brand kit" }, { status: 500 });
  }
}
src/app/api/changelog/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

const CHANGELOG_KEY = "app-changelog";

export interface ChangelogEntry {
  version: string;
  publishedAt: number;
  changes: {
    type: "feature" | "fix" | "improvement" | "breaking" | "docs" | "internal";
    category: "ui" | "api" | "database" | "achievements" | "uploads" | "social" | "membership" | "other";
    title: string;
    description: string;
    technical?: string; // Technical details for the specs page
  }[];
  summary: string; // One-line summary for overview page
}

interface ChangelogIndex {
  entries: ChangelogEntry[];
  currentVersion: string;
  lastUpdated: number;
}

// Fetch changelog from KV
async function fetchChangelog(): Promise<ChangelogIndex> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, CHANGELOG_KEY)).limit(1);
    if (!result[0]?.value) {
      return {
        entries: [],
        currentVersion: "1.0.0",
        lastUpdated: Date.now(),
      };
    }
    return JSON.parse(result[0].value) as ChangelogIndex;
  } catch (error) {
    console.error("[changelog] fetchChangelog error:", error);
    return {
      entries: [],
      currentVersion: "1.0.0",
      lastUpdated: Date.now(),
    };
  }
}

// Store changelog to KV
async function storeChangelog(data: ChangelogIndex): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: CHANGELOG_KEY, value: JSON.stringify(data) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(data) },
    });
    return true;
  } catch (error) {
    console.error("[changelog] storeChangelog error:", error);
    return false;
  }
}

// Increment version number
function incrementVersion(version: string, type: "major" | "minor" | "patch"): string {
  const [major, minor, patch] = version.split(".").map(Number);
  switch (type) {
    case "major":
      return `${major + 1}.0.0`;
    case "minor":
      return `${major}.${minor + 1}.0`;
    case "patch":
    default:
      return `${major}.${minor}.${patch + 1}`;
  }
}

// GET - Fetch changelog (all entries or specific version)
export async function GET(request: NextRequest) {
  const version = request.nextUrl.searchParams.get("version");
  const limit = parseInt(request.nextUrl.searchParams.get("limit") || "10");
  const format = request.nextUrl.searchParams.get("format"); // "overview" | "technical" | "full"

  try {
    const changelog = await fetchChangelog();

    if (version) {
      const entry = changelog.entries.find(e => e.version === version);
      if (!entry) {
        return NextResponse.json({ error: "Version not found" }, { status: 404 });
      }
      return NextResponse.json({ success: true, entry });
    }

    // Return entries based on format
    const entries = changelog.entries.slice(0, limit);

    if (format === "overview") {
      // Simplified format for overview page
      return NextResponse.json({
        success: true,
        currentVersion: changelog.currentVersion,
        entries: entries.map(e => ({
          version: e.version,
          publishedAt: e.publishedAt,
          summary: e.summary,
          changeCount: e.changes.length,
        })),
      });
    }

    if (format === "technical") {
      // Technical format for specs page
      return NextResponse.json({
        success: true,
        currentVersion: changelog.currentVersion,
        entries: entries.map(e => ({
          version: e.version,
          publishedAt: e.publishedAt,
          changes: e.changes.filter(c => c.technical || c.type !== "docs"),
        })),
      });
    }

    return NextResponse.json({
      success: true,
      currentVersion: changelog.currentVersion,
      totalEntries: changelog.entries.length,
      entries,
      lastUpdated: changelog.lastUpdated,
    });
  } catch (error) {
    console.error("[changelog] GET error:", error);
    return NextResponse.json({ error: "Failed to fetch changelog" }, { status: 500 });
  }
}

// POST - Add a new changelog entry (called on publish)
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { changes, summary, versionType = "patch" } = body;

    if (!changes || !Array.isArray(changes) || changes.length === 0) {
      return NextResponse.json(
        { error: "changes array required with at least one change" },
        { status: 400 }
      );
    }

    if (!summary) {
      return NextResponse.json(
        { error: "summary required" },
        { status: 400 }
      );
    }

    const changelog = await fetchChangelog();

    // Determine new version
    const newVersion = incrementVersion(changelog.currentVersion, versionType);

    // Create new entry
    const newEntry: ChangelogEntry = {
      version: newVersion,
      publishedAt: Date.now(),
      changes,
      summary,
    };

    // Add to beginning of entries
    changelog.entries.unshift(newEntry);
    changelog.currentVersion = newVersion;
    changelog.lastUpdated = Date.now();

    // Keep last 100 entries
    if (changelog.entries.length > 100) {
      changelog.entries = changelog.entries.slice(0, 100);
    }

    await storeChangelog(changelog);

    console.log(`[changelog] Added version ${newVersion} with ${changes.length} changes`);

    return NextResponse.json({
      success: true,
      entry: newEntry,
      currentVersion: newVersion,
    });
  } catch (error) {
    console.error("[changelog] POST error:", error);
    return NextResponse.json({ error: "Failed to add changelog entry" }, { status: 500 });
  }
}

// PATCH - Update documentation pages based on changelog
export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const { action } = body;

    if (action === "generate-docs-update") {
      // Generate markdown/HTML snippets for documentation pages
      const changelog = await fetchChangelog();
      const latestEntries = changelog.entries.slice(0, 5);

      // Generate overview update
      const overviewUpdate = latestEntries.map(entry => {
        const date = new Date(entry.publishedAt).toLocaleDateString("en-US", {
          year: "numeric",
          month: "short",
          day: "numeric",
        });
        return `### v${entry.version} (${date})\n${entry.summary}\n`;
      }).join("\n");

      // Generate technical update
      const technicalUpdate = latestEntries.map(entry => {
        const date = new Date(entry.publishedAt).toLocaleDateString("en-US", {
          year: "numeric",
          month: "short",
          day: "numeric",
        });
        const changesList = entry.changes
          .filter(c => c.technical || c.type !== "docs")
          .map(c => {
            const badge = c.type === "feature" ? "🆕" :
                         c.type === "fix" ? "🐛" :
                         c.type === "improvement" ? "✨" :
                         c.type === "breaking" ? "⚠️" : "📝";
            return `- ${badge} **${c.title}**: ${c.description}${c.technical ? `\n  - Technical: ${c.technical}` : ""}`;
          })
          .join("\n");
        return `### v${entry.version} (${date})\n${changesList}\n`;
      }).join("\n");

      return NextResponse.json({
        success: true,
        currentVersion: changelog.currentVersion,
        overviewUpdate,
        technicalUpdate,
        lastUpdated: changelog.lastUpdated,
      });
    }

    if (action === "update-entry") {
      // Update an existing changelog entry (for security fixes, typo corrections, etc.)
      const { version, changes } = body;

      if (!version || !changes || !Array.isArray(changes)) {
        return NextResponse.json({ error: "version and changes array required" }, { status: 400 });
      }

      const changelog = await fetchChangelog();
      const entryIndex = changelog.entries.findIndex(e => e.version === version);

      if (entryIndex === -1) {
        return NextResponse.json({ error: "Version not found" }, { status: 404 });
      }

      // Update the changes array
      changelog.entries[entryIndex].changes = changes;
      changelog.lastUpdated = Date.now();

      await storeChangelog(changelog);

      console.log(`[changelog] Updated version ${version}`);

      return NextResponse.json({
        success: true,
        entry: changelog.entries[entryIndex],
      });
    }

    return NextResponse.json({ error: "Invalid action" }, { status: 400 });
  } catch (error) {
    console.error("[changelog] PATCH error:", error);
    return NextResponse.json({ error: "Failed to process request" }, { status: 500 });
  }
}
src/app/api/coingecko/[...route]/route.ts
// Complete CoinGecko API proxy using our new handler architecture
import { Coingecko } from "@coingecko/coingecko-typescript";
import { createCoinGeckoApiHandler } from "@/neynar-web-sdk/nextjs";
import { privateConfig } from "@/config/private-config";

// Initialize the CoinGecko client with API key from environment
// Use demo environment for testing (can be switched to "pro" with proAPIKey for production)
const client = new Coingecko({
  demoAPIKey: privateConfig.coingeckoApiKey,
  environment: "demo",
});

// Export Next.js API route handlers
export const { GET, POST, PUT, DELETE, OPTIONS } =
  createCoinGeckoApiHandler(client);
src/app/api/collections/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

interface CollectionItem {
  contentKey: string;
  title: string;
  addedAt: number;
}

interface Collection {
  id: string;
  name: string;
  description?: string;
  emoji: string;
  ownerAddress: string;
  items: CollectionItem[];
  isPublic: boolean;
  createdAt: number;
  updatedAt: number;
}

interface UserCollections {
  collections: Collection[];
}

const getKvKey = (userAddress: string) => `collections:${userAddress.toLowerCase()}`;

// Helper to fetch collections from KV database
async function fetchUserCollections(userAddress: string): Promise<UserCollections> {
  const empty: UserCollections = { collections: [] };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, getKvKey(userAddress))).limit(1);
    if (!result[0]?.value) return empty;
    return JSON.parse(result[0].value) as UserCollections;
  } catch {
    return empty;
  }
}

// Helper to store collections to KV database
async function storeUserCollections(userAddress: string, data: UserCollections): Promise<boolean> {
  try {
    const key = getKvKey(userAddress);
    await db.insert(kv).values({
      key,
      value: JSON.stringify(data),
    }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(data) },
    });
    return true;
  } catch (error) {
    console.error("storeUserCollections error:", error);
    return false;
  }
}

// GET - Fetch collections for a user
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userAddress = searchParams.get("userAddress");
    const collectionId = searchParams.get("collectionId");

    if (!userAddress) {
      return NextResponse.json({ error: "Missing userAddress" }, { status: 400 });
    }

    const data = await fetchUserCollections(userAddress);

    if (collectionId) {
      const collection = data.collections.find(c => c.id === collectionId);
      return NextResponse.json({ collection: collection || null });
    }

    return NextResponse.json({ collections: data.collections });
  } catch (error) {
    console.error("[collections] GET error:", error);
    return NextResponse.json({ error: "Failed to fetch collections" }, { status: 500 });
  }
}

// POST - Manage collections
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, userAddress, collectionId, name, description, emoji, isPublic, contentKey, title } = body;

    if (!userAddress) {
      return NextResponse.json({ error: "Missing userAddress" }, { status: 400 });
    }

    const data = await fetchUserCollections(userAddress);

    if (action === "create") {
      if (!name) {
        return NextResponse.json({ error: "Collection name required" }, { status: 400 });
      }

      const collection: Collection = {
        id: `col-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
        name,
        description: description || "",
        emoji: emoji || "📁",
        ownerAddress: userAddress.toLowerCase(),
        items: [],
        isPublic: isPublic || false,
        createdAt: Date.now(),
        updatedAt: Date.now(),
      };

      data.collections.push(collection);
      await storeUserCollections(userAddress, data);

      return NextResponse.json({ success: true, collection });
    }

    if (action === "update") {
      const collection = data.collections.find(c => c.id === collectionId);
      if (!collection) {
        return NextResponse.json({ error: "Collection not found" }, { status: 404 });
      }

      if (name !== undefined) collection.name = name;
      if (description !== undefined) collection.description = description;
      if (emoji !== undefined) collection.emoji = emoji;
      if (isPublic !== undefined) collection.isPublic = isPublic;
      collection.updatedAt = Date.now();

      await storeUserCollections(userAddress, data);

      return NextResponse.json({ success: true, collection });
    }

    if (action === "delete") {
      const index = data.collections.findIndex(c => c.id === collectionId);
      if (index === -1) {
        return NextResponse.json({ error: "Collection not found" }, { status: 404 });
      }

      data.collections.splice(index, 1);
      await storeUserCollections(userAddress, data);

      return NextResponse.json({ success: true });
    }

    if (action === "add-item") {
      const collection = data.collections.find(c => c.id === collectionId);
      if (!collection) {
        return NextResponse.json({ error: "Collection not found" }, { status: 404 });
      }

      // Check if already in collection
      if (collection.items.some(item => item.contentKey === contentKey)) {
        return NextResponse.json({ success: true, message: "Already in collection" });
      }

      collection.items.push({
        contentKey,
        title: title || contentKey,
        addedAt: Date.now(),
      });
      collection.updatedAt = Date.now();

      await storeUserCollections(userAddress, data);

      return NextResponse.json({ success: true, collection });
    }

    if (action === "remove-item") {
      const collection = data.collections.find(c => c.id === collectionId);
      if (!collection) {
        return NextResponse.json({ error: "Collection not found" }, { status: 404 });
      }

      collection.items = collection.items.filter(item => item.contentKey !== contentKey);
      collection.updatedAt = Date.now();

      await storeUserCollections(userAddress, data);

      return NextResponse.json({ success: true, collection });
    }

    return NextResponse.json({ error: "Invalid action" }, { status: 400 });
  } catch (error) {
    console.error("[collections] POST error:", error);
    return NextResponse.json({ error: "Failed to process collection" }, { status: 500 });
  }
}
src/app/api/comments/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { verifyMessage } from "viem";
import { parseSiweMessage } from "@/lib/siwe";

interface Comment {
  id: string;
  contentKey: string;
  authorAddress: string;
  authorUsername?: string;
  authorPfpUrl?: string;
  text: string;
  parentId?: string;
  likes: number;
  likedBy: string[];
  createdAt: number;
  updatedAt?: number;
  isEdited: boolean;
}

interface CommentsData {
  comments: Comment[];
  totalCount: number;
}

// Validate Ethereum address format (0x followed by 40 hex characters)
function isValidEthAddress(address: string): boolean {
  return /^0x[0-9a-fA-F]{40}$/.test(address);
}

/**
 * Verify a SIWE signature proves ownership of the claimed wallet address.
 *
 * @param siweMessage  - The EIP-4361 message that was signed
 * @param siweSignature - The hex signature from the wallet
 * @param expectedAddress - The address the caller claims to be
 * @returns null on success, or an error string on failure
 */
async function verifySiweOwnership(
  siweMessage: string,
  siweSignature: string,
  expectedAddress: string
): Promise<string | null> {
  try {
    const parsed = parseSiweMessage(siweMessage);

    if (!parsed.address) {
      return "Invalid SIWE message: no address found";
    }

    // Address in the SIWE message must match the claimed userAddress
    if (parsed.address.toLowerCase() !== expectedAddress.toLowerCase()) {
      return "SIWE message address does not match userAddress";
    }

    // Reject expired messages
    if (parsed.expirationTime) {
      if (new Date(parsed.expirationTime) < new Date()) {
        return "SIWE message has expired";
      }
    }

    // Reject messages older than 1 hour (replay window)
    if (parsed.issuedAt) {
      const issuedAt = new Date(parsed.issuedAt);
      const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
      if (issuedAt < oneHourAgo) {
        return "SIWE message is too old (max 1 hour)";
      }
    }

    // Verify the cryptographic signature
    const isValid = await verifyMessage({
      address: expectedAddress as `0x${string}`,
      message: siweMessage,
      signature: siweSignature as `0x${string}`,
    });

    if (!isValid) {
      return "Invalid SIWE signature";
    }

    return null; // success
  } catch {
    return "Failed to verify SIWE signature";
  }
}

const getKvKey = (contentKey: string) => `comments:${contentKey}`;

// Helper to fetch comments from KV database
async function fetchComments(contentKey: string): Promise<CommentsData> {
  const empty: CommentsData = { comments: [], totalCount: 0 };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, getKvKey(contentKey))).limit(1);
    if (!result[0]?.value) return empty;
    return JSON.parse(result[0].value) as CommentsData;
  } catch {
    return empty;
  }
}

// Helper to store comments to KV database
async function storeComments(contentKey: string, data: CommentsData): Promise<boolean> {
  try {
    const key = getKvKey(contentKey);
    await db.insert(kv).values({
      key,
      value: JSON.stringify(data),
    }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(data) },
    });
    return true;
  } catch (error) {
    console.error("storeComments error:", error);
    return false;
  }
}

// GET - Fetch comments for a book
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const contentKey = searchParams.get("contentKey");
    const parentId = searchParams.get("parentId");

    if (!contentKey) {
      return NextResponse.json({ error: "Missing contentKey" }, { status: 400 });
    }

    const data = await fetchComments(contentKey);

    // Filter by parent (null = top-level, id = replies to that comment)
    const comments = data.comments.filter(c =>
      parentId ? c.parentId === parentId : !c.parentId
    );

    // Sort by newest first
    comments.sort((a, b) => b.createdAt - a.createdAt);

    // Get reply counts for each comment
    const commentsWithReplies = comments.map(comment => ({
      ...comment,
      replyCount: data.comments.filter(c => c.parentId === comment.id).length,
    }));

    return NextResponse.json({
      comments: commentsWithReplies,
      totalCount: data.totalCount,
    });
  } catch (error) {
    console.error("[comments] GET error:", error);
    return NextResponse.json({ error: "Failed to fetch comments" }, { status: 500 });
  }
}

// POST - Create, update, delete, or like a comment
// All write operations require a SIWE signature proving ownership of userAddress.
// Callers must include: siweMessage (the signed EIP-4361 message) and siweSignature.
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, contentKey, userAddress, commentId, text, parentId, username, pfpUrl, siweMessage, siweSignature } = body;

    if (!contentKey || !userAddress) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
    }

    // Validate address format to prevent trivially malformed addresses
    if (!isValidEthAddress(userAddress)) {
      return NextResponse.json({ error: "Invalid wallet address format" }, { status: 400 });
    }

    // Require SIWE proof of wallet ownership for all write operations
    if (!siweMessage || !siweSignature) {
      return NextResponse.json(
        { error: "Wallet signature required. Provide siweMessage and siweSignature to prove ownership of userAddress." },
        { status: 401 }
      );
    }

    const siweError = await verifySiweOwnership(siweMessage, siweSignature, userAddress);
    if (siweError) {
      return NextResponse.json({ error: siweError }, { status: 401 });
    }

    const data = await fetchComments(contentKey);

    if (action === "create") {
      if (!text?.trim()) {
        return NextResponse.json({ error: "Comment text required" }, { status: 400 });
      }

      const comment: Comment = {
        id: `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
        contentKey,
        authorAddress: userAddress.toLowerCase(),
        authorUsername: username,
        authorPfpUrl: pfpUrl,
        text: text.trim().slice(0, 500),
        parentId: parentId || undefined,
        likes: 0,
        likedBy: [],
        createdAt: Date.now(),
        isEdited: false,
      };

      data.comments.unshift(comment);
      data.totalCount += 1;
      await storeComments(contentKey, data);

      return NextResponse.json({ success: true, comment });
    }

    if (action === "edit") {
      if (!commentId || !text?.trim()) {
        return NextResponse.json({ error: "Missing commentId or text" }, { status: 400 });
      }

      const comment = data.comments.find(c => c.id === commentId);
      if (!comment) {
        return NextResponse.json({ error: "Comment not found" }, { status: 404 });
      }

      if (comment.authorAddress.toLowerCase() !== userAddress.toLowerCase()) {
        return NextResponse.json({ error: "Not authorized" }, { status: 403 });
      }

      comment.text = text.trim().slice(0, 500);
      comment.updatedAt = Date.now();
      comment.isEdited = true;

      await storeComments(contentKey, data);

      return NextResponse.json({ success: true, comment });
    }

    if (action === "delete") {
      if (!commentId) {
        return NextResponse.json({ error: "Missing commentId" }, { status: 400 });
      }

      const comment = data.comments.find(c => c.id === commentId);
      if (!comment) {
        return NextResponse.json({ error: "Comment not found" }, { status: 404 });
      }

      if (comment.authorAddress.toLowerCase() !== userAddress.toLowerCase()) {
        return NextResponse.json({ error: "Not authorized" }, { status: 403 });
      }

      // Remove comment and its replies
      const idsToRemove = new Set([commentId]);
      data.comments.forEach(c => {
        if (c.parentId === commentId) {
          idsToRemove.add(c.id);
        }
      });

      data.comments = data.comments.filter(c => !idsToRemove.has(c.id));
      data.totalCount = Math.max(0, data.totalCount - idsToRemove.size);

      await storeComments(contentKey, data);

      return NextResponse.json({ success: true });
    }

    if (action === "like") {
      if (!commentId) {
        return NextResponse.json({ error: "Missing commentId" }, { status: 400 });
      }

      const comment = data.comments.find(c => c.id === commentId);
      if (!comment) {
        return NextResponse.json({ error: "Comment not found" }, { status: 404 });
      }

      const userLower = userAddress.toLowerCase();

      if (comment.likedBy.includes(userLower)) {
        // Unlike
        comment.likedBy = comment.likedBy.filter(a => a !== userLower);
        comment.likes = Math.max(0, comment.likes - 1);
      } else {
        // Like
        comment.likedBy.push(userLower);
        comment.likes += 1;
      }

      await storeComments(contentKey, data);

      return NextResponse.json({ success: true, likes: comment.likes, liked: comment.likedBy.includes(userLower) });
    }

    return NextResponse.json({ error: "Invalid action" }, { status: 400 });
  } catch (error) {
    console.error("[comments] POST error:", error);
    return NextResponse.json({ error: "Failed to process comment" }, { status: 500 });
  }
}
src/app/api/cover-art/[key]/route.ts
import { NextRequest, NextResponse } from "next/server";
import { getBookInfoByContentKey } from "@/lib/cover-art-cache";

// Fast cover art lookup by content key
// Reads directly from discovery-index (single source of truth)
// Used by share image generation and external API consumers

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ key: string }> }
) {
  try {
    const { key } = await params;
    const contentKey = decodeURIComponent(key);

    // Use shared utility for lookup (reads from discovery-index, handles 0x normalization)
    const data = await getBookInfoByContentKey(contentKey);

    if (!data) {
      return NextResponse.json({
        found: false,
        coverUrl: "",
        title: "Untitled",
        author: "Unknown",
      });
    }

    return NextResponse.json({
      found: true,
      coverUrl: data.coverUrl,
      title: data.title,
      author: data.author,
    });
  } catch (error) {
    console.error("Cover art lookup error:", error);
    return NextResponse.json({
      found: false,
      coverUrl: "",
      title: "Untitled",
      author: "Unknown",
    }, { status: 500 });
  }
}

// Note: To update cover art, use the PATCH /api/discovery endpoint
// This keeps discovery-index as the single source of truth
src/app/api/covers/[key]/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

/**
 * Cover Image Storage API
 *
 * Stores and serves cover images directly from our KV database.
 * This eliminates dependency on external blob storage (Vercel Blob).
 *
 * GET /api/covers/[key] - Serve the cover image as binary
 * The key is a sanitized content key (alphanumeric only)
 */

const COVER_PREFIX = "cover:";
const MAX_COVER_SIZE = 500 * 1024; // 500KB max per cover

// HEAD - Quick check if cover exists (used by share image generation)
export async function HEAD(
  request: NextRequest,
  { params }: { params: Promise<{ key: string }> }
) {
  try {
    const { key } = await params;
    const coverKey = `${COVER_PREFIX}${key}`;

    const result = await db.select().from(kv).where(eq(kv.key, coverKey)).limit(1);

    if (!result[0]?.value) {
      return new NextResponse(null, { status: 404 });
    }

    const data = JSON.parse(result[0].value) as {
      base64: string;
      contentType: string;
    };

    // Return headers without body
    return new NextResponse(null, {
      status: 200,
      headers: {
        "Content-Type": data.contentType,
        "Content-Length": String(Math.ceil(data.base64.length * 0.75)),
        "Cache-Control": "public, max-age=31536000, immutable",
      },
    });
  } catch (error) {
    console.error("[covers] HEAD error:", error);
    return new NextResponse(null, { status: 500 });
  }
}

// GET - Serve cover image as binary
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ key: string }> }
) {
  try {
    const { key } = await params;
    const coverKey = `${COVER_PREFIX}${key}`;

    const result = await db.select().from(kv).where(eq(kv.key, coverKey)).limit(1);

    if (!result[0]?.value) {
      return new NextResponse("Cover not found", { status: 404 });
    }

    const data = JSON.parse(result[0].value) as {
      base64: string;
      contentType: string;
      contentKey: string;
    };

    // Convert base64 back to binary
    const buffer = Buffer.from(data.base64, "base64");

    return new NextResponse(buffer, {
      headers: {
        "Content-Type": data.contentType,
        "Cache-Control": "public, max-age=31536000, immutable", // Cache for 1 year
        "Content-Length": String(buffer.length),
      },
    });
  } catch (error) {
    console.error("[covers] GET error:", error);
    return new NextResponse("Failed to fetch cover", { status: 500 });
  }
}

// POST - Store a new cover (internal use)
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ key: string }> }
) {
  try {
    const { key } = await params;
    const body = await request.json();
    const { dataUrl, contentKey } = body;

    if (!dataUrl || !dataUrl.startsWith("data:image/")) {
      return NextResponse.json({ error: "Invalid data URL" }, { status: 400 });
    }

    // Parse the data URL
    const matches = dataUrl.match(/^data:image\/(png|jpeg|jpg|webp|gif);base64,(.+)$/);
    if (!matches) {
      return NextResponse.json({ error: "Could not parse data URL" }, { status: 400 });
    }

    const imageType = matches[1] === "jpg" ? "jpeg" : matches[1];
    const base64Data = matches[2];

    // Check size
    const sizeBytes = Math.ceil(base64Data.length * 0.75); // Approximate decoded size
    if (sizeBytes > MAX_COVER_SIZE) {
      return NextResponse.json({
        error: `Cover too large (${Math.round(sizeBytes/1024)}KB). Max: ${MAX_COVER_SIZE/1024}KB`
      }, { status: 400 });
    }

    const coverKey = `${COVER_PREFIX}${key}`;
    const coverData = {
      base64: base64Data,
      contentType: `image/${imageType}`,
      contentKey: contentKey || key,
      storedAt: Date.now(),
    };

    // Store in KV
    await db.insert(kv).values({
      key: coverKey,
      value: JSON.stringify(coverData),
    }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(coverData) },
    });

    // Return the URL to access this cover - ALWAYS use production domain
    // This ensures the URL works when shared to Twitter/Farcaster
    const productionHost = "netlibrary.neynar.com";
    const coverUrl = `https://${productionHost}/api/covers/${key}`;

    console.log(`[covers] Stored cover for ${key} (${Math.round(sizeBytes/1024)}KB) -> ${coverUrl}`);

    return NextResponse.json({
      success: true,
      url: coverUrl,
      size: sizeBytes,
    });
  } catch (error) {
    console.error("[covers] POST error:", error);
    return NextResponse.json({ error: "Failed to store cover" }, { status: 500 });
  }
}
src/app/api/covers/fix-all/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry } from "@/lib/net-protocol";

const DISCOVERY_KEY = "discovery-index";
const COVER_PREFIX = "cover:";
const MAX_COVER_SIZE = 500 * 1024; // 500KB max per cover

interface FixResult {
  contentKey: string;
  title: string;
  action: "converted" | "skipped" | "failed";
  reason?: string;
  newCoverUrl?: string;
}

/**
 * POST /api/covers/fix-all
 *
 * Fixes all cover URLs in the discovery index:
 * 1. Converts base64 data URLs to hosted URLs via /api/covers/[key]
 * 2. Reports items without covers
 *
 * Query params:
 * - dryRun=true: Only report what would be fixed, don't actually fix
 */
export async function POST(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const dryRun = searchParams.get("dryRun") === "true";

    // ALWAYS use production domain for cover URLs
    // This ensures Twitter/Farcaster crawlers can access the images
    const productionHost = "netlibrary.neynar.com";
    const baseUrl = `https://${productionHost}`;

    // Fetch current discovery index
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    const entries: DiscoveryEntry[] = result[0]?.value
      ? JSON.parse(result[0].value)
      : [];

    const results: FixResult[] = [];
    let modified = false;

    for (const entry of entries) {
      const { contentKey, title, coverUrl } = entry;

      // Skip if no cover at all
      if (!coverUrl) {
        results.push({
          contentKey,
          title,
          action: "skipped",
          reason: "No cover URL - needs manual extraction or is non-PDF content",
        });
        continue;
      }

      // Skip if already a hosted URL
      if (coverUrl.startsWith("http://") || coverUrl.startsWith("https://")) {
        results.push({
          contentKey,
          title,
          action: "skipped",
          reason: "Already hosted URL",
          newCoverUrl: coverUrl,
        });
        continue;
      }

      // Handle base64 data URLs
      if (coverUrl.startsWith("data:image/")) {
        if (dryRun) {
          results.push({
            contentKey,
            title,
            action: "converted",
            reason: "Would convert base64 to hosted URL (dry run)",
          });
          continue;
        }

        try {
          // Parse the data URL
          const matches = coverUrl.match(/^data:image\/(png|jpeg|jpg|webp|gif);base64,(.+)$/);
          if (!matches) {
            results.push({
              contentKey,
              title,
              action: "failed",
              reason: "Could not parse data URL format",
            });
            continue;
          }

          const imageType = matches[1] === "jpg" ? "jpeg" : matches[1];
          const base64Data = matches[2];

          // Check size
          const sizeBytes = Math.ceil(base64Data.length * 0.75);
          if (sizeBytes > MAX_COVER_SIZE) {
            results.push({
              contentKey,
              title,
              action: "failed",
              reason: `Cover too large (${Math.round(sizeBytes / 1024)}KB). Max: ${MAX_COVER_SIZE / 1024}KB`,
            });
            continue;
          }

          // Generate a safe key for storage
          const safeKey = contentKey.replace(/[^a-zA-Z0-9]/g, "").slice(0, 32);
          const coverKey = `${COVER_PREFIX}${safeKey}`;

          // Store in KV database
          const coverData = {
            base64: base64Data,
            contentType: `image/${imageType}`,
            contentKey: contentKey,
            storedAt: Date.now(),
          };

          await db.insert(kv).values({
            key: coverKey,
            value: JSON.stringify(coverData),
          }).onConflictDoUpdate({
            target: kv.key,
            set: { value: JSON.stringify(coverData) },
          });

          // Build the hosted URL
          const hostedUrl = `${baseUrl}/api/covers/${safeKey}`;

          // Update the entry
          entry.coverUrl = hostedUrl;
          modified = true;

          results.push({
            contentKey,
            title,
            action: "converted",
            reason: `Converted base64 (${Math.round(sizeBytes / 1024)}KB) to hosted URL`,
            newCoverUrl: hostedUrl,
          });

        } catch (err) {
          results.push({
            contentKey,
            title,
            action: "failed",
            reason: `Error converting: ${err instanceof Error ? err.message : String(err)}`,
          });
        }
        continue;
      }

      // Unknown format
      results.push({
        contentKey,
        title,
        action: "failed",
        reason: `Unknown cover URL format: ${coverUrl.slice(0, 50)}...`,
      });
    }

    // Save updated entries if modified
    if (modified && !dryRun) {
      await db.insert(kv).values({
        key: DISCOVERY_KEY,
        value: JSON.stringify(entries),
      }).onConflictDoUpdate({
        target: kv.key,
        set: { value: JSON.stringify(entries) },
      });
    }

    // Summarize results
    const converted = results.filter(r => r.action === "converted").length;
    const skipped = results.filter(r => r.action === "skipped").length;
    const failed = results.filter(r => r.action === "failed").length;
    const alreadyHosted = results.filter(r => r.reason === "Already hosted URL").length;
    const noCover = results.filter(r => r.reason?.includes("No cover URL")).length;

    return NextResponse.json({
      success: true,
      dryRun,
      summary: {
        total: entries.length,
        converted,
        skipped,
        failed,
        alreadyHosted,
        noCover,
      },
      results,
    });

  } catch (error) {
    console.error("[covers/fix-all] Error:", error);
    return NextResponse.json({ error: "Failed to fix covers" }, { status: 500 });
  }
}

/**
 * PATCH /api/covers/fix-all
 *
 * Fixes localhost URLs to use the production domain
 */
export async function PATCH(request: NextRequest) {
  try {
    const host = request.headers.get("host") || "netlibrary.neynar.com";
    const protocol = host.includes("localhost") ? "http" : "https";
    const _baseUrl = `${protocol}://${host}`;

    // Get production domain from request or use default
    const body = await request.json().catch(() => ({}));
    const productionDomain = body.productionDomain || "netlibrary.neynar.com";
    const productionBaseUrl = `https://${productionDomain}`;

    // Fetch current discovery index
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    const entries: DiscoveryEntry[] = result[0]?.value
      ? JSON.parse(result[0].value)
      : [];

    let fixed = 0;
    for (const entry of entries) {
      if (entry.coverUrl && entry.coverUrl.includes("localhost")) {
        // Replace localhost URL with production URL
        const coverPath = entry.coverUrl.replace(/^https?:\/\/[^/]+/, "");
        entry.coverUrl = `${productionBaseUrl}${coverPath}`;
        fixed++;
      }
    }

    if (fixed > 0) {
      await db.insert(kv).values({
        key: DISCOVERY_KEY,
        value: JSON.stringify(entries),
      }).onConflictDoUpdate({
        target: kv.key,
        set: { value: JSON.stringify(entries) },
      });
    }

    return NextResponse.json({
      success: true,
      fixed,
      productionDomain,
    });

  } catch (error) {
    console.error("[covers/fix-all] PATCH Error:", error);
    return NextResponse.json({ error: "Failed to fix localhost URLs" }, { status: 500 });
  }
}

/**
 * GET /api/covers/fix-all
 *
 * Returns current cover status for all entries
 */
export async function GET() {
  try {
    // Fetch current discovery index
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    const entries: DiscoveryEntry[] = result[0]?.value
      ? JSON.parse(result[0].value)
      : [];

    const status = entries.map(entry => {
      const { contentKey, title, coverUrl, mediaType } = entry;

      let coverStatus: string;
      if (!coverUrl) {
        coverStatus = "missing";
      } else if (coverUrl.startsWith("data:")) {
        coverStatus = "base64";
      } else if (coverUrl.startsWith("http")) {
        coverStatus = "hosted";
      } else {
        coverStatus = "unknown";
      }

      return {
        contentKey,
        title,
        mediaType: mediaType || "unknown",
        coverStatus,
        coverUrl: coverUrl ? (coverUrl.startsWith("data:") ? "data:..." : coverUrl) : null,
      };
    });

    const hosted = status.filter(s => s.coverStatus === "hosted").length;
    const base64 = status.filter(s => s.coverStatus === "base64").length;
    const missing = status.filter(s => s.coverStatus === "missing").length;

    return NextResponse.json({
      success: true,
      summary: {
        total: entries.length,
        hosted,
        base64,
        missing,
        needsFix: base64 + missing,
      },
      entries: status,
    });

  } catch (error) {
    console.error("[covers/fix-all] GET Error:", error);
    return NextResponse.json({ error: "Failed to get cover status" }, { status: 500 });
  }
}
src/app/api/covers/set/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry } from "@/lib/net-protocol";

const DISCOVERY_KEY = "discovery-index";

/**
 * POST /api/covers/set
 *
 * Manually set a cover URL for an entry
 *
 * Body:
 * - contentKey: The content key of the entry to update
 * - coverUrl: The new cover URL to set
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { contentKey, coverUrl } = body;

    if (!contentKey || !coverUrl) {
      return NextResponse.json({ error: "Missing contentKey or coverUrl" }, { status: 400 });
    }

    // Fetch current discovery index
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    const entries: DiscoveryEntry[] = result[0]?.value
      ? JSON.parse(result[0].value)
      : [];

    // Find the entry
    const entryIndex = entries.findIndex(e => e.contentKey === contentKey);

    if (entryIndex === -1) {
      return NextResponse.json({ error: "Entry not found" }, { status: 404 });
    }

    // Update cover URL
    entries[entryIndex].coverUrl = coverUrl;

    // Save
    await db.insert(kv).values({
      key: DISCOVERY_KEY,
      value: JSON.stringify(entries),
    }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(entries) },
    });

    return NextResponse.json({
      success: true,
      title: entries[entryIndex].title,
      coverUrl,
    });

  } catch (error) {
    console.error("[covers/set] Error:", error);
    return NextResponse.json({ error: "Failed to set cover" }, { status: 500 });
  }
}

/**
 * PATCH /api/covers/set
 *
 * Copy cover from one entry to another
 *
 * Body:
 * - sourceContentKey: The content key of the entry to copy from
 * - targetContentKey: The content key of the entry to copy to
 */
export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const { sourceContentKey, targetContentKey } = body;

    if (!sourceContentKey || !targetContentKey) {
      return NextResponse.json({ error: "Missing sourceContentKey or targetContentKey" }, { status: 400 });
    }

    // Fetch current discovery index
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    const entries: DiscoveryEntry[] = result[0]?.value
      ? JSON.parse(result[0].value)
      : [];

    // Find source and target entries
    const sourceEntry = entries.find(e => e.contentKey === sourceContentKey);
    const targetIndex = entries.findIndex(e => e.contentKey === targetContentKey);

    if (!sourceEntry) {
      return NextResponse.json({ error: "Source entry not found" }, { status: 404 });
    }

    if (targetIndex === -1) {
      return NextResponse.json({ error: "Target entry not found" }, { status: 404 });
    }

    if (!sourceEntry.coverUrl) {
      return NextResponse.json({ error: "Source entry has no cover" }, { status: 400 });
    }

    // Copy cover URL
    entries[targetIndex].coverUrl = sourceEntry.coverUrl;

    // Save
    await db.insert(kv).values({
      key: DISCOVERY_KEY,
      value: JSON.stringify(entries),
    }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(entries) },
    });

    return NextResponse.json({
      success: true,
      sourceTitle: sourceEntry.title,
      targetTitle: entries[targetIndex].title,
      coverUrl: sourceEntry.coverUrl,
    });

  } catch (error) {
    console.error("[covers/set] PATCH Error:", error);
    return NextResponse.json({ error: "Failed to copy cover" }, { status: 500 });
  }
}
src/app/api/debug-db/route.ts
import { NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";

/* eslint-disable @neynar/no-process-env */
// Debug endpoint to check what's in the KV table
export async function GET() {
  try {
    console.log("[debug-db] Checking DATABASE_URL exists:", !!process.env.DATABASE_URL);
    console.log("[debug-db] DATABASE_URL prefix:", process.env.DATABASE_URL?.slice(0, 30) + "...");

    // Try to list all keys in KV table
    const allKv = await db.select().from(kv);
    console.log("[debug-db] KV entries found:", allKv.length);

    return NextResponse.json({
      success: true,
      hasDbUrl: !!process.env.DATABASE_URL,
      kvCount: allKv.length,
      keys: allKv.map(row => ({
        key: row.key,
        valueLength: row.value?.length || 0,
        valuePreview: row.value?.slice(0, 100) + "...",
      })),
    });
  } catch (error) {
    console.error("[debug-db] Error:", error);
    return NextResponse.json({
      success: false,
      error: error instanceof Error ? error.message : "Unknown error",
      hasDbUrl: !!process.env.DATABASE_URL,
    }, { status: 500 });
  }
}
src/app/api/detect-media-type/route.ts
import { NextRequest, NextResponse } from "next/server";
import { BASE_CHAIN_ID, getRawStorageUrl, createStorageClient } from "@/lib/net-protocol";
import { detectFromBuffer, decodeToBuffer, quickDetectFromBase64Prefix, type DetectedMediaType } from "@/lib/media-type-detector";

// Detect media type for a single content item
// GET /api/detect-media-type?contentKey=0x...&operator=0x...&storageType=xml
export async function GET(request: NextRequest) {
  const contentKey = request.nextUrl.searchParams.get("contentKey");
  const operatorAddress = request.nextUrl.searchParams.get("operator");
  const storageType = request.nextUrl.searchParams.get("storageType") || "regular";

  if (!contentKey || !operatorAddress) {
    return NextResponse.json({ error: "contentKey and operator required" }, { status: 400 });
  }

  try {
    const mediaType = await detectMediaTypeForContent(contentKey, operatorAddress, storageType);

    return NextResponse.json({
      success: true,
      contentKey,
      mediaType,
    });
  } catch (error) {
    console.error("[detect-media-type] Error:", error);
    return NextResponse.json({
      success: false,
      contentKey,
      mediaType: "unknown" as DetectedMediaType,
      error: error instanceof Error ? error.message : "Detection failed",
    });
  }
}

/**
 * Detect media type for a specific content item
 * Fetches enough data to determine the file type without loading the entire file
 */
export async function detectMediaTypeForContent(
  contentKey: string,
  operatorAddress: string,
  storageType: string
): Promise<DetectedMediaType> {
  console.log(`[detect-media-type] Detecting for ${contentKey.slice(0, 20)}... storageType=${storageType}`);

  try {
    let rawData: string | null = null;

    if (storageType === "xml") {
      // XML storage - fetch from SDK
      const storageClient = createStorageClient(BASE_CHAIN_ID);

      try {
        const result = await storageClient.readStorageData({
          key: contentKey,
          operator: operatorAddress,
          keyFormat: "bytes32",
        });

        if (result.data) {
          rawData = result.data;
        }
      } catch (sdkError) {
        console.log("[detect-media-type] SDK read failed, trying raw fetch:", sdkError);

        // Fallback to direct fetch
        const metadataUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${operatorAddress}/${contentKey}`;
        const response = await fetch(metadataUrl);

        if (response.ok) {
          const json = await response.json();
          rawData = json.data;
        }
      }
    } else if (storageType === "chunked") {
      // Chunked storage
      const chunkedUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/chunked-storage/raw/${operatorAddress}/${contentKey}`;
      const response = await fetch(chunkedUrl);

      if (response.ok) {
        const json = await response.json();

        if (json.chunks && Array.isArray(json.chunks) && json.chunks.length > 0) {
          // Just use the first chunk to detect type
          rawData = json.chunks[0];
        }
      }
    } else {
      // Regular storage
      const rawUrl = getRawStorageUrl(BASE_CHAIN_ID, operatorAddress, contentKey);
      const response = await fetch(rawUrl);

      if (response.ok) {
        const json = await response.json();
        rawData = json.data;
      }
    }

    if (!rawData) {
      console.log("[detect-media-type] No data returned");
      return "unknown";
    }

    // Quick check for base64 prefixes
    const quickResult = quickDetectFromBase64Prefix(rawData);
    if (quickResult) {
      console.log(`[detect-media-type] Quick detection: ${quickResult}`);
      return quickResult;
    }

    // Full decode and detect
    const buffer = decodeToBuffer(rawData);
    if (!buffer) {
      console.log("[detect-media-type] Failed to decode to buffer");
      return "unknown";
    }

    const detected = detectFromBuffer(buffer);
    console.log(`[detect-media-type] Detected: ${detected}`);
    return detected;
  } catch (error) {
    console.error("[detect-media-type] Error:", error);
    return "unknown";
  }
}
src/app/api/diagnostics/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiagnosticEvent, ActionCategory } from "@/lib/diagnostics";

// =============================================================================
// COMPREHENSIVE DIAGNOSTICS API
// Stores and retrieves all user action diagnostics
// =============================================================================

const DIAGNOSTICS_KEY = "app-diagnostics";
const MAX_EVENTS = 500; // Keep last 500 events
const MAX_EVENTS_PER_CATEGORY = 100; // Keep last 100 per category for quick queries

interface DiagnosticsStore {
  events: DiagnosticEvent[];
  lastUpdated: number;
  // Quick access indexes
  byCategory: {
    [key in ActionCategory]?: DiagnosticEvent[];
  };
  // Summary stats (updated on each write)
  stats: {
    totalEvents: number;
    eventsByCategory: { [key in ActionCategory]?: number };
    errorRate: number; // Percentage of events that are errors
    last24hEvents: number;
    last24hErrors: number;
  };
}

// Fetch diagnostics from KV
async function fetchDiagnostics(): Promise<DiagnosticsStore> {
  const emptyStore: DiagnosticsStore = {
    events: [],
    lastUpdated: Date.now(),
    byCategory: {},
    stats: {
      totalEvents: 0,
      eventsByCategory: {},
      errorRate: 0,
      last24hEvents: 0,
      last24hErrors: 0,
    },
  };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, DIAGNOSTICS_KEY)).limit(1);
    if (!result[0]?.value) return emptyStore;
    return JSON.parse(result[0].value) as DiagnosticsStore;
  } catch (error) {
    console.error("[diagnostics] fetchDiagnostics error:", error);
    return emptyStore;
  }
}

// Store diagnostics to KV
async function storeDiagnostics(store: DiagnosticsStore): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: DIAGNOSTICS_KEY, value: JSON.stringify(store) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(store) },
    });
    return true;
  } catch (error) {
    console.error("[diagnostics] storeDiagnostics error:", error);
    return false;
  }
}

// Recalculate stats
function recalculateStats(store: DiagnosticsStore): void {
  const now = Date.now();
  const oneDayAgo = now - 24 * 60 * 60 * 1000;

  store.stats.totalEvents = store.events.length;

  // Count by category
  store.stats.eventsByCategory = {};
  for (const event of store.events) {
    store.stats.eventsByCategory[event.category] = (store.stats.eventsByCategory[event.category] || 0) + 1;
  }

  // Calculate error rate
  const errors = store.events.filter(e => e.outcome === "error").length;
  store.stats.errorRate = store.events.length > 0 ? (errors / store.events.length) * 100 : 0;

  // Last 24h stats
  const last24h = store.events.filter(e => e.timestamp > oneDayAgo);
  store.stats.last24hEvents = last24h.length;
  store.stats.last24hErrors = last24h.filter(e => e.outcome === "error").length;

  store.lastUpdated = now;
}

// Update category index
function updateCategoryIndex(store: DiagnosticsStore, event: DiagnosticEvent): void {
  if (!store.byCategory[event.category]) {
    store.byCategory[event.category] = [];
  }

  store.byCategory[event.category]!.push(event);

  // Trim to max per category
  if (store.byCategory[event.category]!.length > MAX_EVENTS_PER_CATEGORY) {
    store.byCategory[event.category] = store.byCategory[event.category]!.slice(-MAX_EVENTS_PER_CATEGORY);
  }
}

// =============================================================================
// API HANDLERS
// =============================================================================

// GET - Query diagnostics
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const category = searchParams.get("category") as ActionCategory | null;
    const action = searchParams.get("action");
    const outcome = searchParams.get("outcome") as DiagnosticEvent["outcome"] | null;
    const walletAddress = searchParams.get("wallet");
    const sessionId = searchParams.get("sessionId");
    const limit = Math.min(parseInt(searchParams.get("limit") || "50", 10), 200);
    const since = searchParams.get("since") ? parseInt(searchParams.get("since")!, 10) : undefined;
    const statsOnly = searchParams.get("statsOnly") === "true";
    const errorsOnly = searchParams.get("errorsOnly") === "true";

    const store = await fetchDiagnostics();

    // Stats only mode
    if (statsOnly) {
      return NextResponse.json({
        stats: store.stats,
        lastUpdated: store.lastUpdated,
        categoryBreakdown: Object.entries(store.stats.eventsByCategory).map(([cat, count]) => ({
          category: cat,
          count,
          recentErrors: store.byCategory[cat as ActionCategory]?.filter(e => e.outcome === "error").length || 0,
        })),
      });
    }

    // Filter events
    let events = category && store.byCategory[category]
      ? store.byCategory[category]!
      : store.events;

    if (action) {
      events = events.filter(e => e.action.includes(action));
    }

    if (outcome) {
      events = events.filter(e => e.outcome === outcome);
    }

    if (errorsOnly) {
      events = events.filter(e => e.outcome === "error");
    }

    if (walletAddress) {
      events = events.filter(e => e.walletAddress?.toLowerCase() === walletAddress.toLowerCase());
    }

    if (sessionId) {
      events = events.filter(e => e.sessionId === sessionId);
    }

    if (since) {
      events = events.filter(e => e.timestamp > since);
    }

    // Return most recent first, limited
    const result = events.slice(-limit).reverse();

    return NextResponse.json({
      events: result,
      total: events.length,
      stats: store.stats,
    });
  } catch (error) {
    console.error("[diagnostics] GET error:", error);
    return NextResponse.json(
      { error: "Failed to retrieve diagnostics" },
      { status: 500 }
    );
  }
}

// POST - Store a diagnostic event
export async function POST(request: NextRequest) {
  try {
    const event = await request.json() as DiagnosticEvent;

    // Validate required fields
    if (!event.eventId || !event.category || !event.action || !event.outcome) {
      return NextResponse.json(
        { error: "Missing required fields: eventId, category, action, outcome" },
        { status: 400 }
      );
    }

    // Get existing store
    const store = await fetchDiagnostics();

    // Add event
    store.events.push(event);

    // Trim to max events
    if (store.events.length > MAX_EVENTS) {
      store.events = store.events.slice(-MAX_EVENTS);
    }

    // Update category index
    updateCategoryIndex(store, event);

    // Recalculate stats
    recalculateStats(store);

    // Store
    await storeDiagnostics(store);

    // Log significant events
    if (event.outcome === "error") {
      console.log(`[diagnostics] ERROR: ${event.category}/${event.action} - ${event.errorMessage || "Unknown error"}`);
    }

    return NextResponse.json({
      success: true,
      eventId: event.eventId,
    });
  } catch (error) {
    console.error("[diagnostics] POST error:", error);
    return NextResponse.json(
      { error: "Failed to store diagnostic event" },
      { status: 500 }
    );
  }
}

// DELETE - Clear diagnostics (admin only, for cleanup)
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const category = searchParams.get("category") as ActionCategory | null;
    const olderThan = searchParams.get("olderThan") ? parseInt(searchParams.get("olderThan")!, 10) : undefined;

    const store = await fetchDiagnostics();

    if (category) {
      // Clear specific category
      store.events = store.events.filter(e => e.category !== category);
      delete store.byCategory[category];
    } else if (olderThan) {
      // Clear events older than timestamp
      store.events = store.events.filter(e => e.timestamp > olderThan);
      // Rebuild category indexes
      store.byCategory = {};
      for (const event of store.events) {
        updateCategoryIndex(store, event);
      }
    } else {
      // Clear all
      store.events = [];
      store.byCategory = {};
    }

    recalculateStats(store);
    await storeDiagnostics(store);

    return NextResponse.json({
      success: true,
      remainingEvents: store.events.length,
    });
  } catch (error) {
    console.error("[diagnostics] DELETE error:", error);
    return NextResponse.json(
      { error: "Failed to clear diagnostics" },
      { status: 500 }
    );
  }
}
src/app/api/discovery/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry } from "@/lib/net-protocol";
import { authenticateCaller, isAuthError, hasPermission } from "@/lib/agent-auth";
import {
  DISCOVERY_INDEX_KEY,
  addDiscoveryEntry,
  updateDiscoveryEntry,
  adminUpdateDiscoveryEntry,
  seedDiscoveryEntries,
} from "@/lib/discovery-ops";

const MEMBER_REGISTRY_KEY = "member-registry";

// Fetch all addresses associated with a user's membership
// This enables cross-platform ownership: a user can manage content from any linked wallet
async function getUserAddressesFromMembership(address: string, fid?: number): Promise<string[]> {
  const addresses = new Set<string>();
  addresses.add(address.toLowerCase());

  try {
    // Fetch member registry
    const result = await db.select().from(kv).where(eq(kv.key, MEMBER_REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) return [address.toLowerCase()];

    const registry = JSON.parse(result[0].value);
    const members = registry.members || [];

    // Find membership by address, linked address, or FID
    for (const member of members) {
      const memberAddr = member.address?.toLowerCase();
      const linkedAddrs = (member.linkedAddresses || []).map((a: string) => a?.toLowerCase()).filter(Boolean);

      // Check if this membership belongs to the user
      const isMatch =
        memberAddr === address.toLowerCase() ||
        linkedAddrs.includes(address.toLowerCase()) ||
        (fid && member.fid === fid);

      if (isMatch) {
        // Add all addresses from this membership
        if (memberAddr) addresses.add(memberAddr);
        linkedAddrs.forEach((a: string) => addresses.add(a));
      }
    }
  } catch (error) {
    console.error("[Discovery] Failed to fetch membership addresses:", error);
  }

  return Array.from(addresses);
}

// Note: Cover art lookups read directly from discovery-index via cover-art-cache.ts
// No separate cache to maintain - discovery-index is the single source of truth

// Initial seed data - books that were uploaded onchain but before local index existed
const INITIAL_BOOKS: DiscoveryEntry[] = [
  {
    contentKey: "0x9011568f42d8a7facb212dce6218e0882014eca80b7a5a244ce23637eba7c1c1",
    metadataKey: "0x9011568f42d8a7facb212dce6218e0882014eca80b7a5a244ce23637eba7c1c1",
    operator: "0x18A432D008a0e5E1D611eae194EE3bdc7FD3f3FA",
    title: "A Christmas Carol",
    author: "Charles Dickens",
    categories: ["classics"],
    fileSize: 1048576, // ~1MB
    storageType: "xml",
    uploadedAt: Date.now(),
  },
];

// Fetch discovery index from KV
async function fetchLocalIndex(): Promise<DiscoveryEntry[]> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_INDEX_KEY)).limit(1);
    if (!result[0]?.value) return [];
    return JSON.parse(result[0].value) as DiscoveryEntry[];
  } catch (error) {
    console.error("fetchLocalIndex error:", error);
    return [];
  }
}


// addEntryAtomically, updateEntryAtomically, adminUpdateDiscoveryEntry, and
// seedDiscoveryEntries are all provided by @/lib/discovery-ops — the single
// source of truth for discovery index mutations.  See that module for docs.

// GET - Fetch all discovery entries
export async function GET(request: NextRequest) {
  try {
    let entries = await fetchLocalIndex();

    // Auto-seed if empty — use seedDiscoveryEntries so per-entry keys are also written
    if (entries.length === 0 && INITIAL_BOOKS.length > 0) {
      await seedDiscoveryEntries(INITIAL_BOOKS);
      entries = INITIAL_BOOKS;
    }

    // ?includeHidden=true is an admin-only parameter — verify ADMIN_SECRET via Authorization header
    // Without valid admin auth, hidden entries are always filtered out regardless of the parameter
    const includeHiddenParam = request.nextUrl.searchParams.get("includeHidden") === "true";
    // eslint-disable-next-line @neynar/no-process-env
    const adminSecret = process.env.ADMIN_SECRET;
    const authHeader = request.headers.get("Authorization") || "";
    const isAdmin = adminSecret && authHeader === `Bearer ${adminSecret}`;
    const includeHidden = includeHiddenParam && isAdmin;
    const visibleEntries = includeHidden ? entries : entries.filter(e => !e.hidden);

    return NextResponse.json({
      success: true,
      entries: visibleEntries,
      count: visibleEntries.length,
      totalCount: entries.length, // Include total count for reference
    });
  } catch (error) {
    console.error("Discovery GET error:", error);
    return NextResponse.json({ error: "Failed to fetch discovery index" }, { status: 500 });
  }
}

// PATCH - Update an existing entry (e.g., cover art, uploader info, hide/unhide, metadata)
// Note: On-chain data is immutable. This updates the DISPLAY metadata stored in KV,
// which is used as an override when displaying items in the UI.
export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      contentKey,
      operator,
      coverUrl,
      cdnUrl,
      uploaderFid,
      uploaderUsername,
      uploaderMemberId,
      uploaderAddress,
      secret,
      hidden,
      mediaType,
      uploadedAt,
      // Editable metadata fields (display overrides)
      title,
      author,
      categories,
      publicationYear,
      publisher,
      isbn,
    } = body;

    // Admin mode: update or remove any entry by contentKey with secret.
    // Uses adminUpdateDiscoveryEntry from discovery-ops so both the full index
    // and the per-entry fast-lookup key are updated atomically.
    // eslint-disable-next-line @neynar/no-process-env
    const adminSecret = process.env.ADMIN_SECRET;
    if (adminSecret && secret === adminSecret && contentKey) {
      const { remove: adminRemove } = body;

      const adminResult = await adminUpdateDiscoveryEntry(contentKey, (entry) => {
        if (adminRemove === true) {
          // Return null to atomically remove from index + delete per-entry key
          return null;
        }

        // Apply all allowed admin field updates
        // Always strip request-only fields that should never be persisted
        const { secret: _s, seed: _sd, ...cleanEntry } = entry as Record<string, unknown>;
        const updated = { ...cleanEntry } as typeof entry;
        if (coverUrl !== undefined) updated.coverUrl = coverUrl || undefined;
        if (cdnUrl !== undefined) updated.cdnUrl = cdnUrl || undefined;
        if (uploaderFid !== undefined) updated.uploaderFid = uploaderFid;
        if (uploaderUsername !== undefined) updated.uploaderUsername = uploaderUsername;
        if (uploaderMemberId !== undefined) updated.uploaderMemberId = uploaderMemberId;
        if (uploaderAddress !== undefined) updated.uploaderAddress = uploaderAddress;
        if (hidden !== undefined) {
          updated.hidden = hidden;
          updated.hiddenAt = hidden ? Date.now() : undefined;
        }
        if (title !== undefined && title.trim()) updated.title = title.trim();
        if (author !== undefined && author.trim()) updated.author = author.trim();
        if (categories !== undefined && Array.isArray(categories)) updated.categories = categories;
        if (publicationYear !== undefined) updated.publicationYear = publicationYear || undefined;
        if (publisher !== undefined) updated.publisher = publisher || undefined;
        if (isbn !== undefined) updated.isbn = isbn || undefined;
        // Admin-only: correct mediaType and uploadedAt for manually-registered entries
        if (mediaType !== undefined) updated.mediaType = mediaType === "document" ? "text" : mediaType;
        if (uploadedAt !== undefined && typeof uploadedAt === "number") updated.uploadedAt = uploadedAt;
        return updated;
      });

      if (!adminResult.success) {
        const status = adminResult.error?.includes("not found") ? 404 : 500;
        return NextResponse.json({ error: adminResult.error || "Failed to update entry" }, { status });
      }

      if (adminResult.removed) {
        console.log(`[Discovery Admin] Removed entry: ${contentKey}`);
        return NextResponse.json({ success: true, removed: true, contentKey });
      }

      return NextResponse.json({ success: true, entry: adminResult.entry });
    }

    // Regular mode: user updating their own entry
    const { remove, fid } = body;

    if (!contentKey || !operator) {
      return NextResponse.json({ error: "Missing contentKey or operator" }, { status: 400 });
    }

    // Get all addresses associated with this user's membership (cross-platform support)
    // This allows users to manage content uploaded from any of their linked wallets
    const userAddresses = await getUserAddressesFromMembership(operator, fid);
    console.log(`[Discovery PATCH] User addresses for cross-platform check:`, userAddresses);

    // Use atomic update from discovery-ops to prevent race conditions
    const result = await updateDiscoveryEntry(contentKey, userAddresses, (entry) => {
      // Handle removal - return null to remove the entry
      if (remove === true) {
        console.log(`[Discovery] Removing entry: ${entry.title} (${contentKey})`);
        return null;
      }

      // Update the entry - all editable fields
      const updated = { ...entry };

      if (coverUrl !== undefined) updated.coverUrl = coverUrl || undefined;
      if (cdnUrl !== undefined) updated.cdnUrl = cdnUrl || undefined;
      // Users can hide/unhide their own entries (or entries they imported)
      if (hidden !== undefined) {
        updated.hidden = hidden;
        updated.hiddenAt = hidden ? Date.now() : undefined;
      }
      // Editable metadata fields - these are display overrides
      if (title !== undefined && title.trim()) updated.title = title.trim();
      if (author !== undefined && author.trim()) updated.author = author.trim();
      if (categories !== undefined && Array.isArray(categories)) updated.categories = categories;
      if (publicationYear !== undefined) updated.publicationYear = publicationYear || undefined;
      if (publisher !== undefined) updated.publisher = publisher || undefined;
      if (isbn !== undefined) updated.isbn = isbn || undefined;

      return updated;
    });

    if (!result.success) {
      const status = result.error?.includes("not found") ? 404 : 500;
      return NextResponse.json({ error: result.error || "Failed to update entry" }, { status });
    }

    if (result.removed) {
      return NextResponse.json({
        success: true,
        removed: true,
        contentKey,
      });
    }

    return NextResponse.json({
      success: true,
      entry: result.entry,
    });
  } catch (error) {
    console.error("Discovery PATCH error:", error);
    return NextResponse.json({ error: "Failed to update entry" }, { status: 500 });
  }
}

// POST - Add a new entry to the discovery index
// Requires either: ADMIN_SECRET in body, OR valid agent Bearer token with library:write permission
export async function POST(request: NextRequest) {
  try {
    // Read body as text so we can both inspect it and parse it
    const rawBody = await request.text();
    let body: Record<string, unknown>;
    try {
      body = JSON.parse(rawBody);
    } catch {
      return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
    }

    // Support seed mode with secret - require ADMIN_SECRET environment variable
    // eslint-disable-next-line @neynar/no-process-env
    if (body.seed && process.env.ADMIN_SECRET && body.secret === process.env.ADMIN_SECRET) {
      const entries = body.entries as DiscoveryEntry[];
      if (!entries || entries.length === 0) {
        return NextResponse.json({ error: "No entries to seed" }, { status: 400 });
      }

      // seedDiscoveryEntries atomically deduplicates and writes both the full index
      // and per-entry fast-lookup keys for every newly-added entry.
      const seedResult = await seedDiscoveryEntries(entries);
      if (!seedResult.success) {
        return NextResponse.json({ error: seedResult.error || "Failed to seed entries" }, { status: 500 });
      }

      return NextResponse.json({
        success: true,
        added: seedResult.added,
        total: seedResult.total,
      });
    }

    // Admin key in body (non-seed single-entry admin path)
    // eslint-disable-next-line @neynar/no-process-env
    const adminSecret = process.env.ADMIN_SECRET;
    const isAdminRequest = adminSecret && body.secret === adminSecret;

    if (!isAdminRequest) {
      // Accept: Bearer token (agents) OR fid/address in body (app users uploading their own content)
      // authenticateCaller handles both paths — Bearer agents need library:write,
      // fid/address callers are regular users and are always allowed to add their own entries.
      const authResult = await authenticateCaller(request, body);
      if (isAuthError(authResult)) {
        return NextResponse.json(
          { error: "Unauthorized. Sign in via the app or provide a valid Bearer token." },
          { status: 401 }
        );
      }
      // Agents using Bearer tokens still need library:write permission
      if (authResult.type === "bearer" && !hasPermission(authResult.agent, "library:write")) {
        return NextResponse.json(
          { error: "Forbidden. library:write permission required." },
          { status: 403 }
        );
      }
    }

    // Strip request-only auth/control fields that must never be persisted in the entry
    const { secret: _secret, seed: _seed, fid: _fid, address: _address, ...entryFields } = body;
    const entry = entryFields as unknown as DiscoveryEntry;
    // Ensure categories is always an array to prevent downstream iteration errors
    if (!Array.isArray(entry.categories)) entry.categories = [];
    // Normalize invalid mediaType values: "document" is not a valid viewer type — store as "text"
    if (entry.mediaType === ("document" as string)) entry.mediaType = "text";

    if (!entry.contentKey || !entry.title || !entry.operator) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
    }

    // Use atomic add from discovery-ops to prevent race conditions and keep per-entry keys in sync
    const result = await addDiscoveryEntry(entry);

    if (!result.success) {
      console.error("[Discovery] Atomic add failed:", result.error);
      return NextResponse.json({ error: result.error || "Failed to store" }, { status: 500 });
    }

    if (result.isDuplicate) {
      return NextResponse.json({
        success: true,
        message: "Entry already exists",
        count: result.count,
      });
    }

    return NextResponse.json({
      success: true,
      entry,
      count: result.count,
    });
  } catch (error) {
    console.error("Discovery POST error:", error);
    return NextResponse.json({ error: "Failed to add entry" }, { status: 500 });
  }
}
src/app/api/engagement/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

const ENGAGEMENT_KV_KEY = "net-library-engagement";

// How long someone is considered "currently reading" (5 minutes)
const READING_THRESHOLD_MS = 5 * 60 * 1000;

interface BookEngagement {
  contentKey: string;
  opens: number;
  // Track who is currently reading with timestamps
  currentReaders: { [address: string]: number };
  // Track which users have this in their queue
  queuedBy: string[];
  lastUpdated: number;
}

interface EngagementIndex {
  books: { [contentKey: string]: BookEngagement };
  lastUpdated: number;
}

// Helper to fetch engagement index from KV database
async function fetchEngagementIndex(): Promise<EngagementIndex> {
  const emptyIndex: EngagementIndex = {
    books: {},
    lastUpdated: Date.now(),
  };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, ENGAGEMENT_KV_KEY)).limit(1);
    if (!result[0]?.value) return emptyIndex;
    return JSON.parse(result[0].value) as EngagementIndex;
  } catch {
    return emptyIndex;
  }
}

// Helper to store engagement index to KV database
async function storeEngagementIndex(index: EngagementIndex): Promise<boolean> {
  try {
    await db.insert(kv).values({
      key: ENGAGEMENT_KV_KEY,
      value: JSON.stringify(index),
    }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(index) },
    });
    return true;
  } catch (error) {
    console.error("storeEngagementIndex error:", error);
    return false;
  }
}

// Clean up stale readers
function cleanupStaleReaders(engagement: BookEngagement): BookEngagement {
  const now = Date.now();
  const activeReaders: { [address: string]: number } = {};

  for (const [address, timestamp] of Object.entries(engagement.currentReaders)) {
    if (now - timestamp < READING_THRESHOLD_MS) {
      activeReaders[address] = timestamp;
    }
  }

  return { ...engagement, currentReaders: activeReaders };
}

// Get or create book engagement entry
function getBookEngagement(index: EngagementIndex, contentKey: string): BookEngagement {
  if (!index.books[contentKey]) {
    index.books[contentKey] = {
      contentKey,
      opens: 0,
      currentReaders: {},
      queuedBy: [],
      lastUpdated: Date.now(),
    };
  }
  return cleanupStaleReaders(index.books[contentKey]);
}

// GET - Fetch engagement stats for a book or multiple books
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const contentKey = searchParams.get("contentKey");
  const contentKeys = searchParams.get("contentKeys"); // comma-separated list
  const uploaderAddress = searchParams.get("uploader")?.toLowerCase();

  const index = await fetchEngagementIndex();

  if (contentKey) {
    // Single book
    const engagement = getBookEngagement(index, contentKey);
    const activeReaders = Object.keys(engagement.currentReaders).length;

    return NextResponse.json({
      contentKey,
      opens: engagement.opens,
      currentlyReading: activeReaders,
      addedToQueues: engagement.queuedBy.length,
    });
  }

  if (contentKeys) {
    // Multiple books
    const keys = contentKeys.split(",");
    const stats: { [key: string]: { opens: number; currentlyReading: number; addedToQueues: number } } = {};

    for (const key of keys) {
      const engagement = getBookEngagement(index, key);
      const activeReaders = Object.keys(engagement.currentReaders).length;
      stats[key] = {
        opens: engagement.opens,
        currentlyReading: activeReaders,
        addedToQueues: engagement.queuedBy.length,
      };
    }

    return NextResponse.json({ stats });
  }

  if (uploaderAddress) {
    // Get aggregate stats for all books by an uploader
    // Note: This requires knowing which books belong to the uploader
    // For now, return empty - the client can aggregate from individual book stats
    return NextResponse.json({
      message: "Use contentKeys param with comma-separated list of uploader's content keys",
    });
  }

  // Return global engagement summary
  const allBooks = Object.values(index.books);
  const now = Date.now();

  let totalOpens = 0;
  let totalCurrentlyReading = 0;
  let totalQueued = 0;

  for (const book of allBooks) {
    totalOpens += book.opens;
    totalQueued += book.queuedBy.length;

    // Count active readers
    for (const timestamp of Object.values(book.currentReaders)) {
      if (now - timestamp < READING_THRESHOLD_MS) {
        totalCurrentlyReading++;
      }
    }
  }

  return NextResponse.json({
    totalBooks: allBooks.length,
    totalOpens,
    totalCurrentlyReading,
    totalQueued,
    lastUpdated: index.lastUpdated,
  });
}

// POST - Record engagement events
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { action, contentKey, userAddress } = body;

    if (!contentKey) {
      return NextResponse.json({ error: "contentKey required" }, { status: 400 });
    }

    const index = await fetchEngagementIndex();
    const engagement = getBookEngagement(index, contentKey);

    switch (action) {
      case "open": {
        // Record a book being opened/viewed
        engagement.opens += 1;
        break;
      }

      case "start-reading": {
        // User started reading - track them as active reader
        if (!userAddress) {
          return NextResponse.json({ error: "userAddress required" }, { status: 400 });
        }
        engagement.currentReaders[userAddress.toLowerCase()] = Date.now();
        break;
      }

      case "stop-reading": {
        // User stopped reading - remove from active readers
        if (!userAddress) {
          return NextResponse.json({ error: "userAddress required" }, { status: 400 });
        }
        delete engagement.currentReaders[userAddress.toLowerCase()];
        break;
      }

      case "heartbeat": {
        // Heartbeat to keep reader status active
        if (!userAddress) {
          return NextResponse.json({ error: "userAddress required" }, { status: 400 });
        }
        const addr = userAddress.toLowerCase();
        if (engagement.currentReaders[addr]) {
          engagement.currentReaders[addr] = Date.now();
        }
        break;
      }

      case "add-to-queue": {
        // User added to their queue
        if (!userAddress) {
          return NextResponse.json({ error: "userAddress required" }, { status: 400 });
        }
        const addr = userAddress.toLowerCase();
        if (!engagement.queuedBy.includes(addr)) {
          engagement.queuedBy.push(addr);
        }
        break;
      }

      case "remove-from-queue": {
        // User removed from their queue
        if (!userAddress) {
          return NextResponse.json({ error: "userAddress required" }, { status: 400 });
        }
        const addr = userAddress.toLowerCase();
        engagement.queuedBy = engagement.queuedBy.filter((a) => a !== addr);
        break;
      }

      default:
        return NextResponse.json({ error: "Invalid action" }, { status: 400 });
    }

    engagement.lastUpdated = Date.now();
    index.books[contentKey] = engagement;
    index.lastUpdated = Date.now();

    await storeEngagementIndex(index);

    // Return updated stats
    const activeReaders = Object.keys(engagement.currentReaders).length;

    return NextResponse.json({
      success: true,
      stats: {
        opens: engagement.opens,
        currentlyReading: activeReaders,
        addedToQueues: engagement.queuedBy.length,
      },
    });
  } catch (error) {
    console.error("Engagement error:", error);
    return NextResponse.json({ error: "Failed to record engagement" }, { status: 500 });
  }
}
src/app/api/grids/archive/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { keccak256, encodePacked } from "viem";
import {
  type Grid,
  type GridCells,
  type ArchivedGrid,
  GRIDS_KV_KEYS,
  isMember,
  isMemberByFid,
  type MemberRegistry,
} from "@/lib/net-protocol";

const MEMBER_REGISTRY_KEY = "member-registry";

// Helper: Get KV value
async function getKV<T>(key: string): Promise<T | null> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, key)).limit(1);
    if (!result[0]?.value) return null;
    return JSON.parse(result[0].value) as T;
  } catch (error) {
    console.error(`[getKV] Error fetching ${key}:`, error);
    return null;
  }
}

// Helper: Set KV value
async function setKV(key: string, value: unknown): Promise<boolean> {
  try {
    const jsonValue = JSON.stringify(value);
    await db.insert(kv).values({ key, value: jsonValue }).onConflictDoUpdate({
      target: kv.key,
      set: { value: jsonValue },
    });
    return true;
  } catch (error) {
    console.error(`[setKV] Error storing ${key}:`, error);
    return false;
  }
}

// Helper: Fetch member registry
async function fetchMemberRegistry(): Promise<MemberRegistry> {
  const emptyRegistry: MemberRegistry = {
    members: [],
    nextMemberId: 1,
    lastUpdated: Date.now(),
  };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, MEMBER_REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) return emptyRegistry;
    return JSON.parse(result[0].value) as MemberRegistry;
  } catch (error) {
    console.error("[fetchMemberRegistry] Error:", error);
    return emptyRegistry;
  }
}

// Helper: Check membership
async function checkMembership(address: string, fid?: number): Promise<boolean> {
  const registry = await fetchMemberRegistry();
  const memberByAddress = isMember(registry, address);
  if (memberByAddress) return true;
  if (fid) {
    const memberByFidResult = isMemberByFid(registry, fid);
    if (memberByFidResult) return true;
  }
  return false;
}

// Generate archive ID
function generateArchiveId(gridId: string, timestamp: number): `0x${string}` {
  return keccak256(
    encodePacked(
      ["bytes32", "uint256"],
      [gridId as `0x${string}`, BigInt(timestamp)]
    )
  );
}

// GET: Fetch archived grids
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const archiveId = searchParams.get("id");
  const gridId = searchParams.get("gridId"); // Get archives for a specific grid
  const creator = searchParams.get("creator"); // Get all archives by creator

  try {
    // Single archive by ID
    if (archiveId) {
      const archive = await getKV<ArchivedGrid>(GRIDS_KV_KEYS.archive(archiveId));
      if (!archive) {
        return NextResponse.json({ success: false, error: "Archive not found" }, { status: 404 });
      }

      return NextResponse.json({
        success: true,
        archive,
      });
    }

    // Archives for a specific grid
    if (gridId) {
      const allArchiveIds = await getKV<string[]>(GRIDS_KV_KEYS.ARCHIVED_REGISTRY) || [];
      const archives: ArchivedGrid[] = [];

      for (const id of allArchiveIds) {
        const archive = await getKV<ArchivedGrid>(GRIDS_KV_KEYS.archive(id));
        if (archive && archive.gridId === gridId) {
          archives.push(archive);
        }
      }

      // Sort by archived date (newest first)
      archives.sort((a, b) => b.archivedAt - a.archivedAt);

      return NextResponse.json({
        success: true,
        archives,
      });
    }

    // Archives by creator
    if (creator) {
      const userArchiveIds = await getKV<string[]>(GRIDS_KV_KEYS.userArchivedGrids(creator)) || [];
      const archives: ArchivedGrid[] = [];

      for (const id of userArchiveIds) {
        const archive = await getKV<ArchivedGrid>(GRIDS_KV_KEYS.archive(id));
        if (archive) {
          archives.push(archive);
        }
      }

      // Sort by archived date (newest first)
      archives.sort((a, b) => b.archivedAt - a.archivedAt);

      return NextResponse.json({
        success: true,
        archives,
      });
    }

    return NextResponse.json(
      { success: false, error: "Missing id, gridId, or creator parameter" },
      { status: 400 }
    );
  } catch (error) {
    console.error("[GET /api/grids/archive] Error:", error);
    return NextResponse.json({ success: false, error: "Internal error" }, { status: 500 });
  }
}

// POST: Create archive
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { gridId, creator, creatorFid, contentKey, cdnUrl, fileName, operator } = body;

    if (!gridId || !creator) {
      return NextResponse.json(
        { success: false, error: "Grid ID and creator are required" },
        { status: 400 }
      );
    }

    // Check membership
    const memberStatus = await checkMembership(creator, creatorFid);
    if (!memberStatus) {
      return NextResponse.json(
        { success: false, error: "Archives are a member-only feature" },
        { status: 403 }
      );
    }

    // Fetch grid
    const grid = await getKV<Grid>(GRIDS_KV_KEYS.grid(gridId));
    if (!grid || grid.deleted) {
      return NextResponse.json({ success: false, error: "Grid not found" }, { status: 404 });
    }

    // Verify ownership
    if (grid.creator.toLowerCase() !== creator.toLowerCase()) {
      return NextResponse.json({ success: false, error: "Not authorized" }, { status: 403 });
    }

    // Fetch cells
    const cells = await getKV<GridCells>(GRIDS_KV_KEYS.gridCells(gridId));
    if (!cells || cells.cells.length === 0) {
      return NextResponse.json(
        { success: false, error: "Cannot archive an empty grid" },
        { status: 400 }
      );
    }

    // Generate archive ID
    const timestamp = Date.now();
    const archiveId = generateArchiveId(gridId, timestamp);

    // Build searchable text from cell metadata
    const searchParts: string[] = [grid.name];
    for (const cell of cells.cells) {
      if (cell.title) searchParts.push(cell.title);
      if (cell.cdnUrl) {
        // Extract filename from URL for search
        try {
          const url = new URL(cell.cdnUrl);
          const filename = url.pathname.split("/").pop() || "";
          if (filename) searchParts.push(filename);
        } catch {
          // Invalid URL, skip
        }
      }
    }
    const searchText = searchParts.join(" ").toLowerCase();

    // Create archive object
    const archive: ArchivedGrid = {
      id: archiveId,
      gridId,
      gridName: grid.name,
      gridSize: grid.size,
      cellCount: cells.cells.length,
      archivedAt: timestamp,
      contentKey: contentKey || undefined, // Set when uploading to Net Protocol
      cdnUrl: cdnUrl || undefined, // Full CDN URL for the archived PNG
      fileName: fileName || undefined, // Original filename for CDN URL format
      operator: operator || creator.toLowerCase(), // Operator (uploader) address
      creator: creator.toLowerCase(),
      creatorFid,
      searchText,
    };

    // Store archive
    await setKV(GRIDS_KV_KEYS.archive(archiveId), archive);

    // Add to global archived registry
    const allArchives = await getKV<string[]>(GRIDS_KV_KEYS.ARCHIVED_REGISTRY) || [];
    allArchives.push(archiveId);
    await setKV(GRIDS_KV_KEYS.ARCHIVED_REGISTRY, allArchives);

    // Add to user's archived grids
    const userArchives = await getKV<string[]>(GRIDS_KV_KEYS.userArchivedGrids(creator)) || [];
    userArchives.push(archiveId);
    await setKV(GRIDS_KV_KEYS.userArchivedGrids(creator), userArchives);

    return NextResponse.json({
      success: true,
      archive,
      cells: cells.cells, // Return cells for reference
    });
  } catch (error) {
    console.error("[POST /api/grids/archive] Error:", error);
    return NextResponse.json({ success: false, error: "Internal error" }, { status: 500 });
  }
}
src/app/api/grids/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import {
  type Grid,
  type GridWithStats,
  type GridCell,
  type GridCells,
  type GridMediaType,
  type ArchivedGrid,
  GRIDS_KV_KEYS,
  generateGridId,
  requiresGridUnlock,
  GRID_UNLOCK_PRICE_USD,
  isMember,
  isMemberByFid,
  type MemberRegistry,
  generateGridScoreKey,
  detectGridMediaType,
} from "@/lib/net-protocol";
import { createPublicClient, http } from "viem";
import { base } from "viem/chains";
import { verifyUsdcPayment, markTxUsed } from "@/lib/agent-auth";

// Constants
const MEMBER_REGISTRY_KEY = "member-registry";
const SCORE_CONTRACT = "0x0000000FA09B022E5616E5a173b4b67FA2FBcF28" as const;
const PURE_ALPHA_STRATEGY = "0x00000001b1bcdeddeafd5296aaf4f3f3e21ae876" as const;

// ABI for Score contract (querying)
const SCORE_ABI = [
  {
    name: "getStrategyKeyScores",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "strategy", type: "address" },
      { name: "scoreKeys", type: "bytes32[]" },
    ],
    outputs: [{ name: "counts", type: "int256[]" }],
  },
] as const;

// Create viem client for reading scores
const publicClient = createPublicClient({
  chain: base,
  transport: http(),
});

// Helper: Fetch upvote count for a grid
async function getGridUpvoteCount(gridId: string, creator: string): Promise<number> {
  try {
    const scoreKey = generateGridScoreKey(gridId, creator);
    const result = await publicClient.readContract({
      address: SCORE_CONTRACT,
      abi: SCORE_ABI,
      functionName: "getStrategyKeyScores",
      args: [PURE_ALPHA_STRATEGY, [scoreKey]],
    });

    const count = result[0];
    return count > 0 ? Number(count) : 0;
  } catch (error) {
    console.error("[getGridUpvoteCount] Error:", error);
    return 0;
  }
}

// Helper: Batch fetch upvote counts for multiple grids
async function getGridUpvoteCounts(grids: Array<{ id: string; creator: string }>): Promise<Map<string, number>> {
  const counts = new Map<string, number>();

  if (grids.length === 0) return counts;

  try {
    const scoreKeys = grids.map(g => generateGridScoreKey(g.id, g.creator));
    const result = await publicClient.readContract({
      address: SCORE_CONTRACT,
      abi: SCORE_ABI,
      functionName: "getStrategyKeyScores",
      args: [PURE_ALPHA_STRATEGY, scoreKeys],
    });

    grids.forEach((grid, index) => {
      const count = result[index];
      counts.set(grid.id, count > 0 ? Number(count) : 0);
    });
  } catch (error) {
    console.error("[getGridUpvoteCounts] Error:", error);
    // Initialize all to 0 on error
    grids.forEach(g => counts.set(g.id, 0));
  }

  return counts;
}

// Helper: Get KV value
async function getKV<T>(key: string): Promise<T | null> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, key)).limit(1);
    if (!result[0]?.value) return null;
    return JSON.parse(result[0].value) as T;
  } catch (error) {
    console.error(`[getKV] Error fetching ${key}:`, error);
    return null;
  }
}

// Helper: Set KV value
async function setKV(key: string, value: unknown): Promise<boolean> {
  try {
    const jsonValue = JSON.stringify(value);
    await db.insert(kv).values({ key, value: jsonValue }).onConflictDoUpdate({
      target: kv.key,
      set: { value: jsonValue },
    });
    return true;
  } catch (error) {
    console.error(`[setKV] Error storing ${key}:`, error);
    return false;
  }
}

// Helper: Fetch member registry
async function fetchMemberRegistry(): Promise<MemberRegistry> {
  const emptyRegistry: MemberRegistry = {
    members: [],
    nextMemberId: 1,
    lastUpdated: Date.now(),
  };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, MEMBER_REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) return emptyRegistry;
    return JSON.parse(result[0].value) as MemberRegistry;
  } catch (error) {
    console.error("[fetchMemberRegistry] Error:", error);
    return emptyRegistry;
  }
}

// Helper: Check if user is a member
async function checkMembership(address: string, fid?: number): Promise<boolean> {
  const registry = await fetchMemberRegistry();
  const memberByAddress = isMember(registry, address);
  if (memberByAddress) return true;
  if (fid) {
    const memberByFidResult = isMemberByFid(registry, fid);
    if (memberByFidResult) return true;
  }
  return false;
}

// Helper: Resolve creator info from member registry
async function resolveCreatorInfo(address: string): Promise<{ username?: string; pfpUrl?: string; fid?: number }> {
  try {
    const registry = await fetchMemberRegistry();
    const normalizedAddress = address.toLowerCase();

    // Find member by address
    const member = registry.members.find(m => m.address.toLowerCase() === normalizedAddress);
    if (member) {
      return {
        username: member.username || member.ensSubname,
        pfpUrl: undefined, // Registry doesn't store pfp, will be fetched client-side if needed
        fid: member.fid,
      };
    }

    return {};
  } catch (error) {
    console.error("[resolveCreatorInfo] Error:", error);
    return {};
  }
}

// Helper: Enrich cells with coverUrl, contentKey, title, and mediaType from discovery index
async function enrichCellsWithMetadata(cells: GridCell[]): Promise<GridCell[]> {
  // If no cells, return early
  if (!cells || cells.length === 0) return cells || [];

  try {
    // Get discovery index once
    // Note: DiscoveryEntry uses 'mediaType' for type category (audio/video/image/etc)
    // and 'storageType' for how the file is stored (regular/chunked/xml)
    const discoveryIndex = await getKV<Array<{
      contentKey?: string;
      operator?: string;
      cdnUrl?: string;
      coverUrl?: string;
      title?: string;
      mediaType?: "pdf" | "image" | "audio" | "video" | "text" | "unknown";
      storageType?: "regular" | "chunked" | "xml";
    }>>("discovery-index") || [];

    console.log("[enrichCellsWithMetadata] Enriching", cells.length, "cells with", discoveryIndex.length, "discovery entries");

    return cells.map(cell => {
      // Skip if cell has no cdnUrl
      if (!cell.cdnUrl) return cell;

      // Try to find matching entry in discovery index
      // Use case-insensitive matching for hex content keys
      const cellUrlLower = cell.cdnUrl.toLowerCase();
      const matchingEntry = discoveryIndex.find(entry => {
        // Match by contentKey in cdnUrl (case-insensitive for hex keys)
        if (entry.contentKey && cellUrlLower.includes(entry.contentKey.toLowerCase())) return true;
        // Match by operator + contentKey (case-insensitive)
        if (entry.operator && entry.contentKey &&
            cellUrlLower.includes(entry.operator.toLowerCase()) &&
            cellUrlLower.includes(entry.contentKey.toLowerCase())) return true;
        // Match by cdnUrl
        if (entry.cdnUrl && (
          cellUrlLower.includes(entry.cdnUrl.toLowerCase()) ||
          entry.cdnUrl.toLowerCase().includes(cellUrlLower) ||
          normalizeCdnUrl(cell.cdnUrl) === normalizeCdnUrl(entry.cdnUrl || '')
        )) return true;
        return false;
      });

      if (matchingEntry) {
        console.log("[enrichCellsWithMetadata] Matched cell:", cell.cdnUrl.slice(0, 80), "-> mediaType:", matchingEntry.mediaType);
      } else {
        // Log when no match found to help debug
        console.log("[enrichCellsWithMetadata] NO MATCH for cell:", cell.cdnUrl.slice(0, 80));
      }

      if (matchingEntry) {
        // Enrich cell with metadata from discovery index
        const enriched = { ...cell };

        // Add coverUrl if missing
        if (!enriched.coverUrl && matchingEntry.coverUrl) {
          enriched.coverUrl = matchingEntry.coverUrl;
        }

        // Add contentKey if missing (critical for navigation to item detail)
        if (!enriched.contentKey && matchingEntry.contentKey) {
          enriched.contentKey = matchingEntry.contentKey;
        }

        // Add title if missing
        if (!enriched.title && matchingEntry.title) {
          enriched.title = matchingEntry.title;
        }

        // Add operator if missing (needed for raw media URLs)
        if (!enriched.operator && matchingEntry.operator) {
          enriched.operator = matchingEntry.operator;
        }

        // Add storageType if missing (needed for proper content reconstruction in media proxy)
        if (!enriched.storageType && matchingEntry.storageType) {
          enriched.storageType = matchingEntry.storageType;
        }

        // ALWAYS update mediaType and contentType from discovery index
        // This fixes cells that were saved with wrong defaults (e.g., image/png for audio files)
        // Discovery uses: "pdf" | "image" | "audio" | "video" | "text" | "unknown"
        // GridCell uses: "image" | "gif" | "video" | "audio" | "text"
        if (matchingEntry.mediaType) {
          const discoveryType = matchingEntry.mediaType;
          if (discoveryType === "video") {
            enriched.mediaType = "video";
            enriched.contentType = "video/mp4";
          } else if (discoveryType === "audio") {
            enriched.mediaType = "audio";
            enriched.contentType = "audio/mpeg";
          } else if (discoveryType === "image") {
            // Check if it's a GIF based on coverUrl or cdnUrl
            const urlToCheck = (enriched.cdnUrl || '').toLowerCase();
            enriched.mediaType = urlToCheck.includes('.gif') ? "gif" : "image";
          } else if (discoveryType === "text") {
            enriched.mediaType = "text";
            enriched.contentType = "text/plain";
          }
          // "pdf" and "unknown" default to image display in grid
        }

        return enriched;
      }

      // No match in discovery index - try to extract operator/contentKey from URL patterns
      // This allows media playback for cells that aren't in the discovery index
      if (!cell.operator || !cell.contentKey) {
        const enriched = { ...cell };
        const url = cell.cdnUrl;

        // Pattern: /storage/raw/{operator}/{contentKey} or /storage/load/{operator}/{contentKey}
        const storageMatch = url.match(/storage\/(?:raw|load)\/([^/]+)\/([^/?#]+)/);
        if (storageMatch) {
          if (!enriched.operator) enriched.operator = storageMatch[1];
          if (!enriched.contentKey) enriched.contentKey = storageMatch[2];
          console.log("[enrichCellsWithMetadata] Extracted from storage URL:", enriched.operator?.slice(0,10), enriched.contentKey?.slice(0,20));
          return enriched;
        }

        // Pattern: /chunked-storage/file/{operator}/{contentKey}
        const chunkedMatch = url.match(/chunked-storage\/(?:file|raw)\/([^/]+)\/([^/?#]+)/);
        if (chunkedMatch) {
          if (!enriched.operator) enriched.operator = chunkedMatch[1];
          if (!enriched.contentKey) enriched.contentKey = chunkedMatch[2];
          enriched.storageType = enriched.storageType || "xml";
          console.log("[enrichCellsWithMetadata] Extracted from chunked URL:", enriched.operator?.slice(0,10), enriched.contentKey?.slice(0,20));
          return enriched;
        }

        // Pattern: /content/{contentKey} - can only extract contentKey, not operator
        const contentMatch = url.match(/storedon\.net\/content\/(0x[a-fA-F0-9]+)/i);
        if (contentMatch) {
          if (!enriched.contentKey) enriched.contentKey = contentMatch[1];
          console.log("[enrichCellsWithMetadata] Extracted contentKey from /content/ URL:", enriched.contentKey?.slice(0,20), "- operator still missing!");
          return enriched;
        }
      }

      return cell;
    });
  } catch (error) {
    console.error("[enrichCellsWithMetadata] Error:", error);
    // Return cells unchanged on error
    return cells;
  }
}

// Keep alias for backwards compatibility
const enrichCellsWithCovers = enrichCellsWithMetadata;

// Helper: Normalize CDN URL for comparison
function normalizeCdnUrl(url: string): string {
  if (!url) return '';
  const normalized = url.trim().toLowerCase().replace(/\/+$/, "");
  // Extract content key from various URL formats
  const keyMatch = normalized.match(/0x[a-fA-F0-9]+/);
  return keyMatch ? keyMatch[0] : normalized;
}

// Helper: Check if a grid has been archived
async function getGridArchiveCount(gridId: string): Promise<number> {
  try {
    const allArchiveIds = await getKV<string[]>(GRIDS_KV_KEYS.ARCHIVED_REGISTRY) || [];
    let count = 0;
    for (const id of allArchiveIds) {
      const archive = await getKV<ArchivedGrid>(GRIDS_KV_KEYS.archive(id));
      if (archive && archive.gridId === gridId) {
        count++;
      }
    }
    return count;
  } catch {
    return 0;
  }
}

// Helper: Get grid with stats (with optional pre-fetched upvote count and creator info)
async function getGridWithStats(
  grid: Grid,
  upvoteCount?: number,
  creatorInfo?: { username?: string; pfpUrl?: string; fid?: number }
): Promise<GridWithStats> {
  const cellsData = await getKV<GridCells>(GRIDS_KV_KEYS.gridCells(grid.id));
  const rawCells = cellsData?.cells || [];
  const cellCount = rawCells.length;
  const gridSize = grid.size || 3;
  const totalCells = gridSize * gridSize;

  // Get first 9 cells for preview and enrich with coverUrls
  const previewCells = await enrichCellsWithCovers(rawCells.slice(0, 9));

  // Fetch upvote count if not provided
  const finalUpvoteCount = upvoteCount ?? await getGridUpvoteCount(grid.id, grid.creator);

  // Resolve creator info if not provided
  const finalCreatorInfo = creatorInfo ?? await resolveCreatorInfo(grid.creator);

  // Check archive status
  const archiveCount = await getGridArchiveCount(grid.id);

  return {
    ...grid,
    cellCount,
    totalCells,
    upvoteCount: finalUpvoteCount,
    previewCells,
    creatorUsername: finalCreatorInfo.username,
    creatorPfpUrl: finalCreatorInfo.pfpUrl,
    creatorFid: finalCreatorInfo.fid,
    isArchived: archiveCount > 0,
    archiveCount,
  };
}

// GET: Fetch grids
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const gridId = searchParams.get("id");
  const creator = searchParams.get("creator");
  const visibility = searchParams.get("visibility"); // "public" | "hidden" | "all"
  const sortBy = searchParams.get("sortBy"); // "upvotes" | "recent"
  const page = parseInt(searchParams.get("page") || "1", 10);
  const pageSize = parseInt(searchParams.get("pageSize") || "20", 10);
  const viewer = searchParams.get("viewer"); // Current viewer's address

  try {
    // Single grid by ID
    if (gridId) {
      const grid = await getKV<Grid>(GRIDS_KV_KEYS.grid(gridId));
      if (!grid || grid.deleted) {
        return NextResponse.json({ success: false, error: "Grid not found" }, { status: 404 });
      }

      // Check if hidden grid is being accessed by non-owner
      if (grid.visibility === "hidden" && (!viewer || viewer.toLowerCase() !== grid.creator.toLowerCase())) {
        return NextResponse.json({
          success: false,
          error: "This grid is hidden",
          isHidden: true,
        }, { status: 403 });
      }

      // Get grid with stats and cells
      const gridWithStats = await getGridWithStats(grid);
      const cellsData = await getKV<GridCells>(GRIDS_KV_KEYS.gridCells(gridId));

      // Enrich all cells with coverUrls from discovery index
      const enrichedCells = await enrichCellsWithCovers(cellsData?.cells || []);

      return NextResponse.json({
        success: true,
        grid: gridWithStats,
        cells: enrichedCells,
      });
    }

    // Grids by creator
    if (creator) {
      const userGridIds = await getKV<string[]>(GRIDS_KV_KEYS.userGrids(creator)) || [];
      const filteredGrids: Grid[] = [];
      const isOwnProfile = viewer && viewer.toLowerCase() === creator.toLowerCase();

      for (const id of userGridIds) {
        const grid = await getKV<Grid>(GRIDS_KV_KEYS.grid(id));
        if (!grid || grid.deleted) continue;

        // Filter by visibility
        if (visibility === "public" && grid.visibility !== "public") continue;
        if (visibility === "hidden" && grid.visibility !== "hidden") continue;

        // Only include hidden grids if viewing own profile
        if (grid.visibility === "hidden" && !isOwnProfile) continue;

        filteredGrids.push(grid);
      }

      // Batch fetch upvote counts
      const upvoteCounts = await getGridUpvoteCounts(
        filteredGrids.map(g => ({ id: g.id, creator: g.creator }))
      );

      // Build grids with stats
      const grids: GridWithStats[] = [];
      for (const grid of filteredGrids) {
        const gridWithStats = await getGridWithStats(grid, upvoteCounts.get(grid.id));
        grids.push(gridWithStats);
      }

      // Sort by creation date (most recent first)
      grids.sort((a, b) => b.createdAt - a.createdAt);

      return NextResponse.json({
        success: true,
        grids,
      });
    }

    // Public feed - all public grids
    const allGridIds = await getKV<string[]>(GRIDS_KV_KEYS.REGISTRY) || [];
    const filteredGrids: Grid[] = [];

    for (const id of allGridIds) {
      const grid = await getKV<Grid>(GRIDS_KV_KEYS.grid(id));
      if (!grid || grid.deleted) continue;

      // Only include public grids in feed
      if (grid.visibility !== "public") continue;

      filteredGrids.push(grid);
    }

    // Batch fetch upvote counts
    const upvoteCounts = await getGridUpvoteCounts(
      filteredGrids.map(g => ({ id: g.id, creator: g.creator }))
    );

    // Build grids with stats
    const grids: GridWithStats[] = [];
    for (const grid of filteredGrids) {
      const gridWithStats = await getGridWithStats(grid, upvoteCounts.get(grid.id));
      grids.push(gridWithStats);
    }

    // Sort
    if (sortBy === "recent") {
      grids.sort((a, b) => b.createdAt - a.createdAt);
    } else {
      // Default: sort by upvotes
      grids.sort((a, b) => b.upvoteCount - a.upvoteCount);
    }

    // Paginate
    const startIndex = (page - 1) * pageSize;
    const paginatedGrids = grids.slice(startIndex, startIndex + pageSize);

    return NextResponse.json({
      success: true,
      grids: paginatedGrids,
      total: grids.length,
      page,
      pageSize,
      totalPages: Math.ceil(grids.length / pageSize),
    });
  } catch (error) {
    console.error("[GET /api/grids] Error:", error);
    return NextResponse.json({ success: false, error: "Internal error" }, { status: 500 });
  }
}

// POST: Create a new grid
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { name, subtitle, description, size, visibility, creator, creatorFid, txHash } = body;

    if (!name || !size || !creator) {
      return NextResponse.json(
        { success: false, error: "Name, size, and creator are required" },
        { status: 400 }
      );
    }

    // Validate size
    if (size < 2 || size > 100) {
      return NextResponse.json(
        { success: false, error: "Grid size must be between 2 and 100" },
        { status: 400 }
      );
    }

    // Check membership
    const memberStatus = await checkMembership(creator, creatorFid);

    if (!memberStatus) {
      return NextResponse.json(
        { success: false, error: "Grids are a member-only feature" },
        { status: 403 }
      );
    }

    // Check if unlock required (6×6+)
    if (requiresGridUnlock(size)) {
      if (!txHash) {
        return NextResponse.json(
          {
            success: false,
            error: "Payment required for 6×6+ grids",
            requiresPayment: true,
            cost: GRID_UNLOCK_PRICE_USD,
          },
          { status: 402 }
        );
      }
      // Verify USDC payment for large grid creation
      const paymentResult = await verifyUsdcPayment(txHash, GRID_UNLOCK_PRICE_USD, creator);
      if (!paymentResult.valid) {
        return NextResponse.json(
          {
            success: false,
            error: paymentResult.error || "Payment verification failed",
            requiresPayment: true,
            cost: GRID_UNLOCK_PRICE_USD,
          },
          { status: 402 }
        );
      }
      await markTxUsed(txHash, `grid-create:${creator}`);
    }

    // Generate grid ID
    const timestamp = Date.now();
    const gridId = generateGridId(creator, name, timestamp);

    // Create grid object
    const grid: Grid = {
      id: gridId,
      name: name.trim(),
      subtitle: subtitle?.trim() || undefined,
      description: description?.trim() || undefined,
      size,
      visibility: visibility || "public",
      creator: creator.toLowerCase(),
      createdAt: timestamp,
      updatedAt: timestamp,
    };

    // Store grid
    await setKV(GRIDS_KV_KEYS.grid(gridId), grid);

    // Initialize empty cells
    const gridCells: GridCells = {
      gridId,
      cells: [],
      updatedAt: timestamp,
    };
    await setKV(GRIDS_KV_KEYS.gridCells(gridId), gridCells);

    // Add to user's grids
    const userGrids = await getKV<string[]>(GRIDS_KV_KEYS.userGrids(creator)) || [];
    userGrids.push(gridId);
    await setKV(GRIDS_KV_KEYS.userGrids(creator), userGrids);

    // Add to global registry
    const allGrids = await getKV<string[]>(GRIDS_KV_KEYS.REGISTRY) || [];
    allGrids.push(gridId);
    await setKV(GRIDS_KV_KEYS.REGISTRY, allGrids);

    return NextResponse.json({
      success: true,
      grid,
    });
  } catch (error) {
    console.error("[POST /api/grids] Error:", error);
    return NextResponse.json({ success: false, error: "Internal error" }, { status: 500 });
  }
}

// PUT: Update grid (add/remove cells, update metadata, resize)
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    const { gridId, action, creator } = body;

    if (!gridId || !creator) {
      return NextResponse.json(
        { success: false, error: "Grid ID and creator are required" },
        { status: 400 }
      );
    }

    // Fetch grid
    const grid = await getKV<Grid>(GRIDS_KV_KEYS.grid(gridId));
    if (!grid || grid.deleted) {
      return NextResponse.json({ success: false, error: "Grid not found" }, { status: 404 });
    }

    // Verify ownership
    const isOwner = grid.creator.toLowerCase() === creator.toLowerCase();
    if (!isOwner) {
      return NextResponse.json({ success: false, error: "Not authorized" }, { status: 403 });
    }

    switch (action) {
      case "add-cell": {
        const { row, col, cdnUrl, contentType, title, coverUrl, contentKey, mediaType: requestMediaType, operator: requestOperator, storageType: requestStorageType } = body;

        if (row === undefined || col === undefined || !cdnUrl) {
          return NextResponse.json(
            { success: false, error: "Row, col, and cdnUrl are required" },
            { status: 400 }
          );
        }

        // Validate row/col within grid bounds
        if (row < 0 || row >= grid.size || col < 0 || col >= grid.size) {
          return NextResponse.json(
            { success: false, error: "Cell position out of bounds" },
            { status: 400 }
          );
        }

        // Get current cells
        const gridCells: GridCells = await getKV<GridCells>(GRIDS_KV_KEYS.gridCells(gridId)) || {
          gridId,
          cells: [] as GridCell[],
          updatedAt: Date.now(),
        };

        // Check if cell already occupied
        const existingCellIndex = gridCells.cells.findIndex(
          (c) => c.row === row && c.col === col
        );

        // Use mediaType from request if provided (from discovery index lookup),
        // otherwise detect from URL/contentType
        let mediaType: GridMediaType;
        let detectedContentType = contentType;

        if (requestMediaType) {
          // Map discovery index mediaType to GridMediaType
          // Discovery uses: "pdf" | "image" | "audio" | "video" | "text" | "unknown"
          // GridCell uses: "image" | "gif" | "video" | "audio" | "text"
          if (requestMediaType === "video") {
            mediaType = "video";
            detectedContentType = detectedContentType || "video/mp4";
          } else if (requestMediaType === "audio") {
            mediaType = "audio";
            detectedContentType = detectedContentType || "audio/mpeg";
          } else if (requestMediaType === "image") {
            const urlLower = cdnUrl.toLowerCase();
            mediaType = urlLower.includes(".gif") ? "gif" : "image";
            detectedContentType = detectedContentType || "image/png";
          } else if (requestMediaType === "text") {
            mediaType = "text";
            detectedContentType = detectedContentType || "text/plain";
          } else {
            // Default fallback
            detectedContentType = detectedContentType || "image/png";
            mediaType = detectGridMediaType(cdnUrl, detectedContentType);
          }
        } else {
          // No mediaType provided - detect from URL
          detectedContentType = detectedContentType || "image/png";
          mediaType = detectGridMediaType(cdnUrl, detectedContentType);
        }

        const newCell: GridCell = {
          row,
          col,
          cdnUrl,
          contentType: detectedContentType,
          mediaType,
          addedAt: Date.now(),
          title,
          coverUrl, // Cover art from discovery index
          contentKey, // Discovery index key for linking to item detail
          operator: requestOperator, // Net Protocol operator address for media playback
          storageType: requestStorageType, // Storage type for content reconstruction (regular/chunked/xml)
        };

        if (existingCellIndex >= 0) {
          // Replace existing cell
          gridCells.cells[existingCellIndex] = newCell;
        } else {
          // Add new cell
          gridCells.cells.push(newCell);
        }

        gridCells.updatedAt = Date.now();
        await setKV(GRIDS_KV_KEYS.gridCells(gridId), gridCells);

        // Update grid updatedAt
        grid.updatedAt = Date.now();
        await setKV(GRIDS_KV_KEYS.grid(gridId), grid);

        return NextResponse.json({
          success: true,
          cell: newCell,
          cellCount: gridCells.cells.length,
        });
      }

      case "remove-cell": {
        const { row, col } = body;

        if (row === undefined || col === undefined) {
          return NextResponse.json(
            { success: false, error: "Row and col are required" },
            { status: 400 }
          );
        }

        const gridCells = await getKV<GridCells>(GRIDS_KV_KEYS.gridCells(gridId));
        if (!gridCells) {
          return NextResponse.json({ success: false, error: "No cells found" }, { status: 404 });
        }

        const filteredCells = gridCells.cells.filter(
          (c) => !(c.row === row && c.col === col)
        );

        if (filteredCells.length === gridCells.cells.length) {
          return NextResponse.json({ success: false, error: "Cell not found" }, { status: 404 });
        }

        gridCells.cells = filteredCells;
        gridCells.updatedAt = Date.now();
        await setKV(GRIDS_KV_KEYS.gridCells(gridId), gridCells);

        grid.updatedAt = Date.now();
        await setKV(GRIDS_KV_KEYS.grid(gridId), grid);

        return NextResponse.json({
          success: true,
          cellCount: filteredCells.length,
        });
      }

      case "move-cell": {
        const { fromRow, fromCol, toRow, toCol } = body;

        if (fromRow === undefined || fromCol === undefined || toRow === undefined || toCol === undefined) {
          return NextResponse.json(
            { success: false, error: "fromRow, fromCol, toRow, and toCol are required" },
            { status: 400 }
          );
        }

        // Validate target position is within grid bounds
        if (toRow < 0 || toRow >= grid.size || toCol < 0 || toCol >= grid.size) {
          return NextResponse.json(
            { success: false, error: `Position must be within grid bounds (1-${grid.size})` },
            { status: 400 }
          );
        }

        const gridCells = await getKV<GridCells>(GRIDS_KV_KEYS.gridCells(gridId));
        if (!gridCells) {
          return NextResponse.json({ success: false, error: "No cells found" }, { status: 404 });
        }

        // Find the cell to move
        const cellIndex = gridCells.cells.findIndex(
          (c) => c.row === fromRow && c.col === fromCol
        );

        if (cellIndex === -1) {
          return NextResponse.json({ success: false, error: "Cell not found at source position" }, { status: 404 });
        }

        // Check if target position has a cell (will be replaced)
        const targetCellIndex = gridCells.cells.findIndex(
          (c) => c.row === toRow && c.col === toCol
        );

        // Remove target cell if it exists
        if (targetCellIndex !== -1) {
          gridCells.cells.splice(targetCellIndex, 1);
          // Adjust cellIndex if needed after removal
          const adjustedCellIndex = gridCells.cells.findIndex(
            (c) => c.row === fromRow && c.col === fromCol
          );
          if (adjustedCellIndex !== -1) {
            gridCells.cells[adjustedCellIndex].row = toRow;
            gridCells.cells[adjustedCellIndex].col = toCol;
          }
        } else {
          // Just move the cell
          gridCells.cells[cellIndex].row = toRow;
          gridCells.cells[cellIndex].col = toCol;
        }

        gridCells.updatedAt = Date.now();
        await setKV(GRIDS_KV_KEYS.gridCells(gridId), gridCells);

        grid.updatedAt = Date.now();
        await setKV(GRIDS_KV_KEYS.grid(gridId), grid);

        return NextResponse.json({
          success: true,
          movedTo: { row: toRow, col: toCol },
          replacedExisting: targetCellIndex !== -1,
        });
      }

      case "update-metadata": {
        const { name, subtitle, description, visibility: newVisibility } = body;

        if (name) grid.name = name.trim();
        // Allow setting to empty string to clear, or new value
        if (subtitle !== undefined) grid.subtitle = subtitle?.trim() || undefined;
        if (description !== undefined) grid.description = description?.trim() || undefined;
        if (newVisibility && (newVisibility === "public" || newVisibility === "hidden")) {
          grid.visibility = newVisibility;
        }

        grid.updatedAt = Date.now();
        await setKV(GRIDS_KV_KEYS.grid(gridId), grid);

        return NextResponse.json({ success: true, grid });
      }

      case "resize": {
        const { newSize, txHash } = body;

        if (!newSize || newSize < grid.size) {
          return NextResponse.json(
            { success: false, error: "New size must be larger than current size" },
            { status: 400 }
          );
        }

        // Check if unlock required for new size
        if (requiresGridUnlock(newSize) && !requiresGridUnlock(grid.size)) {
          if (!txHash) {
            return NextResponse.json(
              {
                success: false,
                error: "Payment required for 6×6+ grids",
                requiresPayment: true,
                cost: GRID_UNLOCK_PRICE_USD,
              },
              { status: 402 }
            );
          }
          // Verify USDC payment for grid resize unlock
          const paymentResult = await verifyUsdcPayment(txHash, GRID_UNLOCK_PRICE_USD, creator);
          if (!paymentResult.valid) {
            return NextResponse.json(
              {
                success: false,
                error: paymentResult.error || "Payment verification failed",
                requiresPayment: true,
                cost: GRID_UNLOCK_PRICE_USD,
              },
              { status: 402 }
            );
          }
          await markTxUsed(txHash, `grid-resize:${gridId}`);
        }

        grid.size = newSize;
        grid.updatedAt = Date.now();
        await setKV(GRIDS_KV_KEYS.grid(gridId), grid);

        return NextResponse.json({ success: true, grid });
      }

      case "swap-cells": {
        // Swap two cells' positions (for drag-to-rearrange)
        const { fromRow, fromCol, toRow, toCol } = body;

        if (fromRow === undefined || fromCol === undefined || toRow === undefined || toCol === undefined) {
          return NextResponse.json(
            { success: false, error: "fromRow, fromCol, toRow, toCol are required" },
            { status: 400 }
          );
        }

        // Validate positions
        if (fromRow < 0 || fromRow >= grid.size || fromCol < 0 || fromCol >= grid.size ||
            toRow < 0 || toRow >= grid.size || toCol < 0 || toCol >= grid.size) {
          return NextResponse.json(
            { success: false, error: "Cell positions out of bounds" },
            { status: 400 }
          );
        }

        const gridCells = await getKV<GridCells>(GRIDS_KV_KEYS.gridCells(gridId));
        if (!gridCells) {
          return NextResponse.json({ success: false, error: "No cells found" }, { status: 404 });
        }

        // Find cells at both positions
        const fromCellIndex = gridCells.cells.findIndex(c => c.row === fromRow && c.col === fromCol);
        const toCellIndex = gridCells.cells.findIndex(c => c.row === toRow && c.col === toCol);

        // At least the source cell must exist
        if (fromCellIndex === -1) {
          return NextResponse.json({ success: false, error: "Source cell not found" }, { status: 404 });
        }

        // Perform swap
        if (toCellIndex === -1) {
          // Moving to empty cell - just update position
          gridCells.cells[fromCellIndex].row = toRow;
          gridCells.cells[fromCellIndex].col = toCol;
        } else {
          // Swap positions of both cells
          gridCells.cells[fromCellIndex].row = toRow;
          gridCells.cells[fromCellIndex].col = toCol;
          gridCells.cells[toCellIndex].row = fromRow;
          gridCells.cells[toCellIndex].col = fromCol;
        }

        gridCells.updatedAt = Date.now();
        await setKV(GRIDS_KV_KEYS.gridCells(gridId), gridCells);

        grid.updatedAt = Date.now();
        await setKV(GRIDS_KV_KEYS.grid(gridId), grid);

        return NextResponse.json({
          success: true,
          message: "Cells swapped",
          cellCount: gridCells.cells.length,
        });
      }

      default:
        return NextResponse.json({ success: false, error: "Invalid action" }, { status: 400 });
    }
  } catch (error) {
    console.error("[PUT /api/grids] Error:", error);
    return NextResponse.json({ success: false, error: "Internal error" }, { status: 500 });
  }
}

// DELETE: Soft-delete a grid
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const gridId = searchParams.get("id");
    const creator = searchParams.get("creator");

    if (!gridId || !creator) {
      return NextResponse.json(
        { success: false, error: "Grid ID and creator are required" },
        { status: 400 }
      );
    }

    // Fetch grid
    const grid = await getKV<Grid>(GRIDS_KV_KEYS.grid(gridId));
    if (!grid) {
      return NextResponse.json({ success: false, error: "Grid not found" }, { status: 404 });
    }

    // Verify ownership
    const isOwner = grid.creator.toLowerCase() === creator.toLowerCase();
    if (!isOwner) {
      return NextResponse.json({ success: false, error: "Not authorized" }, { status: 403 });
    }

    // Soft delete
    grid.deleted = true;
    grid.updatedAt = Date.now();
    await setKV(GRIDS_KV_KEYS.grid(gridId), grid);

    // Remove from user's grids
    const userGrids = await getKV<string[]>(GRIDS_KV_KEYS.userGrids(creator)) || [];
    const updatedUserGrids = userGrids.filter((id) => id !== gridId);
    await setKV(GRIDS_KV_KEYS.userGrids(creator), updatedUserGrids);

    // Remove from global registry
    const allGrids = await getKV<string[]>(GRIDS_KV_KEYS.REGISTRY) || [];
    const updatedAllGrids = allGrids.filter((id) => id !== gridId);
    await setKV(GRIDS_KV_KEYS.REGISTRY, updatedAllGrids);

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("[DELETE /api/grids] Error:", error);
    return NextResponse.json({ success: false, error: "Internal error" }, { status: 500 });
  }
}
src/app/api/leaderboard/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry } from "@/lib/net-protocol";

const LEADERBOARD_KEY = "leaderboard-index";

interface LeaderboardEntry {
  address: string;
  totalUploads: number;
  totalBytes: number;
  lastUpload: number;
}

interface LeaderboardIndex {
  entries: LeaderboardEntry[];
  lastUpdated: number;
}

// Fetch leaderboard from KV
async function fetchLeaderboard(): Promise<LeaderboardIndex> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, LEADERBOARD_KEY)).limit(1);
    if (!result[0]?.value) return { entries: [], lastUpdated: Date.now() };
    return JSON.parse(result[0].value) as LeaderboardIndex;
  } catch (error) {
    console.error("fetchLeaderboard error:", error);
    return { entries: [], lastUpdated: Date.now() };
  }
}

// Store leaderboard to KV
async function storeLeaderboard(data: LeaderboardIndex): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: LEADERBOARD_KEY, value: JSON.stringify(data) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(data) },
    });
    return true;
  } catch (error) {
    console.error("storeLeaderboard error:", error);
    return false;
  }
}

// GET - Fetch leaderboard
export async function GET() {
  try {
    const leaderboard = await fetchLeaderboard();
    // Sort by totalUploads descending
    const sorted = leaderboard.entries.sort((a, b) => b.totalUploads - a.totalUploads);
    return NextResponse.json({
      success: true,
      entries: sorted,
      count: sorted.length,
    });
  } catch (error) {
    console.error("Leaderboard GET error:", error);
    return NextResponse.json({ error: "Failed to fetch leaderboard" }, { status: 500 });
  }
}

// POST - Update leaderboard with new upload
export async function POST(request: NextRequest) {
  try {
    const { entry } = await request.json() as { entry: DiscoveryEntry };

    if (!entry?.operator) {
      return NextResponse.json({ error: "Missing entry data" }, { status: 400 });
    }

    const leaderboard = await fetchLeaderboard();
    if (!entry.operator) {
      return NextResponse.json({ error: "Missing operator" }, { status: 400 });
    }
    const address = entry.operator.toLowerCase();

    // Find or create entry for this uploader
    let uploaderEntry = leaderboard.entries.find(e => e.address.toLowerCase() === address);

    if (uploaderEntry) {
      uploaderEntry.totalUploads += 1;
      uploaderEntry.totalBytes += entry.fileSize;
      uploaderEntry.lastUpload = Date.now();
    } else {
      leaderboard.entries.push({
        address,
        totalUploads: 1,
        totalBytes: entry.fileSize,
        lastUpload: Date.now(),
      });
    }

    leaderboard.lastUpdated = Date.now();

    await storeLeaderboard(leaderboard);

    return NextResponse.json({
      success: true,
      count: leaderboard.entries.length,
    });
  } catch (error) {
    console.error("Leaderboard POST error:", error);
    return NextResponse.json({ error: "Failed to update leaderboard" }, { status: 500 });
  }
}
src/app/api/link-address/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import {
  linkAddressToMember,
  findMembership,
  type MemberRegistry,
} from "@/lib/net-protocol";

const REGISTRY_KEY = "member-registry";

// Direct DB fetch for member registry
async function fetchRegistry(): Promise<MemberRegistry> {
  const emptyRegistry: MemberRegistry = {
    members: [],
    nextMemberId: 1,
    lastUpdated: Date.now(),
  };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) {
      return emptyRegistry;
    }
    return JSON.parse(result[0].value) as MemberRegistry;
  } catch (error) {
    console.error("[fetchRegistry] Error:", error);
    return emptyRegistry;
  }
}

// Direct DB store for member registry
async function storeRegistry(registry: MemberRegistry): Promise<boolean> {
  try {
    const jsonValue = JSON.stringify(registry);
    await db.insert(kv).values({ key: REGISTRY_KEY, value: jsonValue }).onConflictDoUpdate({
      target: kv.key,
      set: { value: jsonValue },
    });
    return true;
  } catch (error) {
    console.error("[storeRegistry] Error:", error);
    return false;
  }
}

/**
 * POST /api/link-address
 * Links a new wallet address to an existing membership.
 *
 * For Farcaster users: Auto-links when their FID matches an existing member
 * For Base App users: Requires providing the member ID they want to link to
 *
 * Body:
 * - address: The new wallet address to link
 * - fid?: Farcaster ID (for auto-linking)
 * - memberId?: Member ID to link to (for manual linking)
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { address, fid, memberId } = body;

    if (!address) {
      return NextResponse.json(
        { error: "Wallet address is required" },
        { status: 400 }
      );
    }

    const registry = await fetchRegistry();

    // Check if address is already associated with a membership
    const existingMembership = findMembership(registry, address, fid);

    if (existingMembership) {
      // Check if this is the primary address or already linked
      if (existingMembership.address.toLowerCase() === address.toLowerCase()) {
        return NextResponse.json({
          success: true,
          alreadyLinked: true,
          member: existingMembership,
          message: "This is the primary address for your membership",
        });
      }

      if (existingMembership.linkedAddresses?.some(
        (linked) => linked.toLowerCase() === address.toLowerCase()
      )) {
        return NextResponse.json({
          success: true,
          alreadyLinked: true,
          member: existingMembership,
          message: "This address is already linked to your membership",
        });
      }

      // FID matched but address not linked yet - auto-link
      if (fid && existingMembership.fid === fid) {
        const result = linkAddressToMember(registry, existingMembership.memberId, address);
        if (result.success) {
          await storeRegistry(result.registry);
          const updatedMember = result.registry.members.find(
            (m) => m.memberId === existingMembership.memberId
          );
          return NextResponse.json({
            success: true,
            linked: true,
            member: updatedMember,
            message: `Address linked to member #${existingMembership.memberId}`,
          });
        }
        return NextResponse.json(
          { error: result.error || "Failed to link address" },
          { status: 400 }
        );
      }
    }

    // Manual linking with memberId
    if (memberId) {
      const targetMember = registry.members.find((m) => m.memberId === memberId);
      if (!targetMember) {
        return NextResponse.json(
          { error: "Member not found" },
          { status: 404 }
        );
      }

      const result = linkAddressToMember(registry, memberId, address);
      if (result.success) {
        await storeRegistry(result.registry);
        const updatedMember = result.registry.members.find(
          (m) => m.memberId === memberId
        );
        return NextResponse.json({
          success: true,
          linked: true,
          member: updatedMember,
          message: `Address linked to member #${memberId}`,
        });
      }
      return NextResponse.json(
        { error: result.error || "Failed to link address" },
        { status: 400 }
      );
    }

    // No existing membership found and no memberId provided
    return NextResponse.json({
      success: false,
      notFound: true,
      message: "No existing membership found for this address or FID",
    });
  } catch (error) {
    console.error("[POST /api/link-address] Error:", error);
    return NextResponse.json(
      { error: "Failed to process link request" },
      { status: 500 }
    );
  }
}

/**
 * GET /api/link-address?address=0x...&fid=123
 * Check if an address can be linked to an existing membership
 */
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const address = searchParams.get("address");
  const fidStr = searchParams.get("fid");
  const fid = fidStr ? parseInt(fidStr, 10) : undefined;

  if (!address) {
    return NextResponse.json(
      { error: "Address parameter is required" },
      { status: 400 }
    );
  }

  try {
    const registry = await fetchRegistry();
    const membership = findMembership(registry, address, fid);

    if (membership) {
      const isPrimaryAddress = membership.address.toLowerCase() === address.toLowerCase();
      const isLinkedAddress = membership.linkedAddresses?.some(
        (linked) => linked.toLowerCase() === address.toLowerCase()
      );

      return NextResponse.json({
        isMember: true,
        member: membership,
        isPrimaryAddress,
        isLinkedAddress,
        canLink: !isPrimaryAddress && !isLinkedAddress && fid && membership.fid === fid,
      });
    }

    // Check if there's a membership by FID that could be linked
    if (fid) {
      const memberByFid = registry.members.find((m) => m.fid === fid);
      if (memberByFid) {
        return NextResponse.json({
          isMember: false,
          canLink: true,
          existingMember: memberByFid,
          message: "Your Farcaster account is already a member. You can link this wallet.",
        });
      }
    }

    return NextResponse.json({
      isMember: false,
      canLink: false,
    });
  } catch (error) {
    console.error("[GET /api/link-address] Error:", error);
    return NextResponse.json(
      { error: "Failed to check link status" },
      { status: 500 }
    );
  }
}
src/app/api/link-challenge/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { findMembership, type MemberRegistry } from "@/lib/net-protocol";
import { randomBytes } from "crypto";

const REGISTRY_KEY = "member-registry";
const CHALLENGE_PREFIX = "link-challenge:";
const CHALLENGE_EXPIRY_MS = 10 * 60 * 1000; // 10 minutes

interface LinkChallenge {
  id: string;
  memberId: number;
  fid: number;
  initiatorAddress: string;
  nonce: string;
  createdAt: number;
  expiresAt: number;
  used: boolean;
}

// Direct DB fetch for member registry
async function fetchRegistry(): Promise<MemberRegistry> {
  const emptyRegistry: MemberRegistry = {
    members: [],
    nextMemberId: 1,
    lastUpdated: Date.now(),
  };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) {
      return emptyRegistry;
    }
    return JSON.parse(result[0].value) as MemberRegistry;
  } catch (error) {
    console.error("[fetchRegistry] Error:", error);
    return emptyRegistry;
  }
}

// Store a challenge
async function storeChallenge(challenge: LinkChallenge): Promise<boolean> {
  try {
    const key = CHALLENGE_PREFIX + challenge.id;
    const jsonValue = JSON.stringify(challenge);
    await db.insert(kv).values({ key, value: jsonValue }).onConflictDoUpdate({
      target: kv.key,
      set: { value: jsonValue },
    });
    return true;
  } catch (error) {
    console.error("[storeChallenge] Error:", error);
    return false;
  }
}

// Fetch a challenge
async function fetchChallenge(challengeId: string): Promise<LinkChallenge | null> {
  try {
    const key = CHALLENGE_PREFIX + challengeId;
    const result = await db.select().from(kv).where(eq(kv.key, key)).limit(1);
    if (!result[0]?.value) {
      return null;
    }
    return JSON.parse(result[0].value) as LinkChallenge;
  } catch (error) {
    console.error("[fetchChallenge] Error:", error);
    return null;
  }
}

// Mark challenge as used
async function markChallengeUsed(challengeId: string): Promise<boolean> {
  const challenge = await fetchChallenge(challengeId);
  if (!challenge) return false;

  challenge.used = true;
  return storeChallenge(challenge);
}

// Generate a secure random challenge ID
function generateChallengeId(): string {
  return randomBytes(16).toString("hex");
}

function generateNonce(): string {
  return randomBytes(8).toString("hex");
}

/**
 * POST /api/link-challenge
 * Creates a new cross-app linking challenge.
 *
 * Only authenticated members can create challenges - this ensures only the
 * membership owner can authorize linking a new wallet.
 *
 * Body:
 * - fid: Farcaster ID of the member
 * - address: Current wallet address (initiator address)
 *
 * Returns:
 * - challengeId: Unique ID for this challenge
 * - expiresAt: When the challenge expires
 * - linkUrl: Full URL to share/open in Base App
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { fid, address } = body;

    if (!fid || !address) {
      return NextResponse.json(
        { error: "FID and address are required" },
        { status: 400 }
      );
    }

    const registry = await fetchRegistry();

    // Find the member by FID - only members can create challenges
    const membership = findMembership(registry, address, fid);

    if (!membership) {
      return NextResponse.json(
        { error: "No membership found. You must be a member to create a link challenge." },
        { status: 403 }
      );
    }

    // Verify the FID matches the membership
    if (membership.fid !== fid) {
      return NextResponse.json(
        { error: "FID does not match membership" },
        { status: 403 }
      );
    }

    // Create the challenge
    const now = Date.now();
    const challenge: LinkChallenge = {
      id: generateChallengeId(),
      memberId: membership.memberId,
      fid: fid,
      initiatorAddress: address.toLowerCase(),
      nonce: generateNonce(),
      createdAt: now,
      expiresAt: now + CHALLENGE_EXPIRY_MS,
      used: false,
    };

    const stored = await storeChallenge(challenge);
    if (!stored) {
      return NextResponse.json(
        { error: "Failed to create challenge" },
        { status: 500 }
      );
    }

    // Build the link URL - this is what gets opened in Base App
    // eslint-disable-next-line @neynar/no-process-env
    const baseUrl = process.env.NEXT_PUBLIC_APP_URL ||
                    // eslint-disable-next-line @neynar/no-process-env
                    (process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` :
                    "https://net-library.vercel.app");
    const linkUrl = `${baseUrl}/link?challenge=${challenge.id}`;

    return NextResponse.json({
      success: true,
      challengeId: challenge.id,
      memberId: membership.memberId,
      ensSubname: membership.ensSubname,
      expiresAt: challenge.expiresAt,
      expiresIn: CHALLENGE_EXPIRY_MS,
      linkUrl,
      message: `Share this link to link a new wallet to member #${membership.memberId}`,
    });
  } catch (error) {
    console.error("[POST /api/link-challenge] Error:", error);
    return NextResponse.json(
      { error: "Failed to create link challenge" },
      { status: 500 }
    );
  }
}

/**
 * GET /api/link-challenge?id=xxx
 * Retrieves challenge details for the Base App link page.
 *
 * Used when a user opens the link URL - the page needs to know:
 * - Is this a valid challenge?
 * - What member is it for?
 * - What message should they sign?
 */
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const challengeId = searchParams.get("id");

  if (!challengeId) {
    return NextResponse.json(
      { error: "Challenge ID is required" },
      { status: 400 }
    );
  }

  try {
    const challenge = await fetchChallenge(challengeId);

    if (!challenge) {
      return NextResponse.json(
        { error: "Challenge not found" },
        { status: 404 }
      );
    }

    // Check if expired
    if (Date.now() > challenge.expiresAt) {
      return NextResponse.json({
        valid: false,
        expired: true,
        error: "This link has expired. Please request a new one from the Farcaster app.",
      });
    }

    // Check if already used
    if (challenge.used) {
      return NextResponse.json({
        valid: false,
        used: true,
        error: "This link has already been used.",
      });
    }

    // Get member details
    const registry = await fetchRegistry();
    const member = registry.members.find(m => m.memberId === challenge.memberId);

    if (!member) {
      return NextResponse.json({
        valid: false,
        error: "Member no longer exists",
      });
    }

    // Build the SIWE message that will be signed
    // eslint-disable-next-line @neynar/no-process-env
    const domain = new URL(process.env.NEXT_PUBLIC_APP_URL || "https://net-library.vercel.app").hostname;
    const siweMessage = [
      `${domain} wants you to sign in with your Ethereum account.`,
      "",
      `Link this wallet to Net Library member #${challenge.memberId} (${member.ensSubname})`,
      "",
      `URI: https://${domain}`,
      `Version: 1`,
      `Chain ID: 8453`,
      `Nonce: ${challenge.nonce}`,
      `Issued At: ${new Date().toISOString()}`,
      `Expiration Time: ${new Date(challenge.expiresAt).toISOString()}`,
    ].join("\n");

    return NextResponse.json({
      valid: true,
      challenge: {
        id: challenge.id,
        memberId: challenge.memberId,
        memberName: member.ensSubname,
        fid: challenge.fid,
        nonce: challenge.nonce,
        expiresAt: challenge.expiresAt,
        expiresIn: challenge.expiresAt - Date.now(),
      },
      siweMessage,
    });
  } catch (error) {
    console.error("[GET /api/link-challenge] Error:", error);
    return NextResponse.json(
      { error: "Failed to fetch challenge" },
      { status: 500 }
    );
  }
}

/**
 * PUT /api/link-challenge
 * Verifies a signed challenge and completes the wallet linking.
 *
 * Body:
 * - challengeId: The challenge being completed
 * - address: The new wallet address to link
 * - signature: SIWE signature from the new wallet
 * - message: The signed message (for verification)
 */
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    const { challengeId, address, signature, message } = body;

    if (!challengeId || !address || !signature || !message) {
      return NextResponse.json(
        { error: "Missing required fields" },
        { status: 400 }
      );
    }

    // Fetch and validate the challenge
    const challenge = await fetchChallenge(challengeId);

    if (!challenge) {
      return NextResponse.json(
        { error: "Challenge not found" },
        { status: 404 }
      );
    }

    if (Date.now() > challenge.expiresAt) {
      return NextResponse.json({
        success: false,
        error: "Challenge expired. Please request a new link from the Farcaster app.",
      });
    }

    if (challenge.used) {
      return NextResponse.json({
        success: false,
        error: "Challenge already used.",
      });
    }

    // Verify the nonce is in the message (prevent replay with different challenge)
    if (!message.includes(challenge.nonce)) {
      return NextResponse.json({
        success: false,
        error: "Invalid message nonce",
      });
    }

    // Verify the member ID is in the message
    if (!message.includes(`member #${challenge.memberId}`)) {
      return NextResponse.json({
        success: false,
        error: "Invalid message - member ID mismatch",
      });
    }

    // Verify the signature using viem
    const { verifyMessage } = await import("viem");
    const isValid = await verifyMessage({
      address: address as `0x${string}`,
      message,
      signature: signature as `0x${string}`,
    });

    if (!isValid) {
      return NextResponse.json({
        success: false,
        error: "Invalid signature",
      });
    }

    // Signature is valid! Now link the address to the membership
    const registry = await fetchRegistry();
    const member = registry.members.find(m => m.memberId === challenge.memberId);

    if (!member) {
      return NextResponse.json({
        success: false,
        error: "Member not found",
      });
    }

    // Check if address is already linked
    const normalizedAddress = address.toLowerCase();
    if (member.address && member.address.toLowerCase() === normalizedAddress) {
      return NextResponse.json({
        success: true,
        alreadyLinked: true,
        message: "This is already your primary address",
      });
    }

    if (member.linkedAddresses?.some(a => a && a.toLowerCase() === normalizedAddress)) {
      return NextResponse.json({
        success: true,
        alreadyLinked: true,
        message: "This address is already linked",
      });
    }

    // Add to linked addresses
    if (!member.linkedAddresses) {
      member.linkedAddresses = [];
    }
    member.linkedAddresses.push(normalizedAddress);
    registry.lastUpdated = Date.now();

    // Save updated registry
    const jsonValue = JSON.stringify(registry);
    await db.insert(kv).values({ key: REGISTRY_KEY, value: jsonValue }).onConflictDoUpdate({
      target: kv.key,
      set: { value: jsonValue },
    });

    // Mark challenge as used
    await markChallengeUsed(challengeId);

    return NextResponse.json({
      success: true,
      linked: true,
      memberId: challenge.memberId,
      memberName: member.ensSubname,
      newAddress: normalizedAddress,
      message: `Successfully linked ${normalizedAddress.slice(0, 6)}...${normalizedAddress.slice(-4)} to member #${challenge.memberId}`,
    });
  } catch (error) {
    console.error("[PUT /api/link-challenge] Error:", error);
    return NextResponse.json(
      { error: "Failed to verify challenge" },
      { status: 500 }
    );
  }
}
src/app/api/link-farcaster/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { isMemberByFid, type MemberRegistry } from "@/lib/net-protocol";

const REGISTRY_KEY = "member-registry";

// Direct DB fetch for member registry
async function fetchRegistry(): Promise<MemberRegistry> {
  const emptyRegistry: MemberRegistry = {
    members: [],
    nextMemberId: 1,
    lastUpdated: Date.now(),
  };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) {
      return emptyRegistry;
    }
    return JSON.parse(result[0].value) as MemberRegistry;
  } catch (error) {
    console.error("[fetchRegistry] Error:", error);
    return emptyRegistry;
  }
}

// Direct DB store for member registry
async function storeRegistry(registry: MemberRegistry): Promise<boolean> {
  try {
    const jsonValue = JSON.stringify(registry);
    await db.insert(kv).values({ key: REGISTRY_KEY, value: jsonValue }).onConflictDoUpdate({
      target: kv.key,
      set: { value: jsonValue },
    });
    return true;
  } catch (error) {
    console.error("[storeRegistry] Error:", error);
    return false;
  }
}

/**
 * POST /api/link-farcaster
 * Links a Farcaster account (FID) to an existing membership.
 * Used by Base App users who want to also access their membership via Farcaster.
 *
 * Body:
 * - address: The wallet address of the member
 * - memberId: The member ID to link to
 * - fid: The Farcaster ID to link
 * - username: The Farcaster username
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { address, memberId, fid, username } = body;

    console.log("[POST /api/link-farcaster] Request:", { address: address?.slice(0, 10), memberId, fid, username });

    if (!address || !memberId || !fid) {
      return NextResponse.json(
        { error: "Address, memberId, and fid are required" },
        { status: 400 }
      );
    }

    const registry = await fetchRegistry();

    // Check if FID is already linked to another membership
    const existingByFid = isMemberByFid(registry, fid);
    if (existingByFid && existingByFid.memberId !== memberId) {
      return NextResponse.json(
        { error: `This Farcaster account is already linked to member #${existingByFid.memberId}` },
        { status: 400 }
      );
    }

    // Find the member to update
    const memberIndex = registry.members.findIndex((m) => m.memberId === memberId);
    if (memberIndex === -1) {
      return NextResponse.json(
        { error: "Member not found" },
        { status: 404 }
      );
    }

    const member = registry.members[memberIndex];

    // Verify the requester owns this membership (by address or linked address)
    const isOwner =
      (member.address && member.address.toLowerCase() === address.toLowerCase()) ||
      member.linkedAddresses?.some((linked) => linked && linked.toLowerCase() === address.toLowerCase());

    if (!isOwner) {
      return NextResponse.json(
        { error: "You don't have permission to modify this membership" },
        { status: 403 }
      );
    }

    // Update the member with FID and username
    const updatedMember = {
      ...member,
      fid,
      username: username || member.username,
    };

    const updatedMembers = [...registry.members];
    updatedMembers[memberIndex] = updatedMember;

    const updatedRegistry = {
      ...registry,
      members: updatedMembers,
      lastUpdated: Date.now(),
    };

    // Store the updated registry
    const stored = await storeRegistry(updatedRegistry);
    if (!stored) {
      return NextResponse.json(
        { error: "Failed to save changes" },
        { status: 500 }
      );
    }

    console.log("[POST /api/link-farcaster] Successfully linked FID", fid, "to member", memberId);

    return NextResponse.json({
      success: true,
      member: updatedMember,
      message: `Farcaster account @${username} linked to member #${memberId}`,
    });
  } catch (error) {
    console.error("[POST /api/link-farcaster] Error:", error);
    return NextResponse.json(
      { error: "Failed to link Farcaster account" },
      { status: 500 }
    );
  }
}

/**
 * DELETE /api/link-farcaster
 * Unlinks a Farcaster account (FID) from a membership.
 * Used when a user sells/transfers their FID and needs to disconnect it.
 *
 * Body:
 * - address: The wallet address of the member (for verification)
 * - memberId: The member ID to unlink from
 * - fid: The Farcaster ID to verify (must match the current linked FID)
 */
export async function DELETE(request: NextRequest) {
  try {
    const body = await request.json();
    const { address, memberId, fid } = body;

    console.log("[DELETE /api/link-farcaster] Request:", { address: address?.slice(0, 10), memberId, fid });

    if (!address || !memberId) {
      return NextResponse.json(
        { error: "Address and memberId are required" },
        { status: 400 }
      );
    }

    const registry = await fetchRegistry();

    // Find the member to update
    const memberIndex = registry.members.findIndex((m) => m.memberId === memberId);
    if (memberIndex === -1) {
      return NextResponse.json(
        { error: "Member not found" },
        { status: 404 }
      );
    }

    const member = registry.members[memberIndex];

    // Verify the requester owns this membership (by address or linked address)
    const isOwner =
      (member.address && member.address.toLowerCase() === address.toLowerCase()) ||
      member.linkedAddresses?.some((linked) => linked && linked.toLowerCase() === address.toLowerCase());

    if (!isOwner) {
      return NextResponse.json(
        { error: "You don't have permission to modify this membership" },
        { status: 403 }
      );
    }

    // Verify the FID matches if provided (extra safety check)
    if (fid && member.fid !== fid) {
      return NextResponse.json(
        { error: "FID mismatch - cannot unlink a different Farcaster account" },
        { status: 400 }
      );
    }

    // Check if there's actually a FID to unlink
    if (!member.fid) {
      return NextResponse.json(
        { error: "No Farcaster account is linked to this membership" },
        { status: 400 }
      );
    }

    const previousFid = member.fid;
    const previousUsername = member.username;

    // Remove FID and username from the member
    const updatedMember = {
      ...member,
      fid: undefined,
      username: undefined,
    };

    const updatedMembers = [...registry.members];
    updatedMembers[memberIndex] = updatedMember;

    const updatedRegistry = {
      ...registry,
      members: updatedMembers,
      lastUpdated: Date.now(),
    };

    // Store the updated registry
    const stored = await storeRegistry(updatedRegistry);
    if (!stored) {
      return NextResponse.json(
        { error: "Failed to save changes" },
        { status: 500 }
      );
    }

    console.log("[DELETE /api/link-farcaster] Successfully unlinked FID", previousFid, "from member", memberId);

    return NextResponse.json({
      success: true,
      member: updatedMember,
      unlinkedFid: previousFid,
      unlinkedUsername: previousUsername,
      message: `Farcaster account @${previousUsername || previousFid} has been unlinked from member #${memberId}`,
    });
  } catch (error) {
    console.error("[DELETE /api/link-farcaster] Error:", error);
    return NextResponse.json(
      { error: "Failed to unlink Farcaster account" },
      { status: 500 }
    );
  }
}
src/app/api/lookup-cdn/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry } from "@/lib/net-protocol";

const DISCOVERY_KEY = "discovery-index";

// Look up metadata for a CDN URL from the discovery index
// Returns title, author, coverUrl, etc. if found

async function fetchDiscoveryIndex(): Promise<DiscoveryEntry[]> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    if (!result[0]?.value) return [];
    return JSON.parse(result[0].value) as DiscoveryEntry[];
  } catch (error) {
    console.error("fetchDiscoveryIndex error:", error);
    return [];
  }
}

// Normalize CDN URLs for comparison
function normalizeCdnUrl(url: string): string {
  try {
    // Remove trailing slashes, normalize case
    const normalized = url.trim().toLowerCase().replace(/\/+$/, "");

    // Extract the content key from storedon.net URLs
    // Format: https://storedon.net/content/{key}
    const contentMatch = normalized.match(/storedon\.net\/content\/([^/?#]+)/);
    if (contentMatch) {
      return contentMatch[1]; // Return just the key
    }

    // Format: https://storedon.net/net/{chainId}/storage/raw/{operator}/{key}
    const storageMatch = normalized.match(/storedon\.net\/net\/\d+\/storage\/(?:raw|load)\/([^/]+)\/([^/?#]+)/);
    if (storageMatch) {
      return `${storageMatch[1]}/${storageMatch[2]}`; // Return operator/key
    }

    // Format: https://storedon.net/net/{chainId}/chunked-storage/file/{operator}/{key}
    const chunkedMatch = normalized.match(/storedon\.net\/net\/\d+\/chunked-storage\/(?:file|raw)\/([^/]+)\/([^/?#]+)/);
    if (chunkedMatch) {
      return `${chunkedMatch[1]}/${chunkedMatch[2]}`; // Return operator/key
    }

    return normalized;
  } catch {
    return url;
  }
}

// Check if two CDN URLs refer to the same content
function urlsMatch(url1: string, url2: string): boolean {
  const n1 = normalizeCdnUrl(url1);
  const n2 = normalizeCdnUrl(url2);

  // Direct match
  if (n1 === n2) return true;

  // Check if one contains the other (for partial matches)
  if (n1.includes(n2) || n2.includes(n1)) return true;

  // Extract content keys and compare
  const key1 = url1.match(/0x[a-fA-F0-9]+/)?.[0]?.toLowerCase();
  const key2 = url2.match(/0x[a-fA-F0-9]+/)?.[0]?.toLowerCase();
  if (key1 && key2 && key1 === key2) return true;

  return false;
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const cdnUrl = searchParams.get("url");

    if (!cdnUrl) {
      return NextResponse.json(
        { success: false, error: "Missing url parameter" },
        { status: 400 }
      );
    }

    const entries = await fetchDiscoveryIndex();

    // Find entry matching this CDN URL (case-insensitive for hex keys)
    const cdnUrlLower = cdnUrl.toLowerCase();
    const entry = entries.find((e) => {
      // Check cdnUrl field if it exists
      if (e.cdnUrl && urlsMatch(e.cdnUrl, cdnUrl)) return true;

      // Check if contentKey matches (case-insensitive for hex)
      if (e.contentKey && cdnUrlLower.includes(e.contentKey.toLowerCase())) return true;

      // Check if the URL contains the entry's operator and contentKey (case-insensitive)
      if (e.operator && e.contentKey) {
        if (cdnUrlLower.includes(e.operator.toLowerCase()) &&
            cdnUrlLower.includes(e.contentKey.toLowerCase())) return true;
      }

      return false;
    });

    if (!entry) {
      return NextResponse.json({
        success: true,
        found: false,
        message: "No metadata found for this CDN URL",
      });
    }

    return NextResponse.json({
      success: true,
      found: true,
      metadata: {
        title: entry.title,
        author: entry.author,
        coverUrl: entry.coverUrl,
        categories: entry.categories,
        storageType: entry.storageType,
        fileSize: entry.fileSize,
        uploadedAt: entry.uploadedAt,
        contentKey: entry.contentKey,
        operator: entry.operator,
        mediaType: entry.mediaType, // Important for grid cell media playback
      },
    });
  } catch (error) {
    console.error("CDN lookup error:", error);
    return NextResponse.json(
      { success: false, error: "Failed to lookup CDN metadata" },
      { status: 500 }
    );
  }
}
src/app/api/media-proxy/route.ts
import { NextRequest, NextResponse } from "next/server";

// Media proxy that fetches content from Net Protocol and serves with correct MIME type
// This is needed because Net Protocol storage doesn't preserve content-type headers
//
// This proxy uses the /api/book-file endpoint internally, which handles:
// - XML chunked storage reconstruction
// - Hex decoding
// - Magic byte detection for proper MIME types
// - Caching headers

// Map our mediaType to file extension for MIME type detection
function getFilenameForMediaType(mediaType: string, contentKey: string): string {
  const shortKey = contentKey.slice(0, 8);
  switch (mediaType) {
    case "audio":
      return `${shortKey}.mp3`;
    case "video":
      return `${shortKey}.mp4`;
    case "image":
      return `${shortKey}.png`;
    case "gif":
      return `${shortKey}.gif`;
    case "pdf":
      return `${shortKey}.pdf`;
    case "text":
      return `${shortKey}.txt`;
    default:
      return `${shortKey}.bin`;
  }
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const operator = searchParams.get("operator");
    const contentKey = searchParams.get("contentKey");
    const mediaType = searchParams.get("mediaType") || "audio";
    const storageType = searchParams.get("storageType") || "xml"; // Default to xml since most media is xml chunked

    if (!operator || !contentKey) {
      return NextResponse.json(
        { error: "operator and contentKey are required" },
        { status: 400 }
      );
    }

    console.log("[media-proxy] Proxying to book-file:", { operator: operator.slice(0, 10), contentKey: contentKey.slice(0, 20), mediaType, storageType });

    // Build internal URL to /api/book-file which handles all the complex storage logic
    // This endpoint properly reconstructs XML chunked storage and detects MIME types
    const filename = getFilenameForMediaType(mediaType, contentKey);
    const bookFileUrl = new URL("/api/book-file", request.url);
    bookFileUrl.searchParams.set("contentKey", contentKey);
    bookFileUrl.searchParams.set("operator", operator);
    bookFileUrl.searchParams.set("storageType", storageType);
    bookFileUrl.searchParams.set("filename", filename);

    console.log("[media-proxy] Fetching from book-file:", bookFileUrl.pathname + bookFileUrl.search);

    // Fetch from our internal book-file endpoint
    const response = await fetch(bookFileUrl.toString());

    if (!response.ok) {
      const errorBody = await response.text().catch(() => "");
      console.error("[media-proxy] book-file fetch failed:", response.status, response.statusText, "body:", errorBody.slice(0, 500));

      // Try alternate storage type as fallback
      const alternateStorageType = storageType === "regular" ? "xml" : "regular";
      console.log("[media-proxy] Trying", alternateStorageType, "storage type as fallback...");
      bookFileUrl.searchParams.set("storageType", alternateStorageType);
      const fallbackResponse = await fetch(bookFileUrl.toString());

      if (fallbackResponse.ok) {
        // Clone the response with CORS header
        const data = await fallbackResponse.arrayBuffer();
        const contentType = fallbackResponse.headers.get("Content-Type") || "application/octet-stream";

        return new NextResponse(data, {
          status: 200,
          headers: {
            "Content-Type": contentType,
            "Content-Length": data.byteLength.toString(),
            "Cache-Control": "public, max-age=31536000, immutable",
            "Access-Control-Allow-Origin": "*",
          },
        });
      }

      return NextResponse.json(
        { error: `Failed to fetch content: ${response.status}` },
        { status: response.status }
      );
    }

    // Get the content and forward with CORS headers
    const data = await response.arrayBuffer();
    const contentType = response.headers.get("Content-Type") || "application/octet-stream";

    console.log("[media-proxy] Got content, size:", data.byteLength, "type:", contentType);

    return new NextResponse(data, {
      status: 200,
      headers: {
        "Content-Type": contentType,
        "Content-Length": data.byteLength.toString(),
        "Cache-Control": "public, max-age=31536000, immutable",
        "Access-Control-Allow-Origin": "*",
      },
    });
  } catch (error) {
    console.error("[media-proxy] Error:", error);
    return NextResponse.json(
      { error: "Failed to proxy media" },
      { status: 500 }
    );
  }
}
src/app/api/member-registry/csv/route.ts
import { NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

// Force dynamic rendering - this route queries a database
export const dynamic = "force-dynamic";

// KV key for member registry
const REGISTRY_KEY = "member-registry";

interface MemberEntry {
  memberId: number;
  address: string;
  username?: string;
  fid?: number;
  signupPlatform?: "farcaster" | "base-app";
  ensSubname?: string;
  joinedAt: number;
  // Pass/upgrade flags
  hasStackPass?: boolean;
  hasUnlimitedPass?: boolean;
  hasUnlimitedStoragePass?: boolean; // legacy field name — read for backwards compat
  // Unlimited Pass NFT details
  unlimitedPassTier?: string;        // "we are so early" | "early-ish"
  unlimitedPassTokenId?: number;
}

// Helper to get KV value directly
async function getKV(key: string): Promise<string | null> {
  const result = await db.select().from(kv).where(eq(kv.key, key)).limit(1);
  return result[0]?.value ?? null;
}

// GET - Download member registry as CSV file
export async function GET() {
  try {
    const data = await getKV(REGISTRY_KEY);

    if (!data) {
      return new NextResponse("No members found", { status: 404 });
    }

    const registry = JSON.parse(data);
    const members: MemberEntry[] = registry.members || [];

    // Build CSV content
    // Columns: memberNumber, ensName, fid, address, joinedAt (plus supplementary fields)
    const headers = ["memberNumber", "ensName", "fid", "address", "joinedAt", "username", "signupPlatform", "hasStackPass", "unlimitedPassTier", "unlimitedPassTokenId"];
    const rows = members.map((m) => [
      m.memberId,
      m.ensSubname || "",
      m.fid || "",
      m.address,
      m.joinedAt ? new Date(m.joinedAt).toISOString() : "",
      m.username || "",
      m.signupPlatform || "",
      m.hasStackPass ? "true" : "false",
      m.unlimitedPassTier || "",
      m.unlimitedPassTokenId ?? "",
    ]);

    const csvContent = [
      headers.join(","),
      ...rows.map((row) => row.map((cell) => `"${cell}"`).join(",")),
    ].join("\n");

    const filename = `net-library-members-${new Date().toISOString().split("T")[0]}.csv`;

    // Return CSV with proper headers for download
    return new NextResponse(csvContent, {
      status: 200,
      headers: {
        "Content-Type": "text/csv; charset=utf-8",
        "Content-Disposition": `attachment; filename="${filename}"`,
        "Cache-Control": "public, max-age=300",
      },
    });
  } catch (error) {
    console.error("Failed to generate CSV:", error);
    return new NextResponse("Failed to generate CSV", { status: 500 });
  }
}
src/app/api/member-registry/route.ts
/* eslint-disable @neynar/no-process-env */
import { NextRequest, NextResponse } from "next/server";
import { kvGet, kvSet } from "@/neynar-db-sdk";

// KV key for member registry
const REGISTRY_KEY = "member-registry";

/**
 * Verify admin Authorization header.
 * Returns true if the request carries a valid Bearer ADMIN_KEY token.
 * Returns a 401/503 NextResponse if auth fails (caller should return it immediately).
 */
function verifyAdminAuth(request: NextRequest): true | NextResponse {
  const adminKey = process.env.ADMIN_KEY;
  if (!adminKey) {
    return NextResponse.json({ error: "Admin endpoint not configured" }, { status: 503 });
  }
  const authHeader = request.headers.get("Authorization") || "";
  const token = authHeader.startsWith("Bearer ") ? authHeader.slice(7).trim() : null;
  if (!token || token !== adminKey) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  return true;
}

// GET - Fetch member registry (public — displayed in the member directory UI)
export async function GET() {
  try {
    const data = await kvGet(REGISTRY_KEY);

    if (!data) {
      // No registry exists yet, return empty
      return NextResponse.json({
        members: [],
        nextMemberId: 1,
        lastUpdated: Date.now(),
      });
    }

    const registry = JSON.parse(data);
    return NextResponse.json(registry);
  } catch (error) {
    console.error("Failed to fetch member registry:", error);
    return NextResponse.json({
      members: [],
      nextMemberId: 1,
      lastUpdated: Date.now(),
    });
  }
}

// POST - Store member registry to KV store (admin only)
export async function POST(request: NextRequest) {
  const auth = verifyAdminAuth(request);
  if (auth !== true) return auth;

  try {
    const registry = await request.json();

    await kvSet(REGISTRY_KEY, JSON.stringify(registry));

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Failed to store member registry:", error);
    return NextResponse.json(
      { success: false, error: "Failed to store registry" },
      { status: 500 }
    );
  }
}

// DELETE - Remove specific members from registry (admin only)
export async function DELETE(request: NextRequest) {
  const auth = verifyAdminAuth(request);
  if (auth !== true) return auth;

  try {
    const { memberIds } = await request.json();

    if (!memberIds || !Array.isArray(memberIds)) {
      return NextResponse.json(
        { success: false, error: "memberIds array required" },
        { status: 400 }
      );
    }

    // Fetch current registry
    const data = await kvGet(REGISTRY_KEY);
    if (!data) {
      return NextResponse.json(
        { success: false, error: "No registry found" },
        { status: 404 }
      );
    }

    const registry = JSON.parse(data);

    // Filter out the specified members
    const originalCount = registry.members.length;
    registry.members = registry.members.filter(
      (m: { memberId: number }) => !memberIds.includes(m.memberId)
    );
    const removedCount = originalCount - registry.members.length;

    // Update lastUpdated
    registry.lastUpdated = Date.now();

    // Save updated registry
    await kvSet(REGISTRY_KEY, JSON.stringify(registry));

    return NextResponse.json({
      success: true,
      removedCount,
      remainingMembers: registry.members.length,
    });
  } catch (error) {
    console.error("Failed to remove members:", error);
    return NextResponse.json(
      { success: false, error: "Failed to remove members" },
      { status: 500 }
    );
  }
}

// PATCH - Check for duplicate FIDs (admin only)
// Multiple member numbers per FID is now allowed by design
export async function PATCH(request: NextRequest) {
  const auth = verifyAdminAuth(request);
  if (auth !== true) return auth;

  try {
    const body = await request.json();
    const { action } = body;

    if (action !== "check-duplicates") {
      return NextResponse.json(
        { success: false, error: "Invalid action. Use 'check-duplicates' (deduplicate is deprecated)" },
        { status: 400 }
      );
    }

    // Fetch current registry
    const data = await kvGet(REGISTRY_KEY);
    if (!data) {
      return NextResponse.json(
        { success: false, error: "No registry found" },
        { status: 404 }
      );
    }

    const registry = JSON.parse(data);

    // Group members by FID
    const fidMap = new Map<number, { memberId: number; username?: string; joinedAt: number }[]>();

    for (const member of registry.members) {
      if (member.fid) {
        const existing = fidMap.get(member.fid) || [];
        existing.push({ memberId: member.memberId, username: member.username, joinedAt: member.joinedAt });
        fidMap.set(member.fid, existing);
      }
    }

    // Find FIDs with multiple entries (this is now allowed)
    const fidDetails: { fid: number; members: { memberId: number; username?: string }[] }[] = [];

    fidMap.forEach((entries, fid) => {
      if (entries.length > 1) {
        fidDetails.push({
          fid,
          members: entries.map(e => ({ memberId: e.memberId, username: e.username })),
        });
      }
    });

    return NextResponse.json({
      success: true,
      message: "Multiple member numbers per FID are allowed by design",
      totalMembers: registry.members.length,
      fidsWithMultipleMembers: fidDetails.length,
      details: fidDetails,
    });
  } catch (error) {
    console.error("Failed to check duplicates:", error);
    return NextResponse.json(
      { success: false, error: "Failed to check duplicates" },
      { status: 500 }
    );
  }
}
src/app/api/membership/admin/route.ts
/* eslint-disable @neynar/no-process-env */
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import {
  type MemberRegistry,
  type MemberEntry,
  type SignupPlatform,
} from "@/lib/net-protocol";

const REGISTRY_KEY = "member-registry";

// Direct DB fetch for member registry
async function fetchRegistry(): Promise<MemberRegistry> {
  const emptyRegistry: MemberRegistry = {
    members: [],
    nextMemberId: 1,
    lastUpdated: Date.now(),
  };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) return emptyRegistry;
    return JSON.parse(result[0].value) as MemberRegistry;
  } catch (error) {
    console.error("fetchRegistry error:", error);
    return emptyRegistry;
  }
}

// Direct DB store for member registry
async function storeRegistry(registry: MemberRegistry): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: REGISTRY_KEY, value: JSON.stringify(registry) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(registry) },
    });
    return true;
  } catch (error) {
    console.error("storeRegistry error:", error);
    return false;
  }
}

// GET - View full registry (with all details for admin)
export async function GET(request: NextRequest) {
  const secret = request.nextUrl.searchParams.get("secret");
  const fid = request.nextUrl.searchParams.get("fid");
  const address = request.nextUrl.searchParams.get("address");

  // Simple auth - require ADMIN_SECRET environment variable
  if (!process.env.ADMIN_SECRET || secret !== process.env.ADMIN_SECRET) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const registry = await fetchRegistry();

    // If looking for specific FID
    if (fid) {
      const fidNum = parseInt(fid, 10);
      const matches = registry.members.filter(m => m.fid === fidNum);
      return NextResponse.json({
        query: { fid: fidNum },
        found: matches.length,
        members: matches,
        allMemberIds: registry.members.map(m => m.memberId),
      });
    }

    // If looking for specific address
    if (address) {
      const normalizedAddr = address.toLowerCase();
      const matches = registry.members.filter(m => m.address.toLowerCase() === normalizedAddr);
      return NextResponse.json({
        query: { address },
        found: matches.length,
        members: matches,
      });
    }

    // Return full registry (with full addresses for admin)
    return NextResponse.json({
      totalMembers: registry.members.length,
      nextMemberId: registry.nextMemberId,
      lastUpdated: registry.lastUpdated,
      members: registry.members.map((m) => ({
        memberId: m.memberId,
        username: m.username,
        fid: m.fid,
        ensSubname: m.ensSubname,
        address: m.address, // Full address for admin view
        joinedAt: m.joinedAt,
        txHash: m.txHash,
      })),
    });
  } catch (error) {
    console.error("Admin GET error:", error);
    return NextResponse.json(
      { error: "Failed to fetch registry" },
      { status: 500 }
    );
  }
}

// POST - Restore or add members with specific member IDs
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { secret, action, members } = body;

    // Simple auth - require ADMIN_SECRET environment variable
    if (!process.env.ADMIN_SECRET || secret !== process.env.ADMIN_SECRET) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const registry = await fetchRegistry();

    // Action: restore - Add members back with their original member IDs
    // Use force: true to allow restoring members with duplicate addresses (for users with multiple memberships)
    if (action === "restore") {
      const { force } = body;

      if (!members || !Array.isArray(members)) {
        return NextResponse.json(
          { error: "members array required for restore action" },
          { status: 400 }
        );
      }

      let restoredCount = 0;
      let skippedCount = 0;
      const restored: MemberEntry[] = [];
      const skipped: { memberId: number; reason: string }[] = [];

      for (const memberData of members) {
        // Must have memberId for restore
        if (!memberData.memberId || !memberData.address) {
          skipped.push({ memberId: memberData.memberId || 0, reason: "Missing memberId or address" });
          skippedCount++;
          continue;
        }

        // Check if this memberId already exists
        const existingById = registry.members.find(m => m.memberId === memberData.memberId);
        if (existingById) {
          skipped.push({ memberId: memberData.memberId, reason: "Member ID already exists" });
          skippedCount++;
          continue;
        }

        // Check if this address already has a different membership (skip if force is true)
        if (!force) {
          const existingByAddress = registry.members.find(
            m => m.address.toLowerCase() === memberData.address.toLowerCase()
          );
          if (existingByAddress) {
            skipped.push({
              memberId: memberData.memberId,
              reason: `Address already has memberId ${existingByAddress.memberId}. Use force: true to allow duplicate addresses.`,
            });
            skippedCount++;
            continue;
          }
        }

        // Restore the member with their original ID
        const restoredMember: MemberEntry = {
          memberId: memberData.memberId,
          address: memberData.address,
          ensSubname: `${memberData.memberId}.netlibrary.eth`,
          fid: memberData.fid,
          username: memberData.username,
          joinedAt: memberData.joinedAt || Date.now(),
          txHash: memberData.txHash,
        };

        registry.members.push(restoredMember);
        restored.push(restoredMember);
        restoredCount++;

        // Update nextMemberId if needed
        if (memberData.memberId >= registry.nextMemberId) {
          registry.nextMemberId = memberData.memberId + 1;
        }
      }

      // Sort members by memberId
      registry.members.sort((a, b) => a.memberId - b.memberId);
      registry.lastUpdated = Date.now();

      const storeSuccess = await storeRegistry(registry);

      if (!storeSuccess) {
        return NextResponse.json(
          { error: "Failed to store registry" },
          { status: 500 }
        );
      }

      return NextResponse.json({
        success: true,
        action: "restore",
        restoredCount,
        skippedCount,
        restored: restored.map(m => ({ memberId: m.memberId, username: m.username })),
        skipped,
        totalMembers: registry.members.length,
        nextMemberId: registry.nextMemberId,
      });
    }

    // Action: update - Update specific member fields by memberId
    if (action === "update") {
      const { memberId, updates } = body;

      if (!memberId || !updates) {
        return NextResponse.json(
          { error: "memberId and updates required for update action" },
          { status: 400 }
        );
      }

      const memberIndex = registry.members.findIndex(m => m.memberId === memberId);
      if (memberIndex === -1) {
        return NextResponse.json(
          { error: `Member ${memberId} not found` },
          { status: 404 }
        );
      }

      // Apply updates (only allowed fields)
      const allowedFields = ["fid", "username", "txHash", "signupPlatform"] as const;
      const appliedUpdates: Record<string, unknown> = {};
      const member = registry.members[memberIndex];

      for (const field of allowedFields) {
        if (updates[field] !== undefined) {
          if (field === "fid") {
            member.fid = updates[field] as number;
          } else if (field === "username") {
            member.username = updates[field] as string;
          } else if (field === "txHash") {
            member.txHash = updates[field] as string;
          } else if (field === "signupPlatform") {
            member.signupPlatform = updates[field] as SignupPlatform;
          }
          appliedUpdates[field] = updates[field];
        }
      }

      registry.lastUpdated = Date.now();

      const storeSuccess = await storeRegistry(registry);

      if (!storeSuccess) {
        return NextResponse.json(
          { error: "Failed to store registry" },
          { status: 500 }
        );
      }

      return NextResponse.json({
        success: true,
        action: "update",
        memberId,
        appliedUpdates,
        member: registry.members[memberIndex],
      });
    }

    // Action: backfillSignupPlatform - Set signupPlatform for all members that don't have it
    // Heuristic: if member has FID, assume "farcaster"; otherwise "base-app"
    // Can override with explicit mappings
    if (action === "backfillSignupPlatform") {
      const { overrides } = body; // Optional: { memberId: "farcaster" | "base-app" }

      let updatedCount = 0;
      const updates: { memberId: number; platform: SignupPlatform }[] = [];

      for (const member of registry.members) {
        // Skip if already has signupPlatform
        if (member.signupPlatform) continue;

        // Check for explicit override
        const override = overrides?.[member.memberId];
        let platform: SignupPlatform;

        if (override && (override === "farcaster" || override === "base-app")) {
          platform = override;
        } else {
          // Heuristic: FID present = Farcaster signup, no FID = Base App signup
          platform = member.fid ? "farcaster" : "base-app";
        }

        member.signupPlatform = platform;
        updates.push({ memberId: member.memberId, platform });
        updatedCount++;
      }

      registry.lastUpdated = Date.now();
      const storeSuccess = await storeRegistry(registry);

      if (!storeSuccess) {
        return NextResponse.json(
          { error: "Failed to store registry" },
          { status: 500 }
        );
      }

      return NextResponse.json({
        success: true,
        action: "backfillSignupPlatform",
        updatedCount,
        updates,
        totalMembers: registry.members.length,
      });
    }

    // Action: fixDuplicateFids - Keep ALL member entries even if they have the same FID
    // This is the opposite of deduplicate - it allows multiple memberships per FID
    if (action === "allowDuplicateFids") {
      // This action does nothing to the data, but confirms the current state
      // The deduplication was the problem - we should NOT deduplicate by FID
      // because users may legitimately have multiple member numbers

      const fidCounts: Record<number, number> = {};
      for (const member of registry.members) {
        if (member.fid) {
          fidCounts[member.fid] = (fidCounts[member.fid] || 0) + 1;
        }
      }

      const duplicateFids = Object.entries(fidCounts)
        .filter(([, count]) => count > 1)
        .map(([fid, count]) => ({ fid: parseInt(fid, 10), count }));

      return NextResponse.json({
        success: true,
        action: "allowDuplicateFids",
        message: "Duplicate FIDs are now allowed (each user can have multiple member numbers)",
        totalMembers: registry.members.length,
        duplicateFids,
      });
    }

    return NextResponse.json(
      { error: "Invalid action. Use 'restore', 'update', 'backfillSignupPlatform', or 'allowDuplicateFids'" },
      { status: 400 }
    );
  } catch (error) {
    console.error("Admin POST error:", error);
    return NextResponse.json(
      { error: "Failed to process admin action" },
      { status: 500 }
    );
  }
}
src/app/api/membership/check-fid/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { isMemberByFid, type MemberRegistry } from "@/lib/net-protocol";

const REGISTRY_KEY = "member-registry";

// Direct DB fetch for member registry
async function fetchRegistry(): Promise<MemberRegistry> {
  const emptyRegistry: MemberRegistry = {
    members: [],
    nextMemberId: 1,
    lastUpdated: Date.now(),
  };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) return emptyRegistry;
    return JSON.parse(result[0].value) as MemberRegistry;
  } catch (error) {
    console.error("fetchRegistry error:", error);
    return emptyRegistry;
  }
}

// GET - Check if a FID is already registered as a member
// This is a pre-flight check to prevent users from paying twice
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const fidParam = searchParams.get("fid");

  if (!fidParam) {
    return NextResponse.json(
      { error: "FID parameter is required" },
      { status: 400 }
    );
  }

  const fid = parseInt(fidParam, 10);
  if (isNaN(fid)) {
    return NextResponse.json(
      { error: "Invalid FID" },
      { status: 400 }
    );
  }

  try {
    const registry = await fetchRegistry();
    const member = isMemberByFid(registry, fid);

    return NextResponse.json({
      isMember: !!member,
      member: member ? {
        memberId: member.memberId,
        ensSubname: member.ensSubname,
        username: member.username,
        // Don't expose the full address, just first/last few chars
        addressHint: member.address
          ? `${member.address.slice(0, 6)}...${member.address.slice(-4)}`
          : undefined,
      } : null,
    });
  } catch (error) {
    console.error("[check-fid] Error:", error);
    return NextResponse.json(
      { error: "Failed to check membership" },
      { status: 500 }
    );
  }
}
src/app/api/membership/grid-pass/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { MemberRegistry } from "@/lib/net-protocol";

const MEMBER_REGISTRY_KEY = "member-registry";

// POST: Record a per-grid unlock payment ($2 per custom grid)
// This is used for one-off custom grid creation when user doesn't have Unlimited Pass
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { address, txHash, gridSize } = body;

    if (!address || !txHash) {
      return NextResponse.json(
        { error: "Missing address or txHash" },
        { status: 400 }
      );
    }

    const normalizedAddress = address.toLowerCase();

    // Fetch member registry
    const registryResult = await db
      .select()
      .from(kv)
      .where(eq(kv.key, MEMBER_REGISTRY_KEY))
      .limit(1);

    if (!registryResult[0]?.value) {
      return NextResponse.json(
        { error: "Member registry not found" },
        { status: 404 }
      );
    }

    const registry: MemberRegistry = JSON.parse(registryResult[0].value);

    // Find member by address or linked addresses
    const memberIndex = registry.members.findIndex(
      (m) =>
        m.address.toLowerCase() === normalizedAddress ||
        m.linkedAddresses?.some((a) => a.toLowerCase() === normalizedAddress)
    );

    if (memberIndex === -1) {
      return NextResponse.json(
        { error: "Member not found. Must be a Net Library member to create custom grids." },
        { status: 404 }
      );
    }

    const member = registry.members[memberIndex];

    // Record grid unlock purchase (stored as array of unlocks for tracking)
    const gridUnlocks = member.gridUnlocks || [];
    gridUnlocks.push({
      txHash,
      gridSize: gridSize || 6,
      purchasedAt: Date.now(),
    });

    // Update member with grid unlock record
    registry.members[memberIndex] = {
      ...member,
      gridUnlocks,
    };
    registry.lastUpdated = Date.now();

    // Save updated registry
    await db
      .insert(kv)
      .values({ key: MEMBER_REGISTRY_KEY, value: JSON.stringify(registry) })
      .onConflictDoUpdate({
        target: kv.key,
        set: { value: JSON.stringify(registry) },
      });

    return NextResponse.json({
      success: true,
      message: "Grid unlocked! You can now create your custom grid.",
      gridUnlock: {
        txHash,
        gridSize: gridSize || 6,
        purchasedAt: Date.now(),
      },
    });
  } catch (error) {
    console.error("[POST /api/membership/grid-pass] Error:", error);
    return NextResponse.json(
      { error: "Failed to record grid unlock" },
      { status: 500 }
    );
  }
}

// GET: Check if user has Unlimited Pass (for unlimited custom grids)
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const address = searchParams.get("address");

    if (!address) {
      return NextResponse.json(
        { error: "Missing address" },
        { status: 400 }
      );
    }

    const normalizedAddress = address.toLowerCase();

    // Fetch member registry
    const registryResult = await db
      .select()
      .from(kv)
      .where(eq(kv.key, MEMBER_REGISTRY_KEY))
      .limit(1);

    if (!registryResult[0]?.value) {
      return NextResponse.json({ hasUnlimitedPass: false, isMember: false });
    }

    const registry: MemberRegistry = JSON.parse(registryResult[0].value);

    // Find member
    const member = registry.members.find(
      (m) =>
        m.address.toLowerCase() === normalizedAddress ||
        m.linkedAddresses?.some((a) => a.toLowerCase() === normalizedAddress)
    );

    if (!member) {
      return NextResponse.json({ hasUnlimitedPass: false, isMember: false });
    }

    // Check for Unlimited Pass (includes unlimited grids + stacks).
    // Read all three field names for backwards compatibility with existing KV data.
    const hasUnlimitedPass = member.hasUnlimitedPass || member.hasUnlimitedStoragePass || member.hasGridPass || false;

    return NextResponse.json({
      hasUnlimitedPass,
      isMember: true,
      // Legacy field for backwards compatibility
      hasGridPass: hasUnlimitedPass,
      // How many individual grids they've unlocked (if not on unlimited plan)
      gridUnlockCount: member.gridUnlocks?.length || 0,
    });
  } catch (error) {
    console.error("[GET /api/membership/grid-pass] Error:", error);
    return NextResponse.json(
      { error: "Failed to check pass status" },
      { status: 500 }
    );
  }
}
src/app/api/membership/repair-pass/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * POST /api/membership/repair-pass
 *
 * Admin-only endpoint that backfills missing pass fields for a member whose
 * post-mint record update was lost (e.g. the storeRegistry(registry) bug where
 * the old snapshot was saved instead of the re-fetched one).
 *
 * Also re-attempts ENS subname minting if it wasn't set.
 *
 * Auth: Authorization: Bearer <ADMIN_KEY>
 *
 * Body:
 *   address       string  — wallet address of the affected member
 *   txHash        string  — the original mint tx hash (for on-chain re-verification)
 *   forceUpdate?  boolean — if true, overwrite even if hasStackPass is already true
 */

import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { mintEnsSubname, type MemberEntry } from "@/lib/agent-auth";
import { addMember, type MemberRegistry } from "@/lib/net-protocol";

const REGISTRY_KEY = "member-registry";
const PASS_CONTRACT = "0xce559a2a6b64504be00aa7aa85c5c31ea93a16bb";
const MINTED_TOPIC =
  "0xe7cd4ce7f2a465edc730269a1305e8a48bad821e8fb7e152ec413829c01a53c4";
const BASE_RPC = process.env.BASE_RPC_URL || "[REDACTED-RPC-URL]";

async function fetchRegistry(): Promise<MemberRegistry> {
  const empty: MemberRegistry = { members: [], nextMemberId: 1, lastUpdated: Date.now() };
  try {
    const result = await db.select().from(kv).where(eq(kv.key, REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) return empty;
    return JSON.parse(result[0].value) as MemberRegistry;
  } catch {
    return empty;
  }
}

async function storeRegistry(registry: MemberRegistry): Promise<boolean> {
  try {
    const jsonValue = JSON.stringify(registry);
    await db
      .insert(kv)
      .values({ key: REGISTRY_KEY, value: jsonValue })
      .onConflictDoUpdate({ target: kv.key, set: { value: jsonValue } });
    return true;
  } catch {
    return false;
  }
}

async function verifyMintOnChain(
  txHash: string,
  address: string
): Promise<{ valid: boolean; tokenId: number | null; tier: "we are so early" | "early-ish"; error?: string }> {
  const normalizedAddress = address.toLowerCase();
  const expectedTopic = "0x" + normalizedAddress.slice(2).padStart(64, "0");

  try {
    const resp = await fetch(BASE_RPC, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: 1,
        method: "eth_getTransactionReceipt",
        params: [txHash],
      }),
    });

    const json = (await resp.json()) as {
      result?: { logs?: Array<{ address: string; topics: string[] }> };
    };

    const logs = json.result?.logs ?? [];
    const mintLog = logs.find(
      (log) =>
        log.address.toLowerCase() === PASS_CONTRACT &&
        log.topics[0] === MINTED_TOPIC &&
        log.topics[1]?.toLowerCase() === expectedTopic
    );

    if (!mintLog) {
      return {
        valid: false,
        tokenId: null,
        tier: "early-ish",
        error: "Minted event not found in transaction",
      };
    }

    const tokenId = parseInt(mintLog.topics[2], 16);
    const tier: "we are so early" | "early-ish" = tokenId <= 1000 ? "we are so early" : "early-ish";
    return { valid: true, tokenId, tier };
  } catch (err) {
    return {
      valid: false,
      tokenId: null,
      tier: "early-ish",
      error: err instanceof Error ? err.message : "RPC error",
    };
  }
}

export async function POST(request: NextRequest) {
  // Auth
  const authHeader = request.headers.get("Authorization") || "";
  const adminKey = authHeader.startsWith("Bearer ") ? authHeader.slice(7).trim() : null;
  const expectedKey = process.env.ADMIN_KEY;

  if (!expectedKey) {
    return NextResponse.json({ error: "Admin endpoint not configured" }, { status: 503 });
  }
  if (!adminKey || adminKey !== expectedKey) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await request.json();
    const { address, txHash, forceUpdate = false, fid, username } = body as {
      address?: string;
      txHash?: string;
      forceUpdate?: boolean;
      fid?: number;
      username?: string;
    };

    if (!address || typeof address !== "string") {
      return NextResponse.json({ error: "address is required" }, { status: 400 });
    }
    if (!txHash || typeof txHash !== "string") {
      return NextResponse.json({ error: "txHash is required" }, { status: 400 });
    }

    const normalizedAddress = address.toLowerCase();

    // 1. Find member in registry
    const registry = await fetchRegistry();
    let member = registry.members.find(
      (m) =>
        m.address.toLowerCase() === normalizedAddress ||
        m.linkedAddresses?.some((a) => a.toLowerCase() === normalizedAddress)
    );

    if (!member) {
      // Member doesn't exist yet — create them now (pass purchase flow failed to persist)
      console.log(`[repair-pass] No member found for ${normalizedAddress} — creating now`);
      const { registry: updatedRegistry, member: newMember } = addMember(
        registry,
        address!,
        fid,
        username,
        txHash,
        "farcaster",
        false,
        undefined
      );
      // Replace registry and member references with the newly created ones
      Object.assign(registry, updatedRegistry);
      registry.members = updatedRegistry.members;
      registry.nextMemberId = updatedRegistry.nextMemberId;
      registry.lastUpdated = updatedRegistry.lastUpdated;
      member = updatedRegistry.members.find(
        (m) => m.address.toLowerCase() === normalizedAddress
      )!;
      console.log(`[repair-pass] Created member #${member.memberId} for ${normalizedAddress}`);
    }

    console.log(
      `[repair-pass] Found member #${member.memberId} for ${normalizedAddress}`
    );

    // 2. If already fully patched and forceUpdate=false, return early
    if (member.hasStackPass && member.unlimitedPassVerified && !forceUpdate) {
      return NextResponse.json({
        success: true,
        alreadyPatched: true,
        message: "Member already has a verified pass. Use forceUpdate=true to overwrite.",
        memberId: member.memberId,
        hasStackPass: member.hasStackPass,
        hasUnlimitedPass: member.hasUnlimitedPass,
        unlimitedPassVerified: member.unlimitedPassVerified,
        unlimitedPassTokenId: member.unlimitedPassTokenId,
        unlimitedPassTier: member.unlimitedPassTier,
      });
    }

    // 3. Verify the mint on-chain
    const verification = await verifyMintOnChain(txHash, normalizedAddress);

    const actions: string[] = [];

    if (!verification.valid) {
      console.warn(
        `[repair-pass] On-chain verification failed for ${normalizedAddress}: ${verification.error}. Applying pass fields without verified tokenId.`
      );
      // Still apply the pass — we trust the admin knows the tx is valid.
      // Mark as unverified so the verify endpoint can confirm later.
      member.hasStackPass = true;
      member.hasUnlimitedPass = true;
      member.stackPassTxHash = txHash;
      member.stackPassPurchasedAt = member.stackPassPurchasedAt ?? Date.now();
      member.unlimitedPassMintTx = txHash;
      member.unlimitedPassVerified = false;
      actions.push("applied pass fields (unverified — RPC unavailable)");
    } else {
      // Apply verified pass fields
      member.hasStackPass = true;
      member.hasUnlimitedPass = true;
      member.stackPassTxHash = txHash;
      member.stackPassPurchasedAt = member.stackPassPurchasedAt ?? Date.now();
      member.unlimitedPassTokenId = verification.tokenId!;
      member.unlimitedPassTier = verification.tier;
      member.unlimitedPassMintTx = txHash;
      member.unlimitedPassVerified = true;
      actions.push(
        `applied verified pass fields: token #${verification.tokenId} (${verification.tier})`
      );
      console.log(
        `[repair-pass] Verified on-chain: token #${verification.tokenId} (${verification.tier})`
      );
    }

    // 4. Save updated registry
    const saved = await storeRegistry(registry);
    if (!saved) {
      return NextResponse.json(
        { error: "Failed to persist updated registry" },
        { status: 500 }
      );
    }
    actions.push("registry saved");

    // 5. Re-attempt ENS mint if ensSubname looks unset or member has no subname
    const expectedEns = `${member.memberId}.netlibrary.eth`;
    if (!member.ensSubname || member.ensSubname !== expectedEns || forceUpdate) {
      // Ensure ensSubname is set on the record
      if (!member.ensSubname) {
        member.ensSubname = expectedEns;
        // Re-save with ensSubname populated
        await storeRegistry(registry);
        actions.push("ensSubname field populated in registry");
      }

      const ensResult = await mintEnsSubname(member.memberId, member.address, false);
      if (ensResult.success) {
        actions.push(`ENS subname ${expectedEns} minted successfully`);
      } else {
        actions.push(`ENS mint failed: ${ensResult.error}`);
        console.error(`[repair-pass] ENS mint failed for member #${member.memberId}: ${ensResult.error}`);
      }
    } else {
      actions.push(`ENS subname already set: ${member.ensSubname}`);
    }

    console.log(
      `[repair-pass] Repair complete for member #${member.memberId} (${normalizedAddress}): ${actions.join(", ")}`
    );

    return NextResponse.json({
      success: true,
      memberId: member.memberId,
      address: member.address,
      ensSubname: member.ensSubname,
      hasStackPass: member.hasStackPass,
      hasUnlimitedPass: member.hasUnlimitedPass,
      unlimitedPassVerified: member.unlimitedPassVerified,
      unlimitedPassTokenId: member.unlimitedPassTokenId,
      unlimitedPassTier: member.unlimitedPassTier,
      verified: verification.valid,
      actions,
    });
  } catch (err) {
    console.error("[repair-pass] Error:", err);
    return NextResponse.json({ error: "Internal server error" }, { status: 500 });
  }
}
src/app/api/membership/route.ts
/* eslint-disable @neynar/no-process-env */
// Force dynamic rendering — membership data (hasStackPass, hasUnlimitedPass) must
// never be served from Next.js static cache; always read live from KV.
export const dynamic = "force-dynamic";

import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import {
  addMember,
  isMember,
  isMemberByFid,
  isMemberByLinkedAddress,
  findAllMemberships,
  linkAddressToMember,
  type MemberRegistry,
  type SignupPlatform,
} from "@/lib/net-protocol";
import {
  awardAchievements,
  checkMembershipAchievements,
} from "@/lib/achievements-service";
import { verifyUsdcPayment, markTxUsed, PRICING, TREASURY_ADDRESS } from "@/lib/agent-auth";

const REGISTRY_KEY = "member-registry";
const PASS_CONTRACT = "0xCe559A2A6b64504bE00aa7aA85C5C31EA93a16BB";
const BASE_RPC = process.env.BASE_RPC_URL || "[REDACTED-RPC-URL]";

// On-chain check: hasUnlimitedPass(address) → bool
// selector 0x8a3b2044, address padded to 32 bytes
async function checkPassOnChain(address: string): Promise<boolean> {
  try {
    const paddedAddr = "0x8a3b2044" + address.slice(2).toLowerCase().padStart(64, "0");
    const resp = await fetch(BASE_RPC, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: 1,
        method: "eth_call",
        params: [{ to: PASS_CONTRACT, data: paddedAddr }, "latest"],
      }),
    });
    const json = (await resp.json()) as { result?: string };
    // result is a 32-byte hex — non-zero means true
    return !!json.result && BigInt(json.result) !== BigInt(0);
  } catch {
    return false;
  }
}

// Helper: Get KV value (for agent registry lookup)
async function getKV<T>(key: string): Promise<T | null> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, key)).limit(1);
    if (!result[0]?.value) return null;
    return JSON.parse(result[0].value) as T;
  } catch (error) {
    console.error(`[getKV] Error fetching ${key}:`, error);
    return null;
  }
}

// Direct DB fetch for member registry
async function fetchRegistry(): Promise<MemberRegistry> {
  const emptyRegistry: MemberRegistry = {
    members: [],
    nextMemberId: 1,
    lastUpdated: Date.now(),
  };

  try {
    console.log("[fetchRegistry] Querying KV for key:", REGISTRY_KEY);
    const result = await db.select().from(kv).where(eq(kv.key, REGISTRY_KEY)).limit(1);
    console.log("[fetchRegistry] Query result:", result.length > 0 ? "found" : "not found");

    if (!result[0]?.value) {
      console.log("[fetchRegistry] No existing registry, returning empty");
      return emptyRegistry;
    }

    const parsed = JSON.parse(result[0].value) as MemberRegistry;
    console.log("[fetchRegistry] Parsed registry with", parsed.members.length, "members");
    return parsed;
  } catch (error) {
    console.error("[fetchRegistry] Error:", error);
    return emptyRegistry;
  }
}

// Direct DB store for member registry
async function storeRegistry(registry: MemberRegistry): Promise<boolean> {
  try {
    console.log("[storeRegistry] Storing registry with", registry.members.length, "members");
    const jsonValue = JSON.stringify(registry);
    console.log("[storeRegistry] JSON length:", jsonValue.length);

    await db.insert(kv).values({ key: REGISTRY_KEY, value: jsonValue }).onConflictDoUpdate({
      target: kv.key,
      set: { value: jsonValue },
    });

    console.log("[storeRegistry] Store successful");
    return true;
  } catch (error) {
    console.error("[storeRegistry] Error:", error);
    return false;
  }
}

// NameStone API configuration
const NAMESTONE_API_URL = "https://namestone.com/api/public_v1/set-name";
const NAMESTONE_API_KEY = process.env.NAMESTONE_API_KEY || "";
const PARENT_DOMAIN = "netlibrary.eth";

// Mint ENS subname via NameStone
async function mintEnsSubname(
  memberId: number,
  walletAddress: string
): Promise<{ success: boolean; error?: string }> {
  if (!NAMESTONE_API_KEY) {
    console.error("NAMESTONE_API_KEY not configured");
    return { success: false, error: "ENS minting not configured" };
  }

  try {
    const response = await fetch(NAMESTONE_API_URL, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: NAMESTONE_API_KEY,
      },
      body: JSON.stringify({
        domain: PARENT_DOMAIN,
        name: String(memberId),
        address: walletAddress,
        text_records: {
          description: `Net Library Member #${memberId}`,
          "com.farcaster": "Net Library",
        },
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error("NameStone API error:", errorText);
      return { success: false, error: `NameStone error: ${response.status}` };
    }

    return { success: true };
  } catch (error) {
    console.error("NameStone API call failed:", error);
    return { success: false, error: "Failed to mint ENS subname" };
  }
}

export async function POST(request: NextRequest) {
  console.log("[POST /api/membership] Request received");

  try {
    const body = await request.json();
    const { address, fid, username, txHash, signupPlatform, verifiedAddresses } = body;
    const platform: SignupPlatform = signupPlatform || (fid ? "farcaster" : "base-app");
    console.log("[POST /api/membership] Body:", {
      address: address?.slice(0, 10) + "...",
      fid,
      username,
      txHash: txHash?.slice(0, 10) + "...",
      platform,
      verifiedAddressCount: verifiedAddresses?.length || 0
    });

    if (!address) {
      return NextResponse.json(
        { error: "Wallet address is required" },
        { status: 400 }
      );
    }

    // Fetch current registry directly from KV
    console.log("[POST /api/membership] Fetching registry...");
    const registry = await fetchRegistry();
    console.log("[POST /api/membership] Registry fetched, members:", registry.members.length);

    // Check if already a member by address
    const existingByAddress = isMember(registry, address);
    if (existingByAddress) {
      console.log("[POST /api/membership] Already a member by address:", existingByAddress.memberId);
      return NextResponse.json({
        success: true,
        alreadyMember: true,
        member: existingByAddress,
      });
    }

    // Check if this address is already linked to a membership
    const existingByLinked = isMemberByLinkedAddress(registry, address);
    if (existingByLinked) {
      console.log("[POST /api/membership] Already a member by linked address:", existingByLinked.memberId);
      return NextResponse.json({
        success: true,
        alreadyMember: true,
        member: existingByLinked,
        linkedAddress: true,
        note: "This wallet is linked to your existing membership",
      });
    }

    // Check by Farcaster ID to prevent duplicates when same user uses different wallets
    if (fid) {
      const existingByFid = isMemberByFid(registry, fid);
      if (existingByFid) {
        console.log("[POST /api/membership] Already a member by fid:", existingByFid.memberId, "fid:", fid);

        // Auto-link this new address to their existing membership
        const linkResult = linkAddressToMember(registry, existingByFid.memberId, address);
        if (linkResult.success) {
          await storeRegistry(linkResult.registry);
          const updatedMember = linkResult.registry.members.find(
            (m) => m.memberId === existingByFid.memberId
          );
          console.log("[POST /api/membership] Auto-linked address to existing membership");
          return NextResponse.json({
            success: true,
            alreadyMember: true,
            member: updatedMember || existingByFid,
            linkedAddress: true,
            note: "Your Farcaster account is already a member. This wallet has been linked to your membership.",
          });
        }

        // If linking failed (shouldn't happen), still return existing membership
        return NextResponse.json({
          success: true,
          alreadyMember: true,
          member: existingByFid,
          note: "Your Farcaster account is already registered with a different wallet address",
        });
      }
    }

    // ENHANCED: Check ALL Farcaster verified addresses for existing membership
    // This catches: Web user (Wallet A) later signs up via FC (Wallet B)
    // If Wallet A is verified on their FC account, we find the existing membership
    if (verifiedAddresses && Array.isArray(verifiedAddresses) && verifiedAddresses.length > 0) {
      for (const verifiedAddr of verifiedAddresses) {
        if (typeof verifiedAddr !== "string") continue;

        // Check if verified address is a primary address of existing membership
        const byVerified = isMember(registry, verifiedAddr);
        if (byVerified) {
          console.log("[POST /api/membership] Found existing membership via verified address:", byVerified.memberId);

          // Auto-link the new signing address to existing membership
          const linkResult = linkAddressToMember(registry, byVerified.memberId, address);
          if (linkResult.success) {
            await storeRegistry(linkResult.registry);
            const updatedMember = linkResult.registry.members.find(
              (m) => m.memberId === byVerified.memberId
            );
            return NextResponse.json({
              success: true,
              alreadyMember: true,
              member: updatedMember || byVerified,
              linkedAddress: true,
              note: "Found existing membership via your Farcaster verified addresses. This wallet has been linked.",
            });
          }

          return NextResponse.json({
            success: true,
            alreadyMember: true,
            member: byVerified,
            note: "You already have a membership registered with another verified wallet",
          });
        }

        // Check if verified address is a linked address
        const byVerifiedLinked = isMemberByLinkedAddress(registry, verifiedAddr);
        if (byVerifiedLinked) {
          console.log("[POST /api/membership] Found existing membership via verified linked address:", byVerifiedLinked.memberId);

          // Auto-link the new signing address
          const linkResult = linkAddressToMember(registry, byVerifiedLinked.memberId, address);
          if (linkResult.success) {
            await storeRegistry(linkResult.registry);
            const updatedMember = linkResult.registry.members.find(
              (m) => m.memberId === byVerifiedLinked.memberId
            );
            return NextResponse.json({
              success: true,
              alreadyMember: true,
              member: updatedMember || byVerifiedLinked,
              linkedAddress: true,
              note: "Found existing membership via your Farcaster verified addresses. This wallet has been linked.",
            });
          }

          return NextResponse.json({
            success: true,
            alreadyMember: true,
            member: byVerifiedLinked,
            note: "You already have a membership registered with another verified wallet",
          });
        }
      }
    }

    // Check if this new member is a registered agent
    let isAgent = false;
    let agentId: string | undefined;

    try {
      // Get all agent IDs from registry
      const agentRegistry = await getKV<string[]>("api-agents-registry");

      if (agentRegistry) {
        for (const id of agentRegistry) {
          const agent = await getKV<{
            id: string;
            address?: string;
            fid?: number;
            name?: string;
            pfpUrl?: string;
            isActive: boolean;
          }>(`api-agent:${id}`);

          if (!agent || !agent.isActive) continue;

          // Match by address or FID
          const addressMatch = agent.address && address &&
            agent.address.toLowerCase() === address.toLowerCase();
          const fidMatch = agent.fid && fid && agent.fid === fid;

          if (addressMatch || fidMatch) {
            isAgent = true;
            agentId = agent.id;
            console.log("[POST /api/membership] New member is a registered agent:", agentId);
            break;
          }
        }
      }
    } catch (err) {
      // Don't block membership creation if agent check fails
      console.error("[Membership] Agent check failed:", err);
    }

    // Verify USDC payment — txHash is required for new memberships
    if (!txHash) {
      return NextResponse.json(
        {
          error: "Payment required",
          message: `Membership costs ${PRICING.MEMBERSHIP} USDC. Send payment to the treasury address, then provide the txHash.`,
          treasuryAddress: TREASURY_ADDRESS,
          price: `${PRICING.MEMBERSHIP} USDC`,
        },
        { status: 402 }
      );
    }

    const paymentResult = await verifyUsdcPayment(txHash, PRICING.MEMBERSHIP, address);
    if (!paymentResult.valid) {
      console.error("[POST /api/membership] Payment verification failed:", paymentResult.error);
      return NextResponse.json(
        {
          error: paymentResult.error || "Payment verification failed",
          treasuryAddress: TREASURY_ADDRESS,
          price: `${PRICING.MEMBERSHIP} USDC`,
        },
        { status: 402 }
      );
    }

    // Mark transaction as used to prevent replay attacks
    await markTxUsed(txHash, "membership");

    // Add new member to registry (gets next available ID)
    console.log("[POST /api/membership] Adding new member...");
    const { registry: updatedRegistry, member: newMember } = addMember(
      registry,
      address,
      fid,
      username,
      txHash,
      platform,
      isAgent,
      agentId
    );
    console.log("[POST /api/membership] New member created:", newMember.memberId, newMember.ensSubname, isAgent ? `(agent: ${agentId})` : "");

    // Mint ENS subname via NameStone
    console.log("[POST /api/membership] Minting ENS subname...");
    const ensResult = await mintEnsSubname(newMember.memberId, address);
    console.log("[POST /api/membership] ENS result:", ensResult);

    if (!ensResult.success) {
      console.error("[POST /api/membership] ENS minting failed:", ensResult.error);
    }

    // Persist the updated registry directly to KV
    console.log("[POST /api/membership] Storing registry...");
    const storeSuccess = await storeRegistry(updatedRegistry);
    console.log("[POST /api/membership] Store result:", storeSuccess);

    if (!storeSuccess) {
      console.error("[POST /api/membership] Failed to persist member registry - returning error");
      return NextResponse.json({
        success: false,
        error: "Failed to save membership to database",
        member: newMember,
        ensSuccess: ensResult.success,
      }, { status: 500 });
    }

    // Verify the store worked by fetching again
    console.log("[POST /api/membership] Verifying store...");
    const verifyRegistry = await fetchRegistry();
    const verifiedMember = isMember(verifyRegistry, address);
    console.log("[POST /api/membership] Verification - found member:", !!verifiedMember);

    // Award membership achievements
    const achievementsToAward = checkMembershipAchievements({
      memberId: newMember.memberId,
      joinedAt: newMember.joinedAt,
    });
    let awardedAchievements: string[] = [];
    if (achievementsToAward.length > 0) {
      const result = await awardAchievements(address, achievementsToAward);
      awardedAchievements = result.awarded;
      console.log("[POST /api/membership] Awarded achievements:", awardedAchievements);
    }

    return NextResponse.json({
      success: true,
      alreadyMember: false,
      member: newMember,
      ensSuccess: ensResult.success,
      ensError: ensResult.error,
      dbStored: storeSuccess,
      verified: !!verifiedMember,
      achievements: awardedAchievements,
    });
  } catch (error) {
    console.error("[POST /api/membership] Error:", error);
    return NextResponse.json(
      { error: "Failed to process membership" },
      { status: 500 }
    );
  }
}

// GET endpoint to check membership status
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const address = searchParams.get("address");
  const fidStr = searchParams.get("fid");
  const fid = fidStr ? parseInt(fidStr, 10) : undefined;
  // Farcaster verified addresses - comma-separated list of addresses from Neynar
  const verifiedAddressesParam = searchParams.get("verifiedAddresses");
  const verifiedAddresses = verifiedAddressesParam ? verifiedAddressesParam.split(",").filter(a => a.length > 0) : undefined;

  console.log("[GET /api/membership] Query params:", {
    address: address?.slice(0, 10) + "...",
    fid,
    verifiedAddresses: verifiedAddresses?.length || 0,
  });

  if (!address) {
    return NextResponse.json(
      { error: "Address parameter is required" },
      { status: 400 }
    );
  }

  try {
    const registry = await fetchRegistry();

    // Find ALL memberships for this user (handles duplicates)
    // Each membership is real - they paid for each one
    // Pass verifiedAddresses to also find memberships via Farcaster verified addresses
    const allMemberships = findAllMemberships(registry, address, fid, verifiedAddresses);

    console.log("[GET /api/membership] Result - isMember:", allMemberships.length > 0, "memberships:", allMemberships.map(m => ({ id: m.memberId, platform: m.signupPlatform })), "totalMembers:", registry.members.length);

    // Build a set of all user addresses for matchType determination
    const allUserAddresses = new Set<string>();
    allUserAddresses.add(address.toLowerCase());
    verifiedAddresses?.forEach(a => allUserAddresses.add(a.toLowerCase()));

    // Determine how each membership was found
    const membershipsWithMatchType = allMemberships.map(m => {
      let matchType: "primary" | "fid" | "linked" | "verified" = "primary";
      if (m.address.toLowerCase() === address.toLowerCase()) {
        matchType = "primary";
      } else if (fid && m.fid === fid) {
        matchType = "fid";
      } else if (m.linkedAddresses?.some(
        (linked) => linked.toLowerCase() === address.toLowerCase()
      )) {
        matchType = "linked";
      } else if (verifiedAddresses?.some(va => va.toLowerCase() === m.address.toLowerCase())) {
        // Found via Farcaster verified address
        matchType = "verified";
      }
      return {
        memberId: m.memberId,
        ensSubname: m.ensSubname,
        signupPlatform: m.signupPlatform || "unknown",
        joinedAt: m.joinedAt,
        fid: m.fid,
        username: m.username,
        address: m.address,
        matchType,
        // Web platform fields
        wid: m.wid,
        customUsername: m.customUsername,
        customPfpUrl: m.customPfpUrl,
        linkedFid: m.linkedFid,
        // Agent identity fields
        isAgent: m.isAgent || false,
        agentId: m.agentId || undefined,
      };
    });

    // On-chain hasUnlimitedPass check for the primary member and each allMemberships entry.
    // Run checks in parallel — one per unique address.
    let primaryHasPass = false;
    let membershipsWithPass = membershipsWithMatchType;

    if (allMemberships.length > 0) {
      // Collect unique addresses to check (primary member + all membership addresses)
      const uniqueAddresses = Array.from(
        new Set([
          allMemberships[0].address.toLowerCase(),
          ...membershipsWithMatchType.map((m) => m.address.toLowerCase()),
        ])
      );

      // Check KV flag first — if already set on record, skip on-chain call for that address
      const passResults = await Promise.all(
        uniqueAddresses.map(async (addr) => {
          // Check if KV record already has a verified pass flag
          const kvMember = allMemberships.find(
            (m) => m.address.toLowerCase() === addr ||
              m.linkedAddresses?.some((la) => la.toLowerCase() === addr)
          );
          if (kvMember?.hasUnlimitedPass || kvMember?.hasStackPass) {
            return { addr, hasPass: true };
          }
          const onChain = await checkPassOnChain(addr);
          return { addr, hasPass: onChain };
        })
      );

      const passMap = new Map(passResults.map((r) => [r.addr, r.hasPass]));

      primaryHasPass = passMap.get(allMemberships[0].address.toLowerCase()) ?? false;

      membershipsWithPass = membershipsWithMatchType.map((m) => ({
        ...m,
        hasUnlimitedPass: passMap.get(m.address.toLowerCase()) ?? false,
      }));
    }

    return NextResponse.json({
      isMember: allMemberships.length > 0,
      // For backward compatibility, return first membership as "member"
      member: allMemberships.length > 0
        ? { ...allMemberships[0], hasUnlimitedPass: primaryHasPass }
        : null,
      // Return ALL memberships with full data
      allMemberships: membershipsWithPass.length > 0 ? membershipsWithPass : null,
      totalMembers: registry.members.length,
    });
  } catch (error) {
    console.error("[GET /api/membership] Error:", error);
    return NextResponse.json(
      { error: "Failed to check membership" },
      { status: 500 }
    );
  }
}

// PUT endpoint to restore/add a member (admin use only - for fixing data)
export async function PUT(request: NextRequest) {
  // Admin key must be provided as Authorization: Bearer <key>
  // Query-string keys get logged by proxies/CDNs — never use them for secrets
  const authHeader = request.headers.get("Authorization") || "";
  const adminKey = authHeader.startsWith("Bearer ") ? authHeader.slice(7).trim() : null;

  const expectedKey = process.env.ADMIN_KEY;
  if (!expectedKey) {
    return NextResponse.json({ error: "Admin endpoint not configured" }, { status: 503 });
  }
  if (!adminKey || adminKey !== expectedKey) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = await request.json();
    const { memberId, username, address, fid, ensSubname, joinedAt, txHash, signupPlatform } = body;

    if (!memberId || !address) {
      return NextResponse.json({ error: "memberId and address required" }, { status: 400 });
    }

    const registry = await fetchRegistry();

    // Check if this memberId already exists
    const existingIndex = registry.members.findIndex(m => m.memberId === memberId);
    if (existingIndex >= 0) {
      return NextResponse.json({
        error: `Member #${memberId} already exists`,
        existingMember: registry.members[existingIndex],
      }, { status: 409 });
    }

    // Add the member
    const newMember = {
      memberId,
      address,
      ensSubname: ensSubname || `${memberId}.netlibrary.eth`,
      fid: fid || undefined,
      username: username || undefined,
      joinedAt: joinedAt || Date.now(),
      txHash: txHash || undefined,
      signupPlatform: signupPlatform || "farcaster",
    };

    registry.members.push(newMember);
    registry.members.sort((a, b) => a.memberId - b.memberId);
    registry.lastUpdated = Date.now();

    // Update nextMemberId if needed
    if (memberId >= registry.nextMemberId) {
      registry.nextMemberId = memberId + 1;
    }

    const stored = await storeRegistry(registry);
    if (!stored) {
      return NextResponse.json({ error: "Failed to store updated registry" }, { status: 500 });
    }

    return NextResponse.json({
      success: true,
      member: newMember,
      totalMembers: registry.members.length,
    });
  } catch (error) {
    console.error("[PUT /api/membership] Error:", error);
    return NextResponse.json({ error: "Failed to add member" }, { status: 500 });
  }
}

// DELETE endpoint to remove duplicate members (admin use only)
export async function DELETE(request: NextRequest) {
  // Admin key must be provided as Authorization: Bearer <key>
  const authHeader = request.headers.get("Authorization") || "";
  const adminKey = authHeader.startsWith("Bearer ") ? authHeader.slice(7).trim() : null;

  const expectedKey = process.env.ADMIN_KEY;
  if (!expectedKey) {
    return NextResponse.json({ error: "Admin endpoint not configured" }, { status: 503 });
  }
  if (!adminKey || adminKey !== expectedKey) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { searchParams } = new URL(request.url);
  const memberIdStr = searchParams.get("memberId");

  if (!memberIdStr) {
    return NextResponse.json({ error: "memberId required" }, { status: 400 });
  }

  const memberId = parseInt(memberIdStr, 10);
  if (isNaN(memberId)) {
    return NextResponse.json({ error: "Invalid memberId" }, { status: 400 });
  }

  try {
    const registry = await fetchRegistry();
    const memberIndex = registry.members.findIndex(m => m.memberId === memberId);

    if (memberIndex === -1) {
      return NextResponse.json({ error: `Member #${memberId} not found` }, { status: 404 });
    }

    const removedMember = registry.members[memberIndex];
    registry.members.splice(memberIndex, 1);

    const stored = await storeRegistry(registry);
    if (!stored) {
      return NextResponse.json({ error: "Failed to store updated registry" }, { status: 500 });
    }

    return NextResponse.json({
      success: true,
      removed: removedMember,
      remainingMembers: registry.members.length,
    });
  } catch (error) {
    console.error("[DELETE /api/membership] Error:", error);
    return NextResponse.json({ error: "Failed to remove member" }, { status: 500 });
  }
}
src/app/api/membership/seed/route.ts
/* eslint-disable @neynar/no-process-env */
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import {
  type MemberRegistry,
  type MemberEntry,
} from "@/lib/net-protocol";

const REGISTRY_KEY = "member-registry";

// Direct DB fetch for member registry
async function fetchRegistry(): Promise<MemberRegistry> {
  const emptyRegistry: MemberRegistry = {
    members: [],
    nextMemberId: 1,
    lastUpdated: Date.now(),
  };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) return emptyRegistry;
    return JSON.parse(result[0].value) as MemberRegistry;
  } catch (error) {
    console.error("fetchRegistry error:", error);
    return emptyRegistry;
  }
}

// Direct DB store for member registry
async function storeRegistry(registry: MemberRegistry): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: REGISTRY_KEY, value: JSON.stringify(registry) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(registry) },
    });
    return true;
  } catch (error) {
    console.error("storeRegistry error:", error);
    return false;
  }
}

// Seed endpoint to add existing members who paid under the old registry format
// This is a one-time migration endpoint

// Known existing members who paid - add their details here
const EXISTING_MEMBERS: Omit<MemberEntry, "memberId" | "ensSubname">[] = [
  {
    address: "0x18A432D008a0e5E1D611eae194EE3bdc7FD3f3FA",
    fid: 282520,
    username: "geaux",
    joinedAt: Date.now(),
  },
  {
    address: "0x2be743907dc805099b16351717b2b8f09b7d5938",
    fid: 248216,
    username: "member2",
    joinedAt: Date.now(),
  },
];

export async function POST(request: NextRequest) {
  try {
    // Simple auth - require a secret key
    const { secret, members, force } = await request.json();

    if (!process.env.ADMIN_SECRET || secret !== process.env.ADMIN_SECRET) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // If force=true, start with empty registry (replace existing)
    const registry = force ? {
      members: [],
      nextMemberId: 1,
      lastUpdated: Date.now(),
    } : await fetchRegistry();

    // Members to add (from request or from hardcoded list)
    const membersToAdd: Omit<MemberEntry, "memberId" | "ensSubname">[] = members || EXISTING_MEMBERS;

    if (membersToAdd.length === 0) {
      return NextResponse.json({ error: "No members to add" }, { status: 400 });
    }

    // Add each member that doesn't already exist
    let addedCount = 0;
    const updatedMembers = [...registry.members];
    let nextId = registry.nextMemberId;

    for (const memberData of membersToAdd) {
      // Check if already exists
      const exists = updatedMembers.some(
        (m) => m.address.toLowerCase() === memberData.address.toLowerCase()
      );

      if (!exists) {
        const newMember: MemberEntry = {
          memberId: nextId,
          address: memberData.address,
          ensSubname: `${nextId}.netlibrary.eth`,
          fid: memberData.fid,
          username: memberData.username,
          joinedAt: memberData.joinedAt || Date.now(),
          txHash: memberData.txHash,
        };

        updatedMembers.push(newMember);
        nextId++;
        addedCount++;
      }
    }

    if (addedCount === 0) {
      return NextResponse.json({
        success: true,
        message: "All members already exist",
        totalMembers: updatedMembers.length,
      });
    }

    // Save updated registry
    const updatedRegistry: MemberRegistry = {
      members: updatedMembers,
      nextMemberId: nextId,
      lastUpdated: Date.now(),
    };

    const storeSuccess = await storeRegistry(updatedRegistry);

    if (!storeSuccess) {
      return NextResponse.json(
        { error: "Failed to store registry" },
        { status: 500 }
      );
    }

    return NextResponse.json({
      success: true,
      addedCount,
      totalMembers: updatedMembers.length,
      nextMemberId: nextId,
    });
  } catch (error) {
    console.error("Seed error:", error);
    return NextResponse.json(
      { error: "Failed to seed members" },
      { status: 500 }
    );
  }
}

// GET to check current registry status
export async function GET() {
  try {
    const registry = await fetchRegistry();

    return NextResponse.json({
      totalMembers: registry.members.length,
      nextMemberId: registry.nextMemberId,
      members: registry.members.map((m) => ({
        memberId: m.memberId,
        username: m.username,
        ensSubname: m.ensSubname,
        address: m.address.slice(0, 10) + "...",
      })),
    });
  } catch (error) {
    console.error("Seed GET error:", error);
    return NextResponse.json(
      { error: "Failed to fetch registry" },
      { status: 500 }
    );
  }
}
src/app/api/membership/stack-pass/route.ts
/* eslint-disable @neynar/no-process-env */
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { mintEnsSubname, type MemberEntry } from "@/lib/agent-auth";
import type { MemberRegistry } from "@/lib/net-protocol";

const REGISTRY_KEY = "member-registry";
const STACKS_KEY = "stacks-registry";
const _STACK_PASS_COST = 10; // $10 USDC — Unlimited Pass

// Direct DB fetch for member registry
async function fetchRegistry(): Promise<MemberRegistry> {
  const emptyRegistry: MemberRegistry = {
    members: [],
    nextMemberId: 1,
    lastUpdated: Date.now(),
  };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) {
      return emptyRegistry;
    }
    return JSON.parse(result[0].value) as MemberRegistry;
  } catch (error) {
    console.error("[stack-pass] Error fetching registry:", error);
    return emptyRegistry;
  }
}

// Direct DB store for member registry
async function storeRegistry(registry: MemberRegistry): Promise<boolean> {
  try {
    const jsonValue = JSON.stringify(registry);
    await db.insert(kv).values({ key: REGISTRY_KEY, value: jsonValue }).onConflictDoUpdate({
      target: kv.key,
      set: { value: jsonValue },
    });
    return true;
  } catch (error) {
    console.error("[stack-pass] Error storing registry:", error);
    return false;
  }
}

// Fetch stacks registry
interface Stack {
  id: string;
  name: string;
  owner: string;
  unlocked: boolean;
  itemCount: number;
  [key: string]: unknown;
}

interface StacksRegistry {
  stacks: Stack[];
  lastUpdated: number;
}

async function fetchStacksRegistry(): Promise<StacksRegistry> {
  const emptyRegistry: StacksRegistry = {
    stacks: [],
    lastUpdated: Date.now(),
  };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, STACKS_KEY)).limit(1);
    if (!result[0]?.value) {
      return emptyRegistry;
    }
    return JSON.parse(result[0].value) as StacksRegistry;
  } catch (error) {
    console.error("[stack-pass] Error fetching stacks:", error);
    return emptyRegistry;
  }
}

async function storeStacksRegistry(registry: StacksRegistry): Promise<boolean> {
  try {
    const jsonValue = JSON.stringify(registry);
    await db.insert(kv).values({ key: STACKS_KEY, value: jsonValue }).onConflictDoUpdate({
      target: kv.key,
      set: { value: jsonValue },
    });
    return true;
  } catch (error) {
    console.error("[stack-pass] Error storing stacks:", error);
    return false;
  }
}

// =============================================================================
// NFT contract constants
// =============================================================================

const PASS_CONTRACT = "0xce559a2a6b64504be00aa7aa85c5c31ea93a16bb";
// Minted(address indexed to, uint256 indexed tokenId, string tier)
const MINTED_TOPIC =
  "0xe7cd4ce7f2a465edc730269a1305e8a48bad821e8fb7e152ec413829c01a53c4";
const BASE_RPC = process.env.BASE_RPC_URL || "[REDACTED-RPC-URL]";

// =============================================================================
// Helper: verify NFT mint on-chain via Base JSON-RPC
// =============================================================================

interface MintVerification {
  valid: boolean;
  tokenId: number | null;
  tier: "we are so early" | "early-ish";
  error?: string;
}

async function verifyNftMint(
  txHash: string,
  address: string
): Promise<MintVerification> {
  const normalizedAddress = address.toLowerCase();

  try {
    const body = JSON.stringify({
      jsonrpc: "2.0",
      id: 1,
      method: "eth_getTransactionReceipt",
      params: [txHash],
    });

    const resp = await fetch(BASE_RPC, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body,
    });

    const json = await resp.json() as {
      result?: {
        logs?: Array<{
          address: string;
          topics: string[];
        }>;
      };
    };

    // topic[1] is the recipient address left-padded to 32 bytes — use exact match
    const expectedTopic = "0x" + normalizedAddress.slice(2).padStart(64, "0");

    const logs = json.result?.logs ?? [];
    const mintLog = logs.find(
      (log) =>
        log.address.toLowerCase() === PASS_CONTRACT &&
        log.topics[0] === MINTED_TOPIC &&
        log.topics[1]?.toLowerCase() === expectedTopic
    );

    if (!mintLog) {
      return {
        valid: false,
        tokenId: null,
        tier: "early-ish",
        error: "NFT mint event not found in transaction",
      };
    }

    const tokenId = parseInt(mintLog.topics[2], 16);
    const tier: "we are so early" | "early-ish" =
      tokenId <= 1000 ? "we are so early" : "early-ish";

    return { valid: true, tokenId, tier };
  } catch (err) {
    console.error("[stack-pass] verifyNftMint error:", err);
    return {
      valid: false,
      tokenId: null,
      tier: "early-ish",
      error: "Failed to verify transaction on-chain",
    };
  }
}

// =============================================================================
// Helper: resolve Farcaster identity (FID, username, displayName) from address
// via Neynar bulk-by-address API. Returns undefined fields on failure — callers
// should proceed without them (bare-address member is acceptable).
// =============================================================================

interface FarcasterIdentity {
  fid?: number;
  username?: string;
  displayName?: string;
}

async function resolveFarcasterIdentity(address: string): Promise<FarcasterIdentity> {
  const neynarApiKey = process.env.NEYNAR_API_KEY;
  if (!neynarApiKey) {
    console.warn("[stack-pass] NEYNAR_API_KEY not set — skipping identity resolution");
    return {};
  }

  try {
    const url = `https://api.neynar.com/v2/farcaster/user/bulk-by-address?addresses=${address.toLowerCase()}`;
    const resp = await fetch(url, {
      headers: { "accept": "application/json", "x-api-key": neynarApiKey },
    });

    if (!resp.ok) {
      console.warn(`[stack-pass] Neynar bulk-by-address returned ${resp.status} for ${address}`);
      return {};
    }

    const data = await resp.json() as Record<string, Array<{
      fid?: number;
      username?: string;
      display_name?: string;
    }>>;

    // Response is a map of address → array of users
    const users = data[address.toLowerCase()] ?? [];
    if (users.length === 0) {
      console.log(`[stack-pass] No Farcaster user found for address ${address}`);
      return {};
    }

    // Pick the first result (primary Farcaster user for this address)
    const user = users[0];
    return {
      fid: user.fid,
      username: user.username,
      displayName: user.display_name,
    };
  } catch (err) {
    console.error("[stack-pass] resolveFarcasterIdentity error:", err);
    return {};
  }
}

// =============================================================================
// Helper: grant membership internally — direct registry write (reliable in
// serverless; avoids addMemberAtomically's raw transaction which can silently
// fail to commit under cold-start / connection-pool conditions).
// =============================================================================

async function grantMembershipInternal(
  walletAddress: string,
  source: string,
  identity?: FarcasterIdentity
): Promise<{
  success: boolean;
  memberId?: number;
  ensSubname?: string;
  isDuplicate?: boolean;
  error?: string;
}> {
  try {
    const registry = await fetchRegistry();

    // Duplicate check — same address already registered
    const existing = registry.members.find(
      (m) => m.address.toLowerCase() === walletAddress.toLowerCase()
    );
    if (existing) {
      return {
        success: true,
        isDuplicate: true,
        memberId: existing.memberId,
        ensSubname: existing.ensSubname,
      };
    }

    // Assign next ID and build entry
    const memberId = registry.nextMemberId;
    const ensSubname = `${memberId}.netlibrary.eth`;
    const newMember: MemberEntry = {
      memberId,
      address: walletAddress,
      ensSubname,
      fid: identity?.fid,
      username: identity?.username,
      displayName: identity?.displayName,
      joinedAt: Date.now(),
      grantType: "admin",
      grantedBy: source,
      signupPlatform: "farcaster",
    };

    registry.members.push(newMember);
    registry.nextMemberId = memberId + 1;

    const saved = await storeRegistry(registry);
    if (!saved) {
      return { success: false, error: "Failed to persist member registry" };
    }

    // Mint ENS subname (best-effort — member record is committed regardless)
    const mintResult = await mintEnsSubname(memberId, walletAddress, false);
    if (!mintResult.success) {
      console.error(
        `[stack-pass] ENS mint failed for auto-granted member #${memberId}: ${mintResult.error}`
      );
    }

    return { success: true, isDuplicate: false, memberId, ensSubname };
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    console.error("[stack-pass] grantMembershipInternal error:", msg);
    return { success: false, error: msg };
  }
}

// =============================================================================
// POST - Purchase / record stack pass
// =============================================================================

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const {
      address,
      txHash,
      nftMint,
      tokenId: clientTokenId,
      tier: clientTier,
    } = body as {
      address?: unknown;
      txHash?: unknown;
      nftMint?: boolean;
      tokenId?: number;
      tier?: string;
    };

    if (!address || typeof address !== "string") {
      return NextResponse.json({ success: false, error: "Address is required" }, { status: 400 });
    }

    if (!txHash || typeof txHash !== "string") {
      return NextResponse.json({ success: false, error: "Transaction hash is required" }, { status: 400 });
    }

    const normalizedAddress = address.toLowerCase();

    // =========================================================================
    // Flow A: NFT mint — verify on-chain, support non-members via auto-grant
    // =========================================================================
    if (nftMint === true) {
      // Verify the mint transaction on-chain
      const mintVerification = await verifyNftMint(txHash, normalizedAddress);

      if (!mintVerification.valid) {
        // On-chain verification failed (RPC slow/unavailable). For "we are so early"
        // tier (token IDs 1–1000), the mint already succeeded on-chain — grant
        // membership optimistically. unlimitedPassVerified=false flags the record
        // as pending confirmation; the verify endpoint will confirm it later.
        //
        // We trust the client-provided tokenId/tier ONLY for determining whether
        // this is "we are so early" (tokenId ≤ 1000). All other perks require
        // confirmed on-chain data.
        console.warn(
          `[stack-pass] NFT mint verification failed for ${normalizedAddress}: ${mintVerification.error}. ` +
          `Client tokenId=${clientTokenId} tier=${clientTier}. Storing as unverified.`
        );

        const isEarlyTierOptimistic =
          (clientTier === "we are so early") ||
          (typeof clientTokenId === "number" && clientTokenId >= 1 && clientTokenId <= 1000);

        const registry = await fetchRegistry();
        let member = registry.members.find((m) => {
          if (m.address.toLowerCase() === normalizedAddress) return true;
          if (m.linkedAddresses?.some((a) => a.toLowerCase() === normalizedAddress))
            return true;
          return false;
        });

        // For early tier non-members: optimistically grant membership now
        let membershipGranted = false;
        let grantedMemberId: number | undefined;
        let grantedEnsSubname: string | undefined;

        if (!member && isEarlyTierOptimistic) {
          // Resolve Farcaster identity before creating the member record
          const identity = await resolveFarcasterIdentity(normalizedAddress);
          const grantResult = await grantMembershipInternal(
            normalizedAddress,
            "unlimited-pass-early-optimistic",
            identity
          );
          if (grantResult.success) {
            membershipGranted = !grantResult.isDuplicate;
            grantedMemberId = grantResult.memberId;
            grantedEnsSubname = grantResult.ensSubname;
            // Re-fetch to get the committed record
            const refreshed = await fetchRegistry();
            member = refreshed.members.find((m) => {
              if (m.address.toLowerCase() === normalizedAddress) return true;
              if (m.linkedAddresses?.some((a) => a.toLowerCase() === normalizedAddress))
                return true;
              return false;
            });
            // Apply pass fields to the freshly re-fetched registry
            if (member) {
              member.hasStackPass = true;
              member.stackPassTxHash = txHash;
              member.stackPassPurchasedAt = Date.now();
              member.unlimitedPassMintTx = txHash;
              member.unlimitedPassVerified = false;
              // Store the client-provided tokenId/tier as preliminary values
              // (will be overwritten with confirmed values when verify succeeds)
              if (typeof clientTokenId === "number") {
                member.unlimitedPassTokenId = clientTokenId;
              }
              if (clientTier === "we are so early" || clientTier === "early-ish") {
                member.unlimitedPassTier = clientTier;
              }
              await storeRegistry(refreshed);
            }
          }
        } else if (member) {
          // Member already exists — record the tx hash, mark unverified
          member.hasStackPass = true;
          member.stackPassTxHash = txHash;
          member.stackPassPurchasedAt = Date.now();
          member.unlimitedPassMintTx = txHash;
          member.unlimitedPassVerified = false;
          if (typeof clientTokenId === "number") {
            member.unlimitedPassTokenId = clientTokenId;
          }
          if (clientTier === "we are so early" || clientTier === "early-ish") {
            member.unlimitedPassTier = clientTier;
          }
          await storeRegistry(registry);
        }

        return NextResponse.json({
          success: true,
          verified: false,
          message: membershipGranted
            ? "Mint recorded. Membership granted (pending on-chain confirmation)."
            : "Mint recorded. Membership grant pending on-chain verification.",
          nftMint: true,
          membershipGranted,
          memberId: grantedMemberId,
          ensSubname: grantedEnsSubname,
        });
      }

      // On-chain verification succeeded — use verified values only
      const resolvedTokenId = mintVerification.tokenId;
      const resolvedTier = mintVerification.tier;

      // Get or create member record
      const registry = await fetchRegistry();

      let member = registry.members.find((m) => {
        if (m.address.toLowerCase() === normalizedAddress) return true;
        if (m.linkedAddresses?.some((a) => a.toLowerCase() === normalizedAddress))
          return true;
        return false;
      });

      // Auto-grant membership for "we are so early" non-members (verified on-chain)
      let membershipGranted = false;
      let grantedMemberId: number | undefined;
      let grantedEnsSubname: string | undefined;

      // activeRegistry tracks which registry snapshot contains our `member` reference.
      // When grantMembershipInternal creates a new member, it writes its own snapshot,
      // so we must re-fetch to get a snapshot that includes the new member — and then
      // storeRegistry MUST use that re-fetched snapshot, not the original `registry`.
      let activeRegistry = registry;

      if (!member && resolvedTier === "we are so early") {
        // Resolve Farcaster identity so the member appears in the directory with
        // their username instead of a bare address
        const identity = await resolveFarcasterIdentity(normalizedAddress);
        const grantResult = await grantMembershipInternal(
          normalizedAddress,
          "unlimited-pass-early",
          identity
        );
        if (grantResult.success) {
          membershipGranted = !grantResult.isDuplicate;
          grantedMemberId = grantResult.memberId;
          grantedEnsSubname = grantResult.ensSubname;
          // Re-fetch registry to get the snapshot that includes the new member.
          // CRITICAL: activeRegistry must point to this refreshed snapshot so that
          // storeRegistry below saves the correct version.
          const refreshed = await fetchRegistry();
          activeRegistry = refreshed;
          member = refreshed.members.find((m) => {
            if (m.address.toLowerCase() === normalizedAddress) return true;
            if (m.linkedAddresses?.some((a) => a.toLowerCase() === normalizedAddress))
              return true;
            return false;
          });
        }
      }

      if (!member) {
        // For "early-ish" non-members, they need to join separately
        // But still record the pass attempt — return partial success
        console.log(
          `[stack-pass] NFT mint recorded for non-member ${normalizedAddress} (${resolvedTier})`
        );
        return NextResponse.json({
          success: true,
          verified: true,
          message: "Unlimited Pass recorded. Membership required for full access.",
          nftMint: true,
          tokenId: resolvedTokenId,
          tier: resolvedTier,
          membershipRequired: true,
        });
      }

      // Already has the pass and it's verified? Idempotent — return success
      if (member.hasStackPass && member.unlimitedPassVerified) {
        return NextResponse.json({
          success: true,
          message: "Already has Unlimited Pass",
          nftMint: true,
          verified: true,
          tokenId: member.unlimitedPassTokenId ?? resolvedTokenId,
          tier: member.unlimitedPassTier ?? resolvedTier,
          membershipGranted,
          memberId: grantedMemberId ?? member.memberId,
          ensSubname: grantedEnsSubname ?? member.ensSubname,
        });
      }

      // Update member record with verified data.
      // `member` is a reference into `activeRegistry.members` — mutating it here
      // and then calling storeRegistry(activeRegistry) persists the changes atomically.
      member.hasStackPass = true;
      member.hasUnlimitedPass = true;
      member.stackPassTxHash = txHash;
      member.stackPassPurchasedAt = Date.now();
      if (resolvedTokenId !== null) {
        member.unlimitedPassTokenId = resolvedTokenId;
      }
      member.unlimitedPassTier = resolvedTier;
      member.unlimitedPassMintTx = txHash;
      member.unlimitedPassVerified = true;

      const saved = await storeRegistry(activeRegistry);
      if (!saved) {
        return NextResponse.json(
          { success: false, error: "Failed to save pass record" },
          { status: 500 }
        );
      }

      // Retroactively unlock stacks
      await unlockMemberStacks(member);

      console.log(
        `[stack-pass] NFT mint verified and recorded: ${normalizedAddress} → token #${resolvedTokenId} (${resolvedTier})`
      );

      return NextResponse.json({
        success: true,
        verified: true,
        message: "Unlimited Pass activated!",
        nftMint: true,
        tokenId: resolvedTokenId,
        tier: resolvedTier,
        membershipGranted,
        memberId: grantedMemberId ?? member.memberId,
        ensSubname: grantedEnsSubname ?? member.ensSubname,
      });
    }

    // =========================================================================
    // Flow B removed — all passes go through NFT mint (Flow A).
    // The legacy USDC transfer path accepted unverified tx hashes and has been
    // removed to prevent free-pass exploits.
    // =========================================================================
    return NextResponse.json(
      { success: false, error: "Please mint the Unlimited Pass NFT to activate. Visit the mint page to get started." },
      { status: 400 }
    );
  } catch (error) {
    console.error("[stack-pass] Error:", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 }
    );
  }
}

// =============================================================================
// Helper: retroactively unlock all stacks for a member
// =============================================================================

interface MemberLike {
  memberId: number;
  address: string;
  linkedAddresses?: string[];
}

async function unlockMemberStacks(member: MemberLike): Promise<void> {
  const stacksRegistry = await fetchStacksRegistry();
  let unlockedCount = 0;

  const memberAddresses = [member.address.toLowerCase()];
  if (member.linkedAddresses) {
    memberAddresses.push(
      ...member.linkedAddresses.filter(Boolean).map((a) => a.toLowerCase())
    );
  }

  for (const stack of stacksRegistry.stacks) {
    if (memberAddresses.includes(stack.owner.toLowerCase()) && !stack.unlocked) {
      stack.unlocked = true;
      unlockedCount++;
    }
  }

  if (unlockedCount > 0) {
    stacksRegistry.lastUpdated = Date.now();
    await storeStacksRegistry(stacksRegistry);
    console.log(
      `[stack-pass] Retroactively unlocked ${unlockedCount} stacks for member ${member.memberId}`
    );
  }
}

// GET - Check stack pass status
export async function GET(request: NextRequest) {
  const address = request.nextUrl.searchParams.get("address");

  if (!address) {
    return NextResponse.json({ success: false, error: "Address is required" }, { status: 400 });
  }

  const normalizedAddress = address.toLowerCase();

  try {
    const registry = await fetchRegistry();

    // Find member by address
    const member = registry.members.find((m) => {
      if (m.address.toLowerCase() === normalizedAddress) return true;
      if (m.linkedAddresses?.some((a) => a.toLowerCase() === normalizedAddress)) return true;
      return false;
    });

    if (!member) {
      return NextResponse.json({
        success: true,
        hasStackPass: false,
        isMember: false,
      });
    }

    return NextResponse.json({
      success: true,
      hasStackPass: member.hasStackPass || false,
      stackPassPurchasedAt: member.stackPassPurchasedAt,
      isMember: true,
      // NFT mint fields
      unlimitedPassTokenId: member.unlimitedPassTokenId,
      unlimitedPassTier: member.unlimitedPassTier,
      unlimitedPassMintTx: member.unlimitedPassMintTx,
      unlimitedPassVerified: member.unlimitedPassVerified ?? (member.hasStackPass ? true : undefined),
    });
  } catch (error) {
    console.error("[stack-pass] Error checking status:", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 }
    );
  }
}
src/app/api/membership/stack-pass/verify/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * GET /api/membership/stack-pass/verify?address=0x...
 *
 * Re-attempts on-chain verification for a pass record that was stored as
 * unlimitedPassVerified=false (e.g. because the RPC was unavailable at mint time).
 *
 * If the on-chain Minted event is now confirmed:
 *   - Sets unlimitedPassTokenId, unlimitedPassTier, unlimitedPassVerified=true
 *   - Auto-grants membership for "we are so early" tier non-members
 *   - Returns { verified: true, tokenId, tier, membershipGranted? }
 *
 * If verification still fails:
 *   - Returns { verified: false, reason }
 */

import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { mintEnsSubname, type MemberEntry } from "@/lib/agent-auth";
import type { MemberRegistry } from "@/lib/net-protocol";

const REGISTRY_KEY = "member-registry";
const PASS_CONTRACT = "0xce559a2a6b64504be00aa7aa85c5c31ea93a16bb";
const MINTED_TOPIC =
  "0xe7cd4ce7f2a465edc730269a1305e8a48bad821e8fb7e152ec413829c01a53c4";
const BASE_RPC = process.env.BASE_RPC_URL || "[REDACTED-RPC-URL]";

async function fetchRegistry(): Promise<MemberRegistry> {
  const empty: MemberRegistry = { members: [], nextMemberId: 1, lastUpdated: Date.now() };
  try {
    const result = await db.select().from(kv).where(eq(kv.key, REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) return empty;
    return JSON.parse(result[0].value) as MemberRegistry;
  } catch {
    return empty;
  }
}

async function storeRegistry(registry: MemberRegistry): Promise<boolean> {
  try {
    const jsonValue = JSON.stringify(registry);
    await db
      .insert(kv)
      .values({ key: REGISTRY_KEY, value: jsonValue })
      .onConflictDoUpdate({ target: kv.key, set: { value: jsonValue } });
    return true;
  } catch {
    return false;
  }
}

async function verifyNftMintOnChain(
  txHash: string,
  addresses: string[]
): Promise<{ valid: boolean; tokenId: number | null; tier: "we are so early" | "early-ish"; error?: string }> {
  // Build a Set of exact 32-byte padded topics for all known addresses.
  // The Minted event's topic[1] is the recipient address left-padded to 32 bytes.
  // We check ALL of the member's known addresses (primary + linked) so that a mint
  // to a linked wallet is accepted when the query param is a different wallet.
  const expectedTopics = new Set(
    addresses.map((a) => "0x" + a.toLowerCase().slice(2).padStart(64, "0"))
  );

  try {
    const resp = await fetch(BASE_RPC, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: 1,
        method: "eth_getTransactionReceipt",
        params: [txHash],
      }),
    });

    const json = (await resp.json()) as {
      result?: { logs?: Array<{ address: string; topics: string[] }> };
    };

    const logs = json.result?.logs ?? [];
    const mintLog = logs.find(
      (log) =>
        log.address.toLowerCase() === PASS_CONTRACT &&
        log.topics[0] === MINTED_TOPIC &&
        log.topics[1] != null &&
        expectedTopics.has(log.topics[1].toLowerCase())
    );

    if (!mintLog) {
      return { valid: false, tokenId: null, tier: "early-ish", error: "Minted event not found" };
    }

    const tokenId = parseInt(mintLog.topics[2], 16);
    const tier: "we are so early" | "early-ish" =
      tokenId <= 1000 ? "we are so early" : "early-ish";
    return { valid: true, tokenId, tier };
  } catch (err) {
    return {
      valid: false,
      tokenId: null,
      tier: "early-ish",
      error: err instanceof Error ? err.message : "RPC error",
    };
  }
}

interface FarcasterIdentity {
  fid?: number;
  username?: string;
  displayName?: string;
}

async function resolveFarcasterIdentity(address: string): Promise<FarcasterIdentity> {
  const neynarApiKey = process.env.NEYNAR_API_KEY;
  if (!neynarApiKey) return {};

  try {
    const url = `https://api.neynar.com/v2/farcaster/user/bulk-by-address?addresses=${address.toLowerCase()}`;
    const resp = await fetch(url, {
      headers: { "accept": "application/json", "x-api-key": neynarApiKey },
    });
    if (!resp.ok) return {};

    const data = await resp.json() as Record<string, Array<{
      fid?: number;
      username?: string;
      display_name?: string;
    }>>;

    const users = data[address.toLowerCase()] ?? [];
    if (users.length === 0) return {};

    const user = users[0];
    return { fid: user.fid, username: user.username, displayName: user.display_name };
  } catch {
    return {};
  }
}

async function grantMembershipInternal(
  walletAddress: string,
  source: string,
  identity?: FarcasterIdentity
): Promise<{ success: boolean; isDuplicate?: boolean; memberId?: number; ensSubname?: string; error?: string }> {
  try {
    const registry = await fetchRegistry();

    // Duplicate check
    const existing = registry.members.find(
      (m) => m.address.toLowerCase() === walletAddress.toLowerCase()
    );
    if (existing) {
      return { success: true, isDuplicate: true, memberId: existing.memberId, ensSubname: existing.ensSubname };
    }

    const memberId = registry.nextMemberId;
    const ensSubname = `${memberId}.netlibrary.eth`;
    const newMember: MemberEntry = {
      memberId,
      address: walletAddress,
      ensSubname,
      fid: identity?.fid,
      username: identity?.username,
      displayName: identity?.displayName,
      joinedAt: Date.now(),
      grantType: "admin",
      grantedBy: source,
      signupPlatform: "farcaster",
    };

    registry.members.push(newMember);
    registry.nextMemberId = memberId + 1;

    const saved = await storeRegistry(registry);
    if (!saved) return { success: false, error: "Failed to persist member registry" };

    const mintResult = await mintEnsSubname(memberId, walletAddress, false);
    if (!mintResult.success) {
      console.error(`[stack-pass/verify] ENS mint failed for member #${memberId}: ${mintResult.error}`);
    }

    return { success: true, isDuplicate: false, memberId, ensSubname };
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    console.error("[stack-pass/verify] grantMembershipInternal error:", msg);
    return { success: false, error: msg };
  }
}

export async function GET(request: NextRequest) {
  const address = request.nextUrl.searchParams.get("address");

  if (!address) {
    return NextResponse.json({ success: false, error: "address is required" }, { status: 400 });
  }

  const normalizedAddress = address.toLowerCase();

  try {
    const registry = await fetchRegistry();

    const member = registry.members.find((m) => {
      if (m.address.toLowerCase() === normalizedAddress) return true;
      if (m.linkedAddresses?.some((a) => a.toLowerCase() === normalizedAddress)) return true;
      return false;
    });

    if (!member) {
      return NextResponse.json({ success: false, error: "No pass record found for this address" }, { status: 404 });
    }

    if (!member.unlimitedPassMintTx) {
      return NextResponse.json({ success: false, error: "No mint transaction on record" }, { status: 400 });
    }

    // Already verified — nothing to do
    if (member.unlimitedPassVerified === true) {
      return NextResponse.json({
        success: true,
        verified: true,
        alreadyVerified: true,
        tokenId: member.unlimitedPassTokenId,
        tier: member.unlimitedPassTier,
      });
    }

    // Build the complete set of addresses to check for the Minted event.
    // The mint may have been sent to any of the member's known addresses — primary or linked.
    const allKnownAddresses: string[] = [
      member.address.toLowerCase(),
      ...(member.linkedAddresses ?? []).map((a) => a.toLowerCase()),
    ];
    // De-duplicate while preserving order
    const uniqueAddresses = [...new Set(allKnownAddresses)];

    // Attempt on-chain verification against ALL known addresses
    const verification = await verifyNftMintOnChain(member.unlimitedPassMintTx, uniqueAddresses);

    if (!verification.valid) {
      return NextResponse.json({
        success: true,
        verified: false,
        reason: verification.error || "Minted event not yet found on-chain. Try again shortly.",
      });
    }

    // Verified — update the record
    member.unlimitedPassTokenId = verification.tokenId!;
    member.unlimitedPassTier = verification.tier;
    member.unlimitedPassVerified = true;
    member.hasUnlimitedPass = true;
    member.hasStackPass = true;

    let membershipGranted = false;
    let grantedEnsSubname: string | undefined;

    // For "we are so early" tier: ensure membership perks are applied.
    if (verification.tier === "we are so early") {
      if (member.memberId === 0) {
        // Edge case: record was created before a membership grant (e.g. pass-first flow).
        // Attempt a full membership grant now, resolving Farcaster identity first.
        const identity = await resolveFarcasterIdentity(normalizedAddress);
        const grantResult = await grantMembershipInternal(normalizedAddress, "unlimited-pass-verify", identity);
        if (grantResult.success && !grantResult.isDuplicate) {
          membershipGranted = true;
          grantedEnsSubname = grantResult.ensSubname;
        }
      }
      // For existing members (memberId > 0) the pass flags set above are sufficient —
      // no additional membership grant is needed; they already have full access.
    }

    const saved = await storeRegistry(registry);
    if (!saved) {
      return NextResponse.json({ success: false, error: "Failed to save verified pass record" }, { status: 500 });
    }

    console.log(
      `[stack-pass/verify] Verified on-chain: ${normalizedAddress} → token #${verification.tokenId} (${verification.tier})`
    );

    return NextResponse.json({
      success: true,
      verified: true,
      tokenId: verification.tokenId,
      tier: verification.tier,
      membershipGranted,
      ensSubname: grantedEnsSubname,
    });
  } catch (err) {
    console.error("[stack-pass/verify] Error:", err);
    return NextResponse.json({ success: false, error: "Internal server error" }, { status: 500 });
  }
}
src/app/api/neynar/[...route]/route.ts
// Complete Neynar API proxy using our new architecture
import { NeynarAPIClient, Configuration } from "@neynar/nodejs-sdk";
import { createNeynarApiHandler } from "@/neynar-web-sdk/nextjs";
import { privateConfig } from "@/config/private-config";

// Create SDK client with proper Configuration object (SDK requires this format to pass API key)
const config = new Configuration({
  apiKey: privateConfig.neynarApiKey,
});

const client = new NeynarAPIClient(config);

// Export Next.js API route handlers
export const { GET, POST, PUT, DELETE, OPTIONS } =
  createNeynarApiHandler(client);
src/app/api/pass-check/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * GET /api/pass-check?address=<wallet>
 *
 * Determines whether a wallet address — or any wallet linked to the same
 * Farcaster identity — already holds an Unlimited Pass NFT on Base.
 *
 * Logic:
 *  1. Resolve the Farcaster identity (FID, custody address, verified addresses)
 *     for the given wallet via Neynar.
 *  2. Check hasUnlimitedPass(address) on-chain for every linked address.
 *  3. Return { hasPass, passHolder, linkedAddresses, canMint, fid, username }.
 *
 * Edge cases:
 *  - No Farcaster user found → check just the single address.
 *  - On-chain check fails for an address → treat as no pass, continue.
 *  - Neynar unreachable → 503.
 *
 * Rate limiting: 30 requests / minute per IP (in-process sliding window).
 * No authentication required — read-only public endpoint.
 */

import { NextRequest, NextResponse } from "next/server";

const PASS_CONTRACT = "0xCe559A2A6b64504bE00aa7aA85C5C31EA93a16BB";
const BASE_RPC = process.env.BASE_RPC_URL || "[REDACTED-RPC-URL]";
const NEYNAR_API_KEY = process.env.NEYNAR_API_KEY || "";

// ---------------------------------------------------------------------------
// Simple in-process rate limiter: 30 requests / minute per IP
// ---------------------------------------------------------------------------

interface RateLimitEntry {
  count: number;
  windowStart: number;
}

const rateLimitMap = new Map<string, RateLimitEntry>();
const RATE_LIMIT_MAX = 30;
const RATE_LIMIT_WINDOW_MS = 60_000;

function isRateLimited(ip: string): boolean {
  const now = Date.now();
  const entry = rateLimitMap.get(ip);

  if (!entry || now - entry.windowStart > RATE_LIMIT_WINDOW_MS) {
    rateLimitMap.set(ip, { count: 1, windowStart: now });
    return false;
  }

  if (entry.count >= RATE_LIMIT_MAX) return true;

  entry.count += 1;
  return false;
}

// ---------------------------------------------------------------------------
// On-chain: hasUnlimitedPass(address) → bool
// selector 0x8a3b2044, address left-padded to 32 bytes
// ---------------------------------------------------------------------------

async function checkPassOnChain(address: string): Promise<boolean> {
  try {
    const callData = "0x8a3b2044" + address.slice(2).toLowerCase().padStart(64, "0");
    const resp = await fetch(BASE_RPC, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: 1,
        method: "eth_call",
        params: [{ to: PASS_CONTRACT, data: callData }, "latest"],
      }),
    });
    const json = (await resp.json()) as { result?: string };
    return !!json.result && BigInt(json.result) !== BigInt(0);
  } catch {
    // Non-fatal — treat as no pass for this address
    return false;
  }
}

// ---------------------------------------------------------------------------
// Neynar: resolve all addresses linked to the Farcaster identity for an address
// ---------------------------------------------------------------------------

interface NeynarUser {
  fid: number;
  username: string;
  custody_address: string;
  verified_addresses?: {
    eth_addresses?: string[];
  };
}

async function resolveLinkedAddresses(
  address: string
): Promise<{ fid: number | null; username: string | null; linkedAddresses: string[] }> {
  if (!NEYNAR_API_KEY) {
    return { fid: null, username: null, linkedAddresses: [address.toLowerCase()] };
  }

  const resp = await fetch(
    `https://api.neynar.com/v2/farcaster/user/bulk-by-address?addresses=${encodeURIComponent(address)}`,
    { headers: { api_key: NEYNAR_API_KEY } }
  );

  if (!resp.ok) {
    if (resp.status === 404) {
      // No Farcaster user for this address — single-address check
      return { fid: null, username: null, linkedAddresses: [address.toLowerCase()] };
    }
    if (resp.status >= 500) {
      throw new Error(`Neynar error ${resp.status}`);
    }
    return { fid: null, username: null, linkedAddresses: [address.toLowerCase()] };
  }

  const data = (await resp.json()) as Record<string, NeynarUser[]>;

  // Response is keyed by address — grab the first user found
  const users = Object.values(data).flat();
  if (!users.length) {
    return { fid: null, username: null, linkedAddresses: [address.toLowerCase()] };
  }

  const user = users[0];
  const allAddresses = new Set<string>();

  // Custody address
  if (user.custody_address) {
    allAddresses.add(user.custody_address.toLowerCase());
  }

  // Verified ETH addresses
  for (const addr of user.verified_addresses?.eth_addresses ?? []) {
    allAddresses.add(addr.toLowerCase());
  }

  // Always include the queried address
  allAddresses.add(address.toLowerCase());

  return {
    fid: user.fid,
    username: user.username,
    linkedAddresses: Array.from(allAddresses),
  };
}

// ---------------------------------------------------------------------------
// Route handler
// ---------------------------------------------------------------------------

export async function GET(request: NextRequest) {
  // Rate limiting
  const ip =
    request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
    request.headers.get("x-real-ip") ||
    "unknown";

  if (isRateLimited(ip)) {
    return NextResponse.json(
      { error: "Too many requests. Please wait a moment and try again." },
      { status: 429, headers: { "Retry-After": "60" } }
    );
  }

  const address = request.nextUrl.searchParams.get("address");

  if (!address || !/^0x[a-fA-F0-9]{40}$/.test(address)) {
    return NextResponse.json(
      { error: "Valid Ethereum address required" },
      { status: 400 }
    );
  }

  // 1. Resolve Farcaster identity and all linked addresses
  let fid: number | null = null;
  let username: string | null = null;
  let linkedAddresses: string[] = [address.toLowerCase()];

  try {
    const resolved = await resolveLinkedAddresses(address);
    fid = resolved.fid;
    username = resolved.username;
    linkedAddresses = resolved.linkedAddresses;
  } catch {
    // Neynar was unreachable — can't safely determine cross-wallet ownership
    return NextResponse.json(
      { error: "Could not verify identity. Please try again shortly." },
      { status: 503 }
    );
  }

  // 2. Check hasUnlimitedPass on-chain for every linked address in parallel
  const checkResults = await Promise.all(
    linkedAddresses.map(async (addr) => ({
      addr,
      hasPass: await checkPassOnChain(addr),
    }))
  );

  const passingEntry = checkResults.find((r) => r.hasPass);
  const hasPass = !!passingEntry;
  const passHolder = passingEntry?.addr ?? null;

  return NextResponse.json({
    address: address.toLowerCase(),
    fid,
    username,
    hasPass,
    passHolder,
    linkedAddresses,
    canMint: !hasPass,
  });
}
src/app/api/passwords/[id]/route.ts
/**
 * Passwords API — Single Entry
 *
 * GET    /api/passwords/[id]   — Retrieve a specific password (decrypted, shown to owner)
 * PUT    /api/passwords/[id]   — Update label only
 * DELETE /api/passwords/[id]   — Delete a saved password
 *
 * Member-only. Caller must own the password entry.
 */

import { NextRequest, NextResponse } from "next/server";
import {
  getKV,
  setKV,
  deleteKV,
  authenticateCaller,
  resolveCallerMember,
  getMemberRegistry,
  handleOptions,
  corsResponse,
  corsError,
} from "@/lib/agent-auth";
import { decryptPasswordEntry } from "@/app/api/passwords/route";
import type { PasswordEntry } from "@/app/api/passwords/route";

const KV_PREFIX = "member-passwords:";

async function getEntries(memberId: number): Promise<PasswordEntry[]> {
  const data = await getKV<PasswordEntry[]>(`${KV_PREFIX}${memberId}`);
  return data || [];
}

async function saveEntries(memberId: number, entries: PasswordEntry[]): Promise<void> {
  if (entries.length === 0) {
    await deleteKV(`${KV_PREFIX}${memberId}`);
  } else {
    await setKV(`${KV_PREFIX}${memberId}`, entries);
  }
}

export async function OPTIONS() {
  return handleOptions();
}

type RouteContext = { params: Promise<{ id: string }> };

/**
 * GET /api/passwords/[id]
 *
 * Decrypts and returns the plaintext password to its owner.
 * This is the only endpoint that reveals the plaintext value.
 *
 * Auth:
 *   - Agent callers: Bearer token in Authorization header
 *   - Web callers:   ?fid=<number> and/or ?address=<0x...> query params
 */
export async function GET(request: NextRequest, context: RouteContext) {
  try {
    const { id } = await context.params;

    // GET has no body — read identity from query params for web callers
    const { searchParams } = new URL(request.url);
    const qFid = searchParams.get("fid");
    const qAddress = searchParams.get("address");

    let body: Record<string, unknown> = {};
    try { body = await request.json(); } catch { /* no body on GET */ }

    if (qFid && !body.fid) body.fid = parseInt(qFid, 10);
    if (qAddress && !body.address) body.address = qAddress.toLowerCase();

    const caller = await authenticateCaller(request, body);
    if (caller instanceof NextResponse) return caller;

    const registry = await getMemberRegistry();
    const member = resolveCallerMember(caller, registry);
    if (!member) {
      return corsError("Membership required.", 403);
    }

    const entries = await getEntries(member.memberId);
    const entry = entries.find(e => e.id === id);

    if (!entry) {
      return corsError("Password not found.", 404);
    }

    let plaintext: string;
    try {
      plaintext = decryptPasswordEntry(entry);
    } catch {
      return corsError("Failed to decrypt password entry — the server key may have changed.", 500);
    }

    return corsResponse({
      id: entry.id,
      label: entry.label,
      password: plaintext,
      createdAt: entry.createdAt,
      updatedAt: entry.updatedAt,
    });
  } catch (err) {
    console.error("[GET /api/passwords/[id]]", err);
    return corsError("Internal server error", 500);
  }
}

/**
 * PUT /api/passwords/[id]
 *
 * Update the label of a saved password.
 * Body: { label: string }
 */
export async function PUT(request: NextRequest, context: RouteContext) {
  try {
    const { id } = await context.params;

    let body: Record<string, unknown> = {};
    try { body = await request.json(); } catch { /* no body */ }

    const caller = await authenticateCaller(request, body);
    if (caller instanceof NextResponse) return caller;

    const registry = await getMemberRegistry();
    const member = resolveCallerMember(caller, registry);
    if (!member) {
      return corsError("Membership required.", 403);
    }

    const newLabel = (body.label as string | undefined)?.trim();
    if (!newLabel) {
      return corsError("label is required", 400);
    }

    const entries = await getEntries(member.memberId);
    const idx = entries.findIndex(e => e.id === id);

    if (idx === -1) {
      return corsError("Password not found.", 404);
    }

    entries[idx] = { ...entries[idx], label: newLabel, updatedAt: Date.now() };
    await saveEntries(member.memberId, entries);

    return corsResponse({
      id: entries[idx].id,
      label: entries[idx].label,
      updatedAt: entries[idx].updatedAt,
    });
  } catch (err) {
    console.error("[PUT /api/passwords/[id]]", err);
    return corsError("Internal server error", 500);
  }
}

/**
 * DELETE /api/passwords/[id]
 *
 * Remove a saved password.
 * Note: encrypted library items that used this password are unaffected (content remains onchain).
 */
export async function DELETE(request: NextRequest, context: RouteContext) {
  try {
    const { id } = await context.params;

    let body: Record<string, unknown> = {};
    try { body = await request.json(); } catch { /* no body */ }

    const caller = await authenticateCaller(request, body);
    if (caller instanceof NextResponse) return caller;

    const registry = await getMemberRegistry();
    const member = resolveCallerMember(caller, registry);
    if (!member) {
      return corsError("Membership required.", 403);
    }

    const entries = await getEntries(member.memberId);
    const idx = entries.findIndex(e => e.id === id);

    if (idx === -1) {
      return corsError("Password not found.", 404);
    }

    entries.splice(idx, 1);
    await saveEntries(member.memberId, entries);

    return corsResponse({
      success: true,
      warning: "Encrypted items that used this password still require it to view. Make sure you have the password saved elsewhere.",
    });
  } catch (err) {
    console.error("[DELETE /api/passwords/[id]]", err);
    return corsError("Internal server error", 500);
  }
}
src/app/api/passwords/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Passwords API
 *
 * GET  /api/passwords          — List saved passwords for the caller (id, label, createdAt, itemCount)
 * POST /api/passwords          — Save a new password (encrypted at rest)
 * OPTIONS                      — CORS preflight
 *
 * Member-only. Passwords are AES-256-GCM encrypted server-side before storage.
 * The plaintext password is NEVER returned by the list endpoint — only by GET /api/passwords/:id.
 *
 * KV schema:
 *   member-passwords:{memberId}  →  PasswordEntry[]
 *
 * Encryption:
 *   Server-side AES-256-GCM using process.env.PASSWORDS_ENCRYPTION_KEY (hex-encoded 32 bytes).
 *   Falls back to a deterministic key derived from NEXTAUTH_SECRET when the env var is absent
 *   (development convenience — production MUST set PASSWORDS_ENCRYPTION_KEY).
 */

import { NextRequest, NextResponse } from "next/server";
import { createCipheriv, createDecipheriv, randomBytes, createHash } from "crypto";
import {
  getKV,
  setKV,
  authenticateCaller,
  resolveCallerMember,
  getMemberRegistry,
  handleOptions,
  corsResponse,
  corsError,
} from "@/lib/agent-auth";

// --------------------------------------------------------------------------
// Types
// --------------------------------------------------------------------------

export interface PasswordEntry {
  id: string;         // Random hex ID
  label: string;      // User-provided label (stored plaintext)
  ciphertext: string; // AES-256-GCM encrypted password, base64
  iv: string;         // GCM IV, base64
  authTag: string;    // GCM auth tag, base64
  createdAt: number;  // Unix ms
  updatedAt?: number; // Unix ms
  itemCount?: number; // Number of library items using this password (informational)
}

// --------------------------------------------------------------------------
// Helpers
// --------------------------------------------------------------------------

const KV_PREFIX = "member-passwords:";

/** Derive (or load) the 32-byte server encryption key. */
function getEncryptionKey(): Buffer {
  const hex = process.env.PASSWORDS_ENCRYPTION_KEY;
  if (hex && hex.length >= 64) {
    return Buffer.from(hex.slice(0, 64), "hex");
  }
  // Fallback: derive from NEXTAUTH_SECRET (dev only — log a warning)
  const secret = process.env.NEXTAUTH_SECRET || process.env.NEYNAR_API_KEY || "[REDACTED]";
  console.warn("[passwords] PASSWORDS_ENCRYPTION_KEY not set — using derived fallback key");
  return createHash("sha256").update(secret).digest();
}

/** Encrypt a plaintext password string → { ciphertext, iv, authTag } (all base64). */
function encryptPassword(plaintext: string): { ciphertext: string; iv: string; authTag: string } {
  const key = getEncryptionKey();
  const iv = randomBytes(12);
  const cipher = createCipheriv("aes-256-gcm", key, iv);
  const encrypted = Buffer.concat([cipher.update(plaintext, "utf8"), cipher.final()]);
  const authTag = cipher.getAuthTag();
  return {
    ciphertext: encrypted.toString("base64"),
    iv: iv.toString("base64"),
    authTag: authTag.toString("base64"),
  };
}

/** Decrypt a stored PasswordEntry → plaintext string. Throws on auth tag failure. */
export function decryptPasswordEntry(entry: Pick<PasswordEntry, "ciphertext" | "iv" | "authTag">): string {
  const key = getEncryptionKey();
  const iv = Buffer.from(entry.iv, "base64");
  const decipher = createDecipheriv("aes-256-gcm", key, iv);
  decipher.setAuthTag(Buffer.from(entry.authTag, "base64"));
  const ciphertext = Buffer.from(entry.ciphertext, "base64");
  const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
  return decrypted.toString("utf8");
}

async function getEntries(memberId: number): Promise<PasswordEntry[]> {
  const data = await getKV<PasswordEntry[]>(`${KV_PREFIX}${memberId}`);
  return data || [];
}

// --------------------------------------------------------------------------
// Route handlers
// --------------------------------------------------------------------------

export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/passwords
 *
 * Returns the list of saved passwords for the caller.
 * Passwords are NOT included — only id, label, createdAt, itemCount.
 *
 * Auth:
 *   - Agent callers: Bearer token in Authorization header
 *   - Web callers:   ?fid=<number> and/or ?address=<0x...> query params
 *                    (same pattern used by /api/membership, /api/reading-queue, etc.)
 */
export async function GET(request: NextRequest) {
  try {
    // GET requests have no body — read identity from query params for web callers,
    // falling back to body for any agent that sends one (e.g. curl/Postman).
    const { searchParams } = new URL(request.url);
    const qFid = searchParams.get("fid");
    const qAddress = searchParams.get("address");

    let body: Record<string, unknown> = {};
    try { body = await request.json(); } catch { /* no body on GET */ }

    // Merge query-param identity into body so authenticateCaller picks it up
    if (qFid && !body.fid) body.fid = parseInt(qFid, 10);
    if (qAddress && !body.address) body.address = qAddress.toLowerCase();

    const caller = await authenticateCaller(request, body);
    if (caller instanceof NextResponse) return caller;

    const registry = await getMemberRegistry();
    const member = resolveCallerMember(caller, registry);
    if (!member) {
      return corsError("Membership required to use saved passwords.", 403);
    }

    const entries = await getEntries(member.memberId);

    return corsResponse({
      passwords: entries.map(e => ({
        id: e.id,
        label: e.label,
        createdAt: e.createdAt,
        updatedAt: e.updatedAt,
        itemCount: e.itemCount ?? 0,
      })),
    });
  } catch (err) {
    console.error("[GET /api/passwords]", err);
    return corsError("Internal server error", 500);
  }
}

/**
 * POST /api/passwords
 *
 * Save a new password.
 *
 * Body: { password: string, label?: string }
 * Returns: { id, label, createdAt }
 */
export async function POST(request: NextRequest) {
  try {
    let body: Record<string, unknown> = {};
    try { body = await request.json(); } catch { /* no body */ }

    const caller = await authenticateCaller(request, body);
    if (caller instanceof NextResponse) return caller;

    const registry = await getMemberRegistry();
    const member = resolveCallerMember(caller, registry);
    if (!member) {
      return corsError("Membership required to save passwords.", 403);
    }

    const plaintext = body.password as string | undefined;
    if (!plaintext || typeof plaintext !== "string" || !plaintext.trim()) {
      return corsError("password is required", 400);
    }

    const label = (body.label as string | undefined)?.trim() || "Untitled";

    const { ciphertext, iv, authTag } = encryptPassword(plaintext.trim());

    const newEntry: PasswordEntry = {
      id: randomBytes(8).toString("hex"),
      label,
      ciphertext,
      iv,
      authTag,
      createdAt: Date.now(),
    };

    const entries = await getEntries(member.memberId);

    // Hard cap: 100 saved passwords per member
    const MAX_PASSWORDS = 100;
    if (entries.length >= MAX_PASSWORDS) {
      return corsError(
        `Password limit reached (${MAX_PASSWORDS} maximum). Delete unused passwords before saving new ones.`,
        400
      );
    }

    // Prevent exact-password duplicates (compare ciphertext is insufficient — use decryption)
    for (const existing of entries) {
      try {
        const existingPlain = decryptPasswordEntry(existing);
        if (existingPlain === plaintext.trim()) {
          // Return the existing entry rather than creating a duplicate
          return corsResponse({
            id: existing.id,
            label: existing.label,
            createdAt: existing.createdAt,
            duplicate: true,
          });
        }
      } catch {
        // Corrupted entry — skip
      }
    }

    entries.push(newEntry);
    await setKV(`${KV_PREFIX}${member.memberId}`, entries);

    return corsResponse({
      id: newEntry.id,
      label: newEntry.label,
      createdAt: newEntry.createdAt,
    }, 201);
  } catch (err) {
    console.error("[POST /api/passwords]", err);
    return corsError("Internal server error", 500);
  }
}
src/app/api/pdf-cover/route.ts
import { NextRequest, NextResponse } from "next/server";

/**
 * PDF Cover Extraction API
 * Extracts the first page of a PDF as a thumbnail image
 *
 * This API handles server-side cover extraction for:
 * 1. New uploads - extract from uploaded PDF
 * 2. Existing content - fetch from CDN and extract
 */

// POST - Extract cover from uploaded PDF or CDN URL
export async function POST(request: NextRequest) {
  try {
    const contentType = request.headers.get("content-type") || "";

    // Handle JSON request (CDN URL)
    if (contentType.includes("application/json")) {
      const body = await request.json();
      const { cdnUrl } = body;

      // cdnUrl is required - /content/{key} format is DEPRECATED and returns 404
      if (!cdnUrl) {
        return NextResponse.json({ error: "Missing cdnUrl - provide full CDN URL" }, { status: 400 });
      }

      const fetchUrl = cdnUrl;

      try {
        // Fetch PDF from CDN
        const response = await fetch(fetchUrl, {
          headers: {
            "Accept": "application/pdf, */*",
          },
        });

        if (!response.ok) {
          return NextResponse.json({
            error: "Failed to fetch PDF from CDN",
            details: `Status: ${response.status}`
          }, { status: 502 });
        }

        const pdfBuffer = await response.arrayBuffer();

        // For now, return a placeholder indicating extraction happened
        // Full PDF rendering requires canvas/sharp which we'll add
        return NextResponse.json({
          success: true,
          coverGenerated: false,
          message: "PDF fetched successfully. Client-side extraction available.",
          pdfSize: pdfBuffer.byteLength,
          // Return base64 of first few KB for client-side rendering
          pdfPreview: Buffer.from(pdfBuffer.slice(0, 50000)).toString("base64"),
        });
      } catch (fetchError) {
        console.error("[pdf-cover] Fetch error:", fetchError);
        return NextResponse.json({
          error: "Failed to fetch PDF",
          details: fetchError instanceof Error ? fetchError.message : "Unknown error"
        }, { status: 502 });
      }
    }

    // Handle multipart/form-data (direct upload)
    if (contentType.includes("multipart/form-data")) {
      const formData = await request.formData();
      const file = formData.get("file") as File | null;

      if (!file) {
        return NextResponse.json({ error: "No file provided" }, { status: 400 });
      }

      if (!file.type.includes("pdf")) {
        return NextResponse.json({ error: "File must be a PDF" }, { status: 400 });
      }

      const buffer = await file.arrayBuffer();

      // Return PDF data for client-side rendering
      return NextResponse.json({
        success: true,
        coverGenerated: false,
        message: "PDF received. Use client-side extraction for thumbnail.",
        pdfSize: buffer.byteLength,
        fileName: file.name,
      });
    }

    return NextResponse.json({ error: "Invalid content type" }, { status: 400 });
  } catch (error) {
    console.error("[pdf-cover] Error:", error);
    return NextResponse.json({
      error: "Failed to process PDF",
      details: error instanceof Error ? error.message : "Unknown error"
    }, { status: 500 });
  }
}

// GET - Check if cover exists for a content key
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const contentKey = searchParams.get("contentKey");

  if (!contentKey) {
    return NextResponse.json({ error: "Missing contentKey" }, { status: 400 });
  }

  // This would check our cover cache/storage
  // For now, return no cover
  return NextResponse.json({
    hasCover: false,
    contentKey,
    message: "Cover extraction available via POST",
  });
}
src/app/api/pdf-file/route.ts
import { NextRequest, NextResponse } from "next/server";
import { BASE_CHAIN_ID, createStorageClient } from "@/lib/net-protocol";

// GET - Serve raw PDF file directly (no JSON wrapping)
export async function GET(request: NextRequest) {
  const contentKey = request.nextUrl.searchParams.get("contentKey");
  const operatorAddress = request.nextUrl.searchParams.get("operator");

  if (!contentKey || !operatorAddress) {
    return new NextResponse("Missing contentKey or operator", { status: 400 });
  }

  try {
    console.log("[pdf-file] Fetching PDF:", contentKey.slice(0, 20));

    const storageClient = createStorageClient(BASE_CHAIN_ID);

    // Retry logic for newly uploaded content (storedon.net indexer may be slow)
    const retryDelays = [0, 3000, 5000, 8000, 12000]; // Initial + 4 retries with exponential backoff
    let result: { data?: string; isXml?: boolean } | null = null;
    let lastError: Error | null = null;

    for (let attempt = 0; attempt < retryDelays.length; attempt++) {
      if (attempt > 0) {
        console.log(`[pdf-file] Retry ${attempt}/${retryDelays.length - 1} after ${retryDelays[attempt]}ms...`);
        await new Promise(resolve => setTimeout(resolve, retryDelays[attempt]));
      }

      try {
        result = await storageClient.readStorageData({
          key: contentKey,
          operator: operatorAddress,
          keyFormat: "bytes32",
        });

        if (result?.data) {
          console.log(`[pdf-file] Successfully fetched on attempt ${attempt + 1}`);
          break;
        }
      } catch (readError) {
        lastError = readError instanceof Error ? readError : new Error(String(readError));
        console.log(`[pdf-file] Fetch error on attempt ${attempt + 1}:`, lastError.message.slice(0, 100));
        // Check if it's a 404-like error that might succeed on retry
        if (lastError.message.includes("404") || lastError.message.includes("not found")) {
          result = null;
          continue;
        }
        // For other errors, might still be worth retrying
        result = null;
      }
    }

    if (!result?.data) {
      console.error("[pdf-file] All fetch attempts failed:", lastError?.message);
      return new NextResponse("No data found - content may still be indexing, try again in a moment", { status: 404 });
    }

    // Check if it's base64-encoded PDF
    if (result.data.startsWith("JVBERi")) {
      const pdfBuffer = Buffer.from(result.data, "base64");
      console.log("[pdf-file] Serving PDF, size:", pdfBuffer.length);

      return new NextResponse(pdfBuffer, {
        headers: {
          "Content-Type": "application/pdf",
          "Content-Disposition": "inline",
          "Cache-Control": "public, max-age=3600",
        },
      });
    }

    // Check if it's hex-encoded PDF
    if (result.data.startsWith("0x")) {
      const cleanHex = result.data.slice(2);
      const bytes = Buffer.from(cleanHex, "hex");

      // Check for PDF magic bytes
      if (bytes[0] === 0x25 && bytes[1] === 0x50 && bytes[2] === 0x44 && bytes[3] === 0x46) {
        console.log("[pdf-file] Serving hex-decoded PDF, size:", bytes.length);

        return new NextResponse(bytes, {
          headers: {
            "Content-Type": "application/pdf",
            "Content-Disposition": "inline",
            "Cache-Control": "public, max-age=3600",
          },
        });
      }
    }

    // Check if it's raw PDF text (starts with %PDF magic bytes as text)
    if (result.data.startsWith("%PDF")) {
      // Convert raw text to binary buffer
      // Use 'latin1' encoding to preserve byte values for binary PDF data
      const pdfBuffer = Buffer.from(result.data, "latin1");
      console.log("[pdf-file] Serving raw text PDF, size:", pdfBuffer.length);

      return new NextResponse(pdfBuffer, {
        headers: {
          "Content-Type": "application/pdf",
          "Content-Disposition": "inline",
          "Cache-Control": "public, max-age=3600",
        },
      });
    }

    return new NextResponse("Not a PDF file", { status: 400 });
  } catch (error) {
    console.error("[pdf-file] Error:", error);
    return new NextResponse("Failed to fetch PDF", { status: 500 });
  }
}
src/app/api/prefs/route.ts
/**
 * User Preferences API
 *
 * GET  /api/prefs?fid=XXX  — Fetch preferences for a user (by FID or address)
 * POST /api/prefs           — Set a preference value
 *
 * Preferences are stored in KV as prefs:{identifier}:{key} → "true"/"false"/value.
 * This enables popup-dismiss state to survive across sessions and webview contexts
 * where localStorage is ephemeral or blocked (Farcaster mini-apps, Base App).
 *
 * Supported keys:
 *   dismissed_membership  — User dismissed the "become a member" popup
 */

import { NextRequest, NextResponse } from "next/server";
import { getKV, setKV } from "@/lib/agent-auth";

// Allowed preference keys (whitelist to prevent KV pollution)
const ALLOWED_KEYS = new Set(["dismissed_membership"]);

function prefKey(identifier: string, key: string): string {
  // identifier is lowercased fid (e.g. "fid:12345") or address
  return `prefs:${identifier.toLowerCase()}:${key}`;
}

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const fid = searchParams.get("fid");
  const address = searchParams.get("address");
  const key = searchParams.get("key");

  if (!fid && !address) {
    return NextResponse.json({ error: "fid or address required" }, { status: 400 });
  }

  const identifier = fid ? `fid:${fid}` : address!;

  if (key) {
    // Return a single preference
    if (!ALLOWED_KEYS.has(key)) {
      return NextResponse.json({ error: "Unknown preference key" }, { status: 400 });
    }
    const value = await getKV<string>(prefKey(identifier, key));
    return NextResponse.json({ key, value: value ?? null });
  }

  // Return all known preferences for this user
  const prefs: Record<string, string | null> = {};
  for (const k of ALLOWED_KEYS) {
    prefs[k] = await getKV<string>(prefKey(identifier, k));
  }
  return NextResponse.json({ prefs });
}

export async function POST(request: NextRequest) {
  let body: { fid?: number | string; address?: string; key?: string; value?: string };
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
  }

  const { fid, address, key, value } = body;

  if (!fid && !address) {
    return NextResponse.json({ error: "fid or address required" }, { status: 400 });
  }
  if (!key || !ALLOWED_KEYS.has(key)) {
    return NextResponse.json({ error: "Unknown or missing preference key" }, { status: 400 });
  }

  const identifier = fid ? `fid:${fid}` : address!;
  const storedValue = value ?? "true";

  await setKV(prefKey(identifier, key), storedValue);

  return NextResponse.json({ success: true, key, value: storedValue });
}
src/app/api/profile/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { type MemberRegistry, type MemberEntry } from "@/lib/net-protocol";

const REGISTRY_KEY = "member-registry";

// Direct DB fetch for member registry
async function fetchRegistry(): Promise<MemberRegistry> {
  const emptyRegistry: MemberRegistry = {
    members: [],
    nextMemberId: 1,
    lastUpdated: Date.now(),
  };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) {
      return emptyRegistry;
    }
    return JSON.parse(result[0].value) as MemberRegistry;
  } catch (error) {
    console.error("[fetchRegistry] Error:", error);
    return emptyRegistry;
  }
}

// Direct DB store for member registry
async function storeRegistry(registry: MemberRegistry): Promise<boolean> {
  try {
    const jsonValue = JSON.stringify(registry);
    await db.insert(kv).values({ key: REGISTRY_KEY, value: jsonValue }).onConflictDoUpdate({
      target: kv.key,
      set: { value: jsonValue },
    });
    return true;
  } catch (error) {
    console.error("[storeRegistry] Error:", error);
    return false;
  }
}

// Validate custom username (alphanumeric, underscores, 3-20 chars)
function isValidUsername(username: string): boolean {
  if (!username || username.length < 3 || username.length > 20) {
    return false;
  }
  // Allow letters, numbers, underscores
  return /^[a-zA-Z0-9_]+$/.test(username);
}

// Check if username is already taken by another member
function isUsernameTaken(registry: MemberRegistry, username: string, excludeMemberId: number): boolean {
  const lowerUsername = username.toLowerCase();
  return registry.members.some(m =>
    m.memberId !== excludeMemberId &&
    (m.customUsername?.toLowerCase() === lowerUsername || m.username?.toLowerCase() === lowerUsername)
  );
}

// GET - Fetch profile for a member by address or memberId
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const address = searchParams.get("address");
  const memberIdStr = searchParams.get("memberId");

  if (!address && !memberIdStr) {
    return NextResponse.json(
      { error: "address or memberId parameter required" },
      { status: 400 }
    );
  }

  try {
    const registry = await fetchRegistry();
    let member: MemberEntry | undefined;

    if (memberIdStr) {
      const memberId = parseInt(memberIdStr, 10);
      member = registry.members.find(m => m.memberId === memberId);
    } else if (address) {
      const lowerAddress = address.toLowerCase();
      // First check primary address
      member = registry.members.find(m => m.address.toLowerCase() === lowerAddress);
      // If not found, check linked addresses
      if (!member) {
        member = registry.members.find(m =>
          m.linkedAddresses?.some(linked => linked.toLowerCase() === lowerAddress)
        );
      }
    }

    if (!member) {
      return NextResponse.json({ error: "Member not found" }, { status: 404 });
    }

    // Return profile data
    return NextResponse.json({
      memberId: member.memberId,
      address: member.address,
      ensSubname: member.ensSubname,
      signupPlatform: member.signupPlatform,
      // Identity (may come from different sources)
      fid: member.fid,
      username: member.username,           // Farcaster username (if from FC)
      customUsername: member.customUsername, // User-set username (web platform)
      customPfpUrl: member.customPfpUrl,     // User-uploaded PFP (web platform)
      wid: member.wid,                       // Web ID
      linkedFid: member.linkedFid,           // FID linked after signup
      linkedPlatforms: member.linkedPlatforms,
      // Computed display values
      displayUsername: member.customUsername || member.username || `member${member.memberId}`,
      joinedAt: member.joinedAt,
    });
  } catch (error) {
    console.error("[GET /api/profile] Error:", error);
    return NextResponse.json({ error: "Failed to fetch profile" }, { status: 500 });
  }
}

// PATCH - Update profile for web platform users
export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const { address, customUsername, customPfpUrl } = body;

    if (!address) {
      return NextResponse.json(
        { error: "address is required" },
        { status: 400 }
      );
    }

    // At least one field to update
    if (customUsername === undefined && customPfpUrl === undefined) {
      return NextResponse.json(
        { error: "Nothing to update. Provide customUsername or customPfpUrl" },
        { status: 400 }
      );
    }

    const registry = await fetchRegistry();

    // Find member by address
    const memberIndex = registry.members.findIndex(
      m => m.address.toLowerCase() === address.toLowerCase()
    );

    if (memberIndex === -1) {
      return NextResponse.json({ error: "Member not found" }, { status: 404 });
    }

    const member = registry.members[memberIndex];

    // Only web platform users can edit their profile
    // Farcaster/Base users get identity from their platforms
    if (member.signupPlatform !== "web") {
      return NextResponse.json(
        {
          error: "Profile editing is only available for web platform users",
          note: "Your identity comes from your connected platform (Farcaster or Base)"
        },
        { status: 403 }
      );
    }

    // Validate and update customUsername
    if (customUsername !== undefined) {
      if (customUsername === null || customUsername === "") {
        // Allow clearing the username
        member.customUsername = undefined;
      } else {
        if (!isValidUsername(customUsername)) {
          return NextResponse.json(
            { error: "Invalid username. Use 3-20 characters: letters, numbers, underscores only" },
            { status: 400 }
          );
        }

        if (isUsernameTaken(registry, customUsername, member.memberId)) {
          return NextResponse.json(
            { error: "Username already taken" },
            { status: 409 }
          );
        }

        member.customUsername = customUsername;
      }
    }

    // Validate and update customPfpUrl
    if (customPfpUrl !== undefined) {
      if (customPfpUrl === null || customPfpUrl === "") {
        // Allow clearing the PFP
        member.customPfpUrl = undefined;
      } else {
        // Basic URL validation
        try {
          new URL(customPfpUrl);
          // Only allow https URLs
          if (!customPfpUrl.startsWith("https://")) {
            return NextResponse.json(
              { error: "PFP URL must use HTTPS" },
              { status: 400 }
            );
          }
          member.customPfpUrl = customPfpUrl;
        } catch {
          return NextResponse.json(
            { error: "Invalid PFP URL" },
            { status: 400 }
          );
        }
      }
    }

    // Update the member in registry
    registry.members[memberIndex] = member;
    registry.lastUpdated = Date.now();

    const stored = await storeRegistry(registry);
    if (!stored) {
      return NextResponse.json(
        { error: "Failed to save profile" },
        { status: 500 }
      );
    }

    return NextResponse.json({
      success: true,
      profile: {
        memberId: member.memberId,
        customUsername: member.customUsername,
        customPfpUrl: member.customPfpUrl,
        displayUsername: member.customUsername || member.username || `member${member.memberId}`,
      },
    });
  } catch (error) {
    console.error("[PATCH /api/profile] Error:", error);
    return NextResponse.json({ error: "Failed to update profile" }, { status: 500 });
  }
}
src/app/api/reading-progress/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

// Reading progress stored per user per book
interface ReadingProgress {
  bookId: string;
  contentKey: string;
  currentPage: number;
  totalPages: number;
  currentSentence: number;
  totalSentences: number;
  percentComplete: number;
  lastReadAt: number;
  totalReadingTime: number; // in seconds
  startedAt: number;
  completedAt?: number;
}

interface UserProgress {
  progress: Record<string, ReadingProgress>;
}

const getKvKey = (userAddress: string) => `reading-progress:${userAddress.toLowerCase()}`;

// Helper to fetch progress from KV database
async function fetchUserProgress(userAddress: string): Promise<UserProgress> {
  const empty: UserProgress = { progress: {} };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, getKvKey(userAddress))).limit(1);
    if (!result[0]?.value) return empty;
    return JSON.parse(result[0].value) as UserProgress;
  } catch {
    return empty;
  }
}

// Helper to store progress to KV database
async function storeUserProgress(userAddress: string, data: UserProgress): Promise<boolean> {
  try {
    const key = getKvKey(userAddress);
    await db.insert(kv).values({
      key,
      value: JSON.stringify(data),
    }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(data) },
    });
    return true;
  } catch (error) {
    console.error("storeUserProgress error:", error);
    return false;
  }
}

// GET - Fetch reading progress for a user
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userAddress = searchParams.get("userAddress");
    const bookId = searchParams.get("bookId");

    if (!userAddress) {
      return NextResponse.json({ error: "Missing userAddress" }, { status: 400 });
    }

    const data = await fetchUserProgress(userAddress);

    if (bookId) {
      // Return progress for specific book
      return NextResponse.json({ progress: data.progress[bookId] || null });
    }

    // Return all progress
    return NextResponse.json({ progress: Object.values(data.progress) });
  } catch (error) {
    console.error("[reading-progress] GET error:", error);
    return NextResponse.json({ error: "Failed to fetch progress" }, { status: 500 });
  }
}

// POST - Save reading progress
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { userAddress, bookId, contentKey, currentPage, totalPages, currentSentence, totalSentences, readingTime } = body;

    if (!userAddress || !bookId) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
    }

    const data = await fetchUserProgress(userAddress);
    const existing = data.progress[bookId];

    const percentComplete = totalPages > 0
      ? Math.round((currentPage / totalPages) * 100)
      : totalSentences > 0
      ? Math.round((currentSentence / totalSentences) * 100)
      : 0;

    const progress: ReadingProgress = {
      bookId,
      contentKey: contentKey || existing?.contentKey || "",
      currentPage: currentPage || 1,
      totalPages: totalPages || existing?.totalPages || 0,
      currentSentence: currentSentence || 0,
      totalSentences: totalSentences || existing?.totalSentences || 0,
      percentComplete,
      lastReadAt: Date.now(),
      totalReadingTime: (existing?.totalReadingTime || 0) + (readingTime || 0),
      startedAt: existing?.startedAt || Date.now(),
      completedAt: percentComplete >= 100 ? Date.now() : existing?.completedAt,
    };

    data.progress[bookId] = progress;
    await storeUserProgress(userAddress, data);

    return NextResponse.json({ success: true, progress });
  } catch (error) {
    console.error("[reading-progress] POST error:", error);
    return NextResponse.json({ error: "Failed to save progress" }, { status: 500 });
  }
}
src/app/api/reading-queue/route.ts
import { NextRequest, NextResponse } from "next/server";
import { generateStorageKey } from "@/lib/net-protocol";

const NET_PROTOCOL_API = "https://storedon.net";

// Each user has their own reading queue stored under their address
function getQueueKey(address: string): string {
  return generateStorageKey(`net-library-reading-queue-${address.toLowerCase()}`);
}

export interface QueuedBookEntry {
  id: string;
  contentKey: string;
  title: string;
  author: string;
  categories: string[];
  addedAt: number;
  estimatedReadTime: string;
  progress: number;
}

export interface UserReadingQueue {
  address: string;
  items: QueuedBookEntry[];
  lastUpdated: number;
}

// Helper to fetch queue from Net Protocol
// NOTE: This uses the deprecated /content/{key} endpoint which may return 404
// TODO: Migrate to use proper storage API with operator or use KV storage instead
async function fetchQueue(address: string): Promise<UserReadingQueue | null> {
  try {
    const key = getQueueKey(address);
    const response = await fetch(`${NET_PROTOCOL_API}/content/${key}`);
    if (!response.ok) return null;
    return await response.json();
  } catch {
    return null;
  }
}

// Helper to store queue on Net Protocol
async function storeQueue(queue: UserReadingQueue): Promise<boolean> {
  try {
    const key = getQueueKey(queue.address);
    const response = await fetch(`${NET_PROTOCOL_API}/upload`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        contentKey: key,
        data: JSON.stringify(queue),
        contentType: "application/json",
      }),
    });
    return response.ok;
  } catch {
    return false;
  }
}

// GET - Fetch user's reading queue
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const address = searchParams.get("address")?.toLowerCase();

  if (!address) {
    return NextResponse.json({ error: "Address required" }, { status: 400 });
  }

  const queue = await fetchQueue(address);

  return NextResponse.json({
    queue: queue || { address, items: [], lastUpdated: Date.now() },
  });
}

// POST - Update reading queue
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { address, action, item, itemId, progress, newOrder } = body;

    if (!address) {
      return NextResponse.json({ error: "Address required" }, { status: 400 });
    }

    const normalizedAddress = address.toLowerCase();
    let queue: UserReadingQueue = await fetchQueue(normalizedAddress) || {
      address: normalizedAddress,
      items: [] as QueuedBookEntry[],
      lastUpdated: Date.now(),
    };

    switch (action) {
      case "add": {
        if (!item) {
          return NextResponse.json({ error: "Item required for add action" }, { status: 400 });
        }
        // Check if already in queue
        if (queue.items.some((i) => i.contentKey === item.contentKey)) {
          return NextResponse.json({ message: "Already in queue", queue });
        }
        const newItem: QueuedBookEntry = {
          id: `q-${Date.now()}`,
          contentKey: item.contentKey,
          title: item.title,
          author: item.author,
          categories: item.categories || [],
          addedAt: Date.now(),
          estimatedReadTime: item.estimatedReadTime || "Unknown",
          progress: 0,
        };
        queue.items.push(newItem);
        break;
      }

      case "remove": {
        if (!itemId) {
          return NextResponse.json({ error: "ItemId required for remove action" }, { status: 400 });
        }
        queue.items = queue.items.filter((i) => i.id !== itemId && i.contentKey !== itemId);
        break;
      }

      case "update-progress": {
        if (!itemId || progress === undefined) {
          return NextResponse.json({ error: "ItemId and progress required" }, { status: 400 });
        }
        queue.items = queue.items.map((i) =>
          i.id === itemId || i.contentKey === itemId
            ? { ...i, progress: Math.min(100, Math.max(0, progress)) }
            : i
        );
        break;
      }

      case "reorder": {
        if (!newOrder || !Array.isArray(newOrder)) {
          return NextResponse.json({ error: "NewOrder array required" }, { status: 400 });
        }
        // Reorder items based on the new order of IDs
        const itemMap = new Map(queue.items.map((i) => [i.id, i]));
        queue.items = newOrder
          .map((id) => itemMap.get(id))
          .filter((i): i is QueuedBookEntry => i !== undefined);
        break;
      }

      case "clear": {
        queue.items = [];
        break;
      }

      default:
        return NextResponse.json({ error: "Invalid action" }, { status: 400 });
    }

    queue.lastUpdated = Date.now();
    await storeQueue(queue);

    return NextResponse.json({ success: true, queue });
  } catch (error) {
    console.error("Reading queue error:", error);
    return NextResponse.json({ error: "Failed to update queue" }, { status: 500 });
  }
}
src/app/api/reading-stats/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

interface ReadingStats {
  totalBooksStarted: number;
  totalBooksCompleted: number;
  totalReadingTime: number; // in seconds
  totalPagesRead: number;
  currentStreak: number; // consecutive days reading
  longestStreak: number;
  lastReadDate: string; // YYYY-MM-DD
  readingDays: string[]; // Array of YYYY-MM-DD strings
  favoriteCategories: Record<string, number>; // category -> books read
  averageSessionTime: number; // in seconds
  booksThisMonth: number;
  booksThisYear: number;
}

const getStatsKey = (userAddress: string) => `reading-stats:${userAddress.toLowerCase()}`;

const defaultStats: ReadingStats = {
  totalBooksStarted: 0,
  totalBooksCompleted: 0,
  totalReadingTime: 0,
  totalPagesRead: 0,
  currentStreak: 0,
  longestStreak: 0,
  lastReadDate: "",
  readingDays: [],
  favoriteCategories: {},
  averageSessionTime: 0,
  booksThisMonth: 0,
  booksThisYear: 0,
};

// Helper to fetch stats from KV database
async function fetchStats(userAddress: string): Promise<ReadingStats> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, getStatsKey(userAddress))).limit(1);
    if (!result[0]?.value) return { ...defaultStats };
    return JSON.parse(result[0].value) as ReadingStats;
  } catch {
    return { ...defaultStats };
  }
}

// Helper to store stats to KV database
async function storeStats(userAddress: string, stats: ReadingStats): Promise<boolean> {
  try {
    const key = getStatsKey(userAddress);
    await db.insert(kv).values({
      key,
      value: JSON.stringify(stats),
    }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(stats) },
    });
    return true;
  } catch (error) {
    console.error("storeStats error:", error);
    return false;
  }
}

// GET - Fetch reading stats for a user
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userAddress = searchParams.get("userAddress");

    if (!userAddress) {
      return NextResponse.json({ error: "Missing userAddress" }, { status: 400 });
    }

    const stats = await fetchStats(userAddress);

    return NextResponse.json({ stats });
  } catch (error) {
    console.error("[reading-stats] GET error:", error);
    return NextResponse.json({ error: "Failed to fetch stats" }, { status: 500 });
  }
}

// POST - Update reading stats
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { userAddress, sessionTime, pagesRead, bookCompleted, categories, bookStarted } = body;

    if (!userAddress) {
      return NextResponse.json({ error: "Missing userAddress" }, { status: 400 });
    }

    const existing = await fetchStats(userAddress);

    const today = new Date().toISOString().split("T")[0];
    const currentMonth = today.slice(0, 7);
    const currentYear = today.slice(0, 4);

    // Update basic stats
    if (sessionTime) {
      existing.totalReadingTime += sessionTime;
      const totalSessions = existing.readingDays.length || 1;
      existing.averageSessionTime = Math.round(existing.totalReadingTime / totalSessions);
    }

    if (pagesRead) {
      existing.totalPagesRead += pagesRead;
    }

    if (bookStarted) {
      existing.totalBooksStarted += 1;
    }

    if (bookCompleted) {
      existing.totalBooksCompleted += 1;

      // Update monthly/yearly counts
      if (existing.lastReadDate.startsWith(currentMonth)) {
        existing.booksThisMonth += 1;
      } else {
        existing.booksThisMonth = 1;
      }

      if (existing.lastReadDate.startsWith(currentYear)) {
        existing.booksThisYear += 1;
      } else {
        existing.booksThisYear = 1;
      }
    }

    // Update favorite categories
    if (categories && Array.isArray(categories)) {
      categories.forEach((cat: string) => {
        existing.favoriteCategories[cat] = (existing.favoriteCategories[cat] || 0) + 1;
      });
    }

    // Update streak
    if (!existing.readingDays.includes(today)) {
      existing.readingDays.push(today);

      // Keep only last 365 days
      if (existing.readingDays.length > 365) {
        existing.readingDays = existing.readingDays.slice(-365);
      }

      // Calculate streak
      const yesterday = new Date();
      yesterday.setDate(yesterday.getDate() - 1);
      const yesterdayStr = yesterday.toISOString().split("T")[0];

      if (existing.lastReadDate === yesterdayStr || existing.lastReadDate === today) {
        // Continuing streak
        existing.currentStreak += 1;
      } else if (existing.lastReadDate !== today) {
        // Streak broken
        existing.currentStreak = 1;
      }

      if (existing.currentStreak > existing.longestStreak) {
        existing.longestStreak = existing.currentStreak;
      }
    }

    existing.lastReadDate = today;

    await storeStats(userAddress, existing);

    return NextResponse.json({ success: true, stats: existing });
  } catch (error) {
    console.error("[reading-stats] POST error:", error);
    return NextResponse.json({ error: "Failed to update stats" }, { status: 500 });
  }
}
src/app/api/recommendations/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

interface DiscoveryEntry {
  contentKey: string;
  metadataKey: string;
  operator: string;
  title: string;
  author: string;
  categories: string[];
  fileSize: number;
  storageType: string;
  coverUrl?: string;
  uploadedAt: number;
}

interface DiscoveryIndex {
  entries: DiscoveryEntry[];
  lastUpdated: number;
}

const DISCOVERY_KV_KEY = "discovery-index";

// Helper to fetch discovery index
async function fetchDiscoveryIndex(): Promise<DiscoveryIndex> {
  const empty: DiscoveryIndex = { entries: [], lastUpdated: 0 };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KV_KEY)).limit(1);
    if (!result[0]?.value) return empty;
    return JSON.parse(result[0].value) as DiscoveryIndex;
  } catch {
    return empty;
  }
}

// GET - Get recommendations for a user
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userAddress = searchParams.get("userAddress");
    const contentKey = searchParams.get("contentKey"); // For "similar items" recommendations
    const type = searchParams.get("type") || "personalized"; // personalized, similar, popular, new, trending
    const limit = Math.min(parseInt(searchParams.get("limit") || "10"), 20);

    const index = await fetchDiscoveryIndex();
    const entries = index.entries || [];

    if (entries.length === 0) {
      return NextResponse.json({ recommendations: [] });
    }

    let recommendations: DiscoveryEntry[] = [];

    if (type === "trending" || type === "popular") {
      // Return most recent items (would integrate with upvote counts for real popularity)
      recommendations = [...entries]
        .sort((a, b) => (b.uploadedAt || 0) - (a.uploadedAt || 0))
        .slice(0, limit);
    } else if (type === "new") {
      // Return newest items
      recommendations = [...entries]
        .sort((a, b) => (b.uploadedAt || 0) - (a.uploadedAt || 0))
        .slice(0, limit);
    } else if (type === "similar" && contentKey) {
      // Find similar items based on categories and author
      const targetItem = entries.find(e => e.contentKey === contentKey);

      if (targetItem) {
        recommendations = entries
          .filter(e => e.contentKey !== contentKey)
          .map(entry => {
            // Calculate similarity score
            let score = 0;

            // Same author = high score
            if ((entry.author || '').toLowerCase() === (targetItem.author || '').toLowerCase()) {
              score += 10;
            }

            // Shared categories
            const sharedCategories = (entry.categories || []).filter(c =>
              (targetItem.categories || []).includes(c)
            );
            score += sharedCategories.length * 5;

            return { entry, score };
          })
          .filter(({ score }) => score > 0)
          .sort((a, b) => b.score - a.score)
          .slice(0, limit)
          .map(({ entry }) => entry);
      }
    } else if (type === "personalized" && userAddress) {
      // For personalized recommendations, we'd ideally look at user's history
      // For now, just return a mix of recent and diverse items

      // Get recent items
      const recentItems = [...entries]
        .sort((a, b) => (b.uploadedAt || 0) - (a.uploadedAt || 0))
        .slice(0, Math.ceil(limit / 2));

      // Get diverse items by category
      const categoryItems = new Map<string, DiscoveryEntry>();
      for (const entry of entries) {
        for (const cat of entry.categories) {
          if (!categoryItems.has(cat) && !recentItems.some(r => r.contentKey === entry.contentKey)) {
            categoryItems.set(cat, entry);
          }
        }
      }

      recommendations = [
        ...recentItems,
        ...Array.from(categoryItems.values()).slice(0, Math.floor(limit / 2))
      ].slice(0, limit);
    } else {
      // Default: return newest items
      recommendations = [...entries]
        .sort((a, b) => (b.uploadedAt || 0) - (a.uploadedAt || 0))
        .slice(0, limit);
    }

    // Also find similar items if contentKey provided
    let similarItems: DiscoveryEntry[] = [];
    if (contentKey) {
      const targetItem = entries.find(e => e.contentKey === contentKey);
      if (targetItem) {
        similarItems = entries
          .filter(e => e.contentKey !== contentKey)
          .map(entry => {
            let score = 0;
            if ((entry.author || '').toLowerCase() === (targetItem.author || '').toLowerCase()) score += 10;
            const sharedCats = (entry.categories || []).filter(c => (targetItem.categories || []).includes(c));
            score += sharedCats.length * 5;
            return { entry, score };
          })
          .filter(({ score }) => score > 0)
          .sort((a, b) => b.score - a.score)
          .slice(0, 5)
          .map(({ entry }) => entry);
      }
    }

    return NextResponse.json({
      recommendations,
      similarItems,
      type,
    });
  } catch (error) {
    console.error("[recommendations] GET error:", error);
    return NextResponse.json({ error: "Failed to get recommendations" }, { status: 500 });
  }
}
src/app/api/register-cdn-link/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry } from "@/lib/net-protocol";
import { authenticateAgent, isAuthError, hasPermission } from "@/lib/agent-auth";
import { checkServerUploadLimit, recordServerUpload } from "@/lib/upload-rate-limit";

// Register a Net Protocol CDN link as a discoverable item
// This adds it to the discovery index so it appears in the library
//
// IMPORTANT: Only valid Net Protocol URLs with parseable operator + storage key are accepted.
// This ensures all content in the library can be properly upvoted on-chain.
// We do NOT accept URLs we can't fully parse - no fake content keys allowed.

type ContentType = "pdf" | "image" | "audio" | "video" | "text" | "unknown";

const DISCOVERY_KEY = "discovery-index";

// Parse Net Protocol CDN URL to extract original operator, storage key, and filename
// ONLY accepts URLs where we can extract BOTH operator AND storage key
// This is required for upvotes to work correctly on-chain
//
// Supported URL formats:
// - https://storedon.net/net/{chainId}/storage/raw/{operatorAddress}/{storageKey}
// - https://storedon.net/net/{chainId}/storage/load/{operatorAddress}/{filename} - PREFERRED user-facing format
// - https://storedon.net/net/{chainId}/chunked-storage/file/{operatorAddress}/{storageKey}
//
// NOT supported (rejected):
// - https://storedon.net/content/{key} - DEPRECATED, returns 404
// - Any non-storedon.net URLs
function parseNetProtocolUrl(cdnUrl: string): { operator: string; storageKey: string; storageType: "regular" | "chunked"; fileName?: string } | null {
  try {
    const url = new URL(cdnUrl);

    // Must be a storedon.net URL
    if (!url.hostname.endsWith("storedon.net")) {
      return null;
    }

    const pathname = url.pathname;

    // Pattern 1: /net/{chainId}/storage/raw/{operator}/{key} - regular storage
    const rawStorageMatch = pathname.match(/\/net\/\d+\/storage\/raw\/([^/]+)\/(.+)/);
    if (rawStorageMatch) {
      const [, operator, storageKey] = rawStorageMatch;
      // Validate storage key looks like a hex key
      if (storageKey.startsWith("0x") || /^[a-fA-F0-9]{64}$/.test(storageKey)) {
        return {
          operator: operator.toLowerCase(),
          storageKey: storageKey.startsWith("0x") ? storageKey : `0x${storageKey}`,
          storageType: "regular",
        };
      }
      // Not a valid storage key format
      return null;
    }

    // Pattern 2: /net/{chainId}/chunked-storage/file/{operator}/{key} - chunked storage
    const chunkedStorageMatch = pathname.match(/\/net\/\d+\/chunked-storage\/file\/([^/]+)\/(.+)/);
    if (chunkedStorageMatch) {
      const [, operator, storageKey] = chunkedStorageMatch;
      // Validate storage key looks like a hex key
      if (storageKey.startsWith("0x") || /^[a-fA-F0-9]{64}$/.test(storageKey)) {
        return {
          operator: operator.toLowerCase(),
          storageKey: storageKey.startsWith("0x") ? storageKey : `0x${storageKey}`,
          storageType: "chunked",
        };
      }
      // Not a valid storage key format
      return null;
    }

    // Pattern 3: /net/{chainId}/storage/load/{operator}/{filename} - user-friendly format (PREFERRED)
    // This format returns actual file content, not JSON - but we can extract operator from it
    // The filename is URL-encoded, so we decode it for the fileName field
    const loadStorageMatch = pathname.match(/\/net\/\d+\/storage\/load\/([^/]+)\/(.+)/);
    if (loadStorageMatch) {
      const [, operator, encodedFileName] = loadStorageMatch;
      const fileName = decodeURIComponent(encodedFileName);
      // For /storage/load/ URLs, we generate a unique key from the operator + filename
      // This allows us to index user-friendly URLs while maintaining upvote functionality
      // The storage key is derived from keccak256(encodePacked([filename, operator]))
      // NOTE: This key won't match the original storage key, but the content is accessible
      // via the CDN URL. For upvotes to work, we use the operator address.
      const storageKey = `0x${Buffer.from(fileName + operator.toLowerCase()).toString("hex").slice(0, 64).padEnd(64, "0")}`;
      return {
        operator: operator.toLowerCase(),
        storageKey,
        storageType: "regular",
        fileName,
      };
    }

    // /content/{key} format is DEPRECATED and returns 404 - reject it
    const contentMatch = pathname.match(/\/content\/(.+)/);
    if (contentMatch) {
      // Return null to trigger helpful error message
      return null;
    }

    return null;
  } catch {
    return null;
  }
}

// Look up operator from discovery index by content key
async function lookupOperatorFromDiscovery(storageKey: string): Promise<{ operator: string; storageType: "regular" | "chunked" } | null> {
  try {
    const entries = await fetchLocalIndex();
    const entry = entries.find(e =>
      e.contentKey.toLowerCase() === storageKey.toLowerCase()
    );
    if (entry) {
      return {
        operator: entry.operator.toLowerCase(),
        storageType: entry.storageType === "chunked" ? "chunked" : "regular",
      };
    }
    return null;
  } catch {
    return null;
  }
}

// Fetch discovery index from KV
async function fetchLocalIndex(): Promise<DiscoveryEntry[]> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    if (!result[0]?.value) return [];
    return JSON.parse(result[0].value) as DiscoveryEntry[];
  } catch (error) {
    console.error("fetchLocalIndex error:", error);
    return [];
  }
}

// Store discovery index to KV
async function storeLocalIndex(entries: DiscoveryEntry[]): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: DISCOVERY_KEY, value: JSON.stringify(entries) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(entries) },
    });
    return true;
  } catch (error) {
    console.error("storeLocalIndex error:", error);
    return false;
  }
}


export async function POST(request: NextRequest) {
  try {
    // Require valid agent Bearer token with library:write permission
    // OR admin secret in the Authorization header
    // eslint-disable-next-line @neynar/no-process-env
    const adminSecret = process.env.ADMIN_SECRET;
    const authHeader = request.headers.get("Authorization") || "";
    const isAdminRequest = adminSecret && authHeader === `Bearer ${adminSecret}`;

    // Capture the authenticated agent record so we can use its verified FID
    // and address for rate limiting and attribution (prevents body-field spoofing).
    let authenticatedFid: number | undefined;
    let authenticatedAddress: string | undefined;

    if (!isAdminRequest) {
      const authResult = await authenticateAgent(request);
      if (isAuthError(authResult)) {
        return NextResponse.json(
          { error: "Unauthorized. Provide a valid agent Bearer token with library:write permission." },
          { status: 401 }
        );
      }
      if (!hasPermission(authResult.agent, "library:write")) {
        return NextResponse.json(
          { error: "Forbidden. library:write permission required." },
          { status: 403 }
        );
      }
      // Trust the FID and address from the authenticated agent record, not the request body.
      authenticatedFid = authResult.agent.fid;
      authenticatedAddress = authResult.agent.address;
    }

    const body = await request.json();
    const {
      cdnUrl,
      contentType,
      title,
      author,
      categories,
      publicationYear: _publicationYear,
      publisher: _publisher,
      isbn: _isbn,
      coverUrl,
      uploaderAddress,
      uploaderFid,
      uploaderUsername,
      uploaderMemberId,
      uploaderEnsSubname,
      uploaderStoredUsername, // Farcaster username stored at signup - social identity
      // Social receipt specific fields
      isSocialReceipt,
      socialPlatform,
      originalUrl,
      socialText,
      socialAuthor,
      socialTimestamp,
    } = body;

    // Validate required fields
    if (!cdnUrl || !title || !uploaderAddress) {
      return NextResponse.json(
        { success: false, error: "Missing required fields: cdnUrl, title, uploaderAddress" },
        { status: 400 }
      );
    }

    // For non-admin Bearer requests, prefer the authenticated agent's address over the
    // body-supplied uploaderAddress — prevents callers from spoofing attribution or
    // consuming another user's rate limit quota.
    const effectiveAddress = isAdminRequest
      ? uploaderAddress
      : (authenticatedAddress ?? uploaderAddress);

    // Server-side daily upload rate limit check.
    // Prevents CLI/API users from bypassing the client-side warm-up enforcement.
    //
    // For Bearer-token requests: use the FID from the authenticated agent record
    // (prevents a caller from setting uploaderFid to a different FID to dodge or
    // consume another user's quota).  Admin-secret requests trust the body fields.
    const rateLimitFid = isAdminRequest
      ? (uploaderFid ? Number(uploaderFid) : undefined)
      : (authenticatedFid ?? (uploaderFid ? Number(uploaderFid) : undefined));

    const rateCheck = await checkServerUploadLimit(effectiveAddress, rateLimitFid);
    if (!rateCheck.allowed) {
      return NextResponse.json(
        { success: false, error: rateCheck.error },
        { status: rateCheck.status }
      );
    }

    // Validate URL format
    try {
      new URL(cdnUrl);
    } catch {
      return NextResponse.json(
        { success: false, error: "Invalid CDN URL format" },
        { status: 400 }
      );
    }

    // Parse the CDN URL to extract operator and storage key
    // This is REQUIRED for upvotes to work correctly on-chain
    const parsedUrl = parseNetProtocolUrl(cdnUrl);

    if (!parsedUrl) {
      // Reject URLs we can't parse at all
      console.log(`[CDN Link] Rejected - could not parse URL: ${cdnUrl}`);
      return NextResponse.json(
        {
          success: false,
          error: "Invalid Net Protocol URL. Only storedon.net URLs are supported. Use format /net/{chainId}/storage/raw/{operator}/{storageKey}, /net/{chainId}/chunked-storage/file/{operator}/{storageKey}, or /content/{storageKey}.",
        },
        { status: 400 }
      );
    }

    // Determine operator and storage type
    let operator: string;
    let storageKey: string;
    let storageType: "regular" | "chunked";

    if ("needsOperatorLookup" in parsedUrl) {
      // /content/{key} format - need to look up operator from discovery index
      storageKey = parsedUrl.storageKey;
      console.log(`[CDN Link] Looking up operator for /content/ URL: ${storageKey}`);

      const lookupResult = await lookupOperatorFromDiscovery(storageKey);
      if (!lookupResult) {
        console.log(`[CDN Link] Operator lookup failed - content not found in discovery index`);
        return NextResponse.json(
          {
            success: false,
            error: "Could not find operator for this content. The /content/{key} URL format requires the content to already exist in the library. Please use the full URL format: /net/{chainId}/storage/raw/{operator}/{storageKey}",
          },
          { status: 400 }
        );
      }

      operator = lookupResult.operator;
      storageType = lookupResult.storageType;
      console.log(`[CDN Link] Found operator from discovery: ${operator}, storageType: ${storageType}`);
    } else {
      // Full URL format - operator is in the URL
      operator = parsedUrl.operator;
      storageKey = parsedUrl.storageKey;
      storageType = parsedUrl.storageType;
      console.log(`[CDN Link] Parsed URL - operator: ${operator}, storageKey: ${storageKey}, storageType: ${storageType}`);
    }

    // Create a discovery entry for this CDN link
    // IMPORTANT: 'operator' field is used for upvoting, so we use the ORIGINAL operator
    // The importer info is stored separately for attribution
    const entry: DiscoveryEntry = {
      contentKey: storageKey,
      metadataKey: storageKey,
      operator, // Original operator for upvotes - this is what makes upvoting work!
      title,
      author: author || "Unknown",
      categories: categories || [],
      fileSize: 0, // Unknown for CDN links
      storageType, // Inferred from URL pattern (regular or chunked)
      uploadedAt: Date.now(),
      coverUrl: (contentType as ContentType) === "image" ? cdnUrl : coverUrl, // Use the URL as cover for images
      uploaderFid, // Importer's Farcaster info
      uploaderUsername, // Importer's username
      uploaderMemberId, // Importer's membership ID (for unified identity)
      uploaderEnsSubname, // Importer's ENS subname (for internal tracking)
      uploaderStoredUsername, // Farcaster username - the actual social identity to display
      // Store the CDN URL and content type as extended properties
      // These will be available when fetching the entry
      cdnUrl,
      mediaType: contentType as ContentType,
      // Track who imported this CDN link (separate from original operator).
      // Uses effectiveAddress (authenticated) rather than body uploaderAddress to
      // prevent attribution spoofing by non-admin callers.
      importerAddress: effectiveAddress.toLowerCase(),
      // Social receipt specific metadata (for sharing)
      ...(isSocialReceipt && {
        isSocialReceipt: true,
        socialPlatform,
        originalUrl,
        socialText,
        socialAuthor,
        socialTimestamp,
      }),
    };

    // Fetch existing entries and add the new one
    const currentEntries = await fetchLocalIndex();

    // Check if this URL already exists
    const existingIndex = currentEntries.findIndex(e =>
      (e as DiscoveryEntry & { cdnUrl?: string }).cdnUrl === cdnUrl
    );
    if (existingIndex !== -1) {
      return NextResponse.json(
        { success: false, error: "This CDN URL has already been registered" },
        { status: 409 }
      );
    }

    // Add to the front of the list (most recent first)
    currentEntries.unshift(entry);

    // Store updated index
    const stored = await storeLocalIndex(currentEntries);
    if (!stored) {
      return NextResponse.json(
        { success: false, error: "Failed to store entry" },
        { status: 500 }
      );
    }

    console.log(`[CDN Link] Registered: ${storageKey} -> ${cdnUrl}`);

    // Increment server-side upload counter (fire-and-forget — CDN link = 0 bytes)
    recordServerUpload(uploaderAddress, 0).catch(err =>
      console.error("[CDN Link] Failed to record upload counter:", err)
    );

    return NextResponse.json({
      success: true,
      contentKey: storageKey,
      entry,
    });
  } catch (error) {
    console.error("[CDN Link] Registration error:", error);
    return NextResponse.json(
      { success: false, error: error instanceof Error ? error.message : "Registration failed" },
      { status: 500 }
    );
  }
}
src/app/api/relay/[chainId]/fund/route.ts
import { NextRequest, NextResponse } from "next/server";

const RELAY_API_URL = "https://www.netprotocol.app";
const SECRET_KEY = "net-relay-public-access-key-v1";

/**
 * Dynamic fund endpoint proxy for x402 payment flow
 *
 * This route matches the SDK's expected URL pattern: /api/relay/[chainId]/fund
 *
 * Flow (per x402 spec):
 * 1. First call (no X-PAYMENT header): Returns 402 with payment requirements
 * 2. Second call (with X-PAYMENT header): Processes payment and funds wallet
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ chainId: string }> }
) {
  try {
    const { chainId } = await params;
    const chain = parseInt(chainId, 10);

    if (isNaN(chain)) {
      return NextResponse.json(
        { success: false, error: "Invalid chainId" },
        { status: 400 }
      );
    }

    const body = await request.json();
    const { operatorAddress, amountUsdc } = body;

    if (!operatorAddress) {
      return NextResponse.json(
        { success: false, error: "Missing operatorAddress" },
        { status: 400 }
      );
    }

    // Build URL with optional amount query parameter
    // The Net Protocol server uses this to determine how much USDC to request in the 402 response
    let url = `${RELAY_API_URL}/api/relay/${chain}/fund`;
    if (amountUsdc !== undefined && amountUsdc > 0) {
      url += `?amount=${amountUsdc}`;
      console.log(`[API FUND/${chain}] Adding amount query param: ?amount=${amountUsdc}`);
    }

    // Forward x402 payment header if present
    const x402PaymentHeader = request.headers.get("X-PAYMENT") || request.headers.get("x-payment");

    console.log(`[API FUND/${chain}] Calling relay fund: ${url}`);
    console.log(`[API FUND/${chain}] Request: operatorAddress=${operatorAddress}, amountUsdc=${amountUsdc}, hasPaymentHeader=${!!x402PaymentHeader}`);

    // Build headers
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      "X-Relay-Secret": SECRET_KEY,
    };
    if (x402PaymentHeader) {
      headers["X-PAYMENT"] = x402PaymentHeader;
    }

    // Build request body - include chainId as required by server
    const requestBody: Record<string, unknown> = {
      ...body,
      secretKey: SECRET_KEY,
      chainId: chain,
    };

    // Also include amount in smallest units (USDC has 6 decimals)
    // Server might expect either amountUsdc (dollars) or amount (smallest units)
    if (amountUsdc !== undefined && amountUsdc > 0) {
      requestBody.amountUsdc = amountUsdc;
      requestBody.amount = String(Math.round(amountUsdc * 1_000_000));
      console.log(`[API FUND/${chain}] Sending amount: $${amountUsdc} = ${requestBody.amount} smallest units`);
    }

    console.log(`[API FUND/${chain}] Request body:`, JSON.stringify(requestBody, null, 2));

    const response = await fetch(url, {
      method: "POST",
      headers,
      body: JSON.stringify(requestBody),
    });

    // Handle response
    const contentType = response.headers.get("content-type") || "";
    let data;

    if (contentType.includes("application/json")) {
      data = await response.json();
    } else {
      const text = await response.text();
      console.error(`[API FUND/${chain}] Non-JSON response (${response.status}):`, text.slice(0, 500));
      return NextResponse.json(
        {
          success: false,
          error: `Relay service returned HTML instead of JSON. Status: ${response.status}`,
          debug: { contentType, bodyPreview: text.slice(0, 200) }
        },
        { status: 502 }
      );
    }

    console.log(`[API FUND/${chain}] Response status: ${response.status}`);
    console.log(`[API FUND/${chain}] Response data:`, JSON.stringify(data, null, 2));

    // CRITICAL: Forward x402 payment response headers from Net Protocol
    // The SDK uses these to extract the payment tx hash after successful payment
    const responseHeaders = new Headers();

    // Log all response headers for debugging
    const headerLog: Record<string, string> = {};
    response.headers.forEach((value, key) => {
      headerLog[key] = value.length > 100 ? value.slice(0, 100) + "..." : value;
    });
    console.log(`[API FUND/${chain}] Response headers:`, headerLog);

    // Forward all x402-related headers (payment settle response contains the tx hash)
    const headersToForward = [
      "x-payment-response",
      "X-PAYMENT-RESPONSE",
      "x-payment",
      "X-PAYMENT",
      "x-402-receipt",
      "X-402-Receipt",
    ];

    for (const headerName of headersToForward) {
      const headerValue = response.headers.get(headerName);
      if (headerValue) {
        responseHeaders.set(headerName, headerValue);
        console.log(`[API FUND/${chain}] Forwarding header: ${headerName}`);
      }
    }

    // Also forward any header that contains "payment" (case insensitive)
    response.headers.forEach((value, key) => {
      if (key.toLowerCase().includes("payment") || key.toLowerCase().includes("402")) {
        responseHeaders.set(key, value);
        console.log(`[API FUND/${chain}] Forwarding header (auto): ${key}`);
      }
    });

    return NextResponse.json(data, {
      status: response.status,
      headers: responseHeaders,
    });
  } catch (error) {
    console.error("[API FUND] Error:", error);
    const message = error instanceof Error ? error.message : "Failed to contact relay service";
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    );
  }
}
src/app/api/relay/balance/route.ts
import { NextRequest, NextResponse } from "next/server";

const RELAY_API_URL = "https://www.netprotocol.app";
const SECRET_KEY = "net-relay-public-access-key-v1";
const BASE_CHAIN_ID = 8453;

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { operatorAddress, chainId } = body;

    console.log(`[API BALANCE] Request:`, { operatorAddress: operatorAddress?.slice(0, 10) + "...", chainId });

    if (!operatorAddress) {
      return NextResponse.json(
        { success: false, error: "Missing operatorAddress" },
        { status: 400 }
      );
    }

    const chain = chainId || BASE_CHAIN_ID;
    // Issue #6 fix: Balance endpoint has no chainId in path - chainId goes in body
    const url = `${RELAY_API_URL}/api/relay/balance`;

    console.log(`[API BALANCE] Calling: ${url}`);

    // Direct fetch instead of SDK to control error handling
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Relay-Secret": SECRET_KEY,
      },
      body: JSON.stringify({
        chainId: chain,
        operatorAddress,
        secretKey: SECRET_KEY,
      }),
    });

    // Handle non-JSON responses
    const contentType = response.headers.get("content-type") || "";

    if (!contentType.includes("application/json")) {
      const text = await response.text();
      console.error(`[API BALANCE] Non-JSON response (${response.status}):`, text.slice(0, 300));
      return NextResponse.json(
        {
          success: false,
          error: "Relay service temporarily unavailable",
          balanceEth: "0",
          balanceWei: "0",
          sufficientBalance: false,
          debug: { bodyPreview: text.slice(0, 100) }
        },
        { status: 503 }
      );
    }

    const result = await response.json();

    console.log(`[API BALANCE] Result:`, {
      backendWallet: result.backendWalletAddress?.slice(0, 10) + "...",
      balanceEth: result.balanceEth,
      balanceWei: result.balanceWei,
      sufficientBalance: result.sufficientBalance,
    });

    return NextResponse.json({
      success: true,
      ...result,
    });
  } catch (error) {
    console.error("[API BALANCE] Error:", error);
    const message = error instanceof Error ? error.message : "Failed to check balance";

    return NextResponse.json(
      {
        success: false,
        error: message,
        balanceEth: "0",
        balanceWei: "0",
        sufficientBalance: false,
      },
      { status: 500 }
    );
  }
}
src/app/api/relay/fund/route.ts
import { NextRequest, NextResponse } from "next/server";

const RELAY_API_URL = "https://www.netprotocol.app";
const SECRET_KEY = "net-relay-public-access-key-v1";
const BASE_CHAIN_ID = 8453;

/**
 * Fund endpoint proxy for x402 payment flow
 *
 * Flow (per x402 spec):
 * 1. First call (no X-402-Payment header): Returns 402 with payment requirements
 * 2. Second call (with X-402-Payment header): Processes payment and funds wallet
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { operatorAddress, chainId, amountUsdc } = body;

    if (!operatorAddress) {
      return NextResponse.json(
        { success: false, error: "Missing operatorAddress" },
        { status: 400 }
      );
    }

    const chain = chainId || BASE_CHAIN_ID;
    // Build URL with optional amount query parameter (matching official @net-protocol/relay SDK)
    let url = `${RELAY_API_URL}/api/relay/${chain}/fund`;
    if (amountUsdc !== undefined && amountUsdc > 0) {
      url += `?amount=${amountUsdc}`;
      console.log(`[API FUND] Adding amount query param: ?amount=${amountUsdc}`);
    }

    // Check for x402 payment header (forwarded from client)
    // Net Protocol uses "X-PAYMENT" header - try multiple cases
    const x402PaymentHeader = request.headers.get("X-PAYMENT") || request.headers.get("x-payment");

    // Debug: log all incoming headers to see what we're receiving
    const allHeaders: Record<string, string> = {};
    request.headers.forEach((value, key) => {
      allHeaders[key] = key.toLowerCase().includes("payment") ? value.slice(0, 50) + "..." : value;
    });
    console.log(`[API FUND] Incoming headers:`, allHeaders);
    console.log(`[API FUND] Calling relay fund: ${url}`);
    console.log(`[API FUND] Request: operatorAddress=${operatorAddress}, hasPaymentHeader=${!!x402PaymentHeader}, headerLength=${x402PaymentHeader?.length || 0}`);

    // Build headers - include secret key header and forward x402 payment header if present
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
      "X-Relay-Secret": SECRET_KEY,
    };
    if (x402PaymentHeader) {
      headers["X-PAYMENT"] = x402PaymentHeader;
    }

    // Call the relay API with secretKey, chainId, and amount
    // IMPORTANT: chainId is REQUIRED in the body (server validation changed)
    const requestBody: Record<string, unknown> = {
      operatorAddress,
      secretKey: SECRET_KEY,
      chainId: chain, // Required by Net Protocol server
    };
    // Forward amountUsdc if provided (for custom funding amounts)
    // Convert to smallest units (USDC has 6 decimals) since that's what x402 expects
    if (amountUsdc) {
      // Send both formats - server might expect either
      requestBody.amountUsdc = amountUsdc; // Dollar amount (e.g., 0.25)
      requestBody.amount = String(Math.round(amountUsdc * 1_000_000)); // Smallest units (e.g., "250000")
      console.log(`[API FUND] Sending amount: $${amountUsdc} = ${requestBody.amount} smallest units`);
    }
    console.log(`[API FUND] Request body:`, JSON.stringify(requestBody, null, 2));

    const response = await fetch(url, {
      method: "POST",
      headers,
      body: JSON.stringify(requestBody),
    });

    // Get the response body - handle non-JSON responses gracefully
    const contentType = response.headers.get("content-type") || "";
    let data;

    if (contentType.includes("application/json")) {
      data = await response.json();
    } else {
      // Server returned non-JSON (likely an error page or redirect)
      const text = await response.text();
      console.error(`[API] Relay returned non-JSON response (${response.status}):`);
      console.error(`[API] Content-Type: ${contentType}`);
      console.error(`[API] Response URL: ${response.url}`);
      console.error(`[API] Body preview: ${text.slice(0, 500)}`);
      return NextResponse.json(
        {
          success: false,
          error: `Relay service returned HTML instead of JSON. The API endpoint may have changed. Status: ${response.status}`,
          debug: {
            contentType,
            responseUrl: response.url,
            bodyPreview: text.slice(0, 200),
          }
        },
        { status: 502 }
      );
    }

    console.log(`[API] Relay fund response status: ${response.status}`);
    console.log(`[API] Relay fund response data:`, JSON.stringify(data, null, 2));

    // For x402 responses, ensure we have the expected structure
    if (response.status === 402) {
      // Log the full x402 response for debugging
      console.log(`[API] x402 payment required. Full response:`, JSON.stringify(data, null, 2));

      // Validate the x402 response has required fields
      const accepts = data.accepts?.[0];
      if (!accepts?.payTo) {
        console.error(`[API] x402 response missing payTo address!`);
        console.error(`[API] accepts array:`, JSON.stringify(data.accepts, null, 2));
      }
    }

    // Return the response with same status code (402 for x402 payment required)
    return NextResponse.json(data, { status: response.status });
  } catch (error) {
    console.error("[API] Relay fund error:", error);
    const message = error instanceof Error ? error.message : "Failed to contact relay service";
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    );
  }
}
src/app/api/relay/fund/verify/route.ts
import { NextRequest, NextResponse } from "next/server";

const RELAY_API_URL = "https://www.netprotocol.app";
const SECRET_KEY = "net-relay-public-access-key-v1";
const BASE_CHAIN_ID = 8453;

/**
 * Verify a USDC payment and fund the backend wallet
 * Called after user sends USDC to the payTo address
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { operatorAddress, paymentTxHash, chainId } = body;

    console.log(`[API VERIFY] Request received:`, { operatorAddress, paymentTxHash, chainId });

    if (!operatorAddress) {
      console.log(`[API VERIFY] ERROR: Missing operatorAddress`);
      return NextResponse.json(
        { success: false, error: "Missing operatorAddress" },
        { status: 400 }
      );
    }

    if (!paymentTxHash) {
      console.log(`[API VERIFY] ERROR: Missing paymentTxHash`);
      return NextResponse.json(
        { success: false, error: "Missing paymentTxHash" },
        { status: 400 }
      );
    }

    const chain = chainId || BASE_CHAIN_ID;
    // SDK calls /api/relay/fund/verify with chainId in body (not in path)
    const url = `${RELAY_API_URL}/api/relay/fund/verify`;

    console.log(`[API VERIFY] Calling relay API: ${url}`);
    console.log(`[API VERIFY] Payload:`, {
      chainId: chain,
      operatorAddress,
      paymentTxHash,
      secretKey: SECRET_KEY.slice(0, 10) + "...",
    });

    // Call the relay API to verify payment
    const response = await fetch(url, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        chainId: chain,
        operatorAddress,
        paymentTxHash,
        secretKey: SECRET_KEY,
      }),
    });

    // Handle non-JSON responses gracefully
    const contentType = response.headers.get("content-type") || "";
    let data;

    if (contentType.includes("application/json")) {
      data = await response.json();
    } else {
      // Server returned non-JSON (likely an error page)
      const text = await response.text();
      console.error(`[API FUND/VERIFY] Relay returned non-JSON response (${response.status}):`);
      console.error(`[API FUND/VERIFY] Content-Type: ${contentType}`);
      console.error(`[API FUND/VERIFY] Body preview: ${text.slice(0, 500)}`);
      return NextResponse.json(
        {
          success: false,
          error: `Fund/verify endpoint returned HTML instead of JSON. Status: ${response.status}`,
          debug: {
            contentType,
            responseUrl: response.url,
            bodyPreview: text.slice(0, 200),
          }
        },
        { status: 502 }
      );
    }
    console.log(`[API VERIFY] Relay API response (status ${response.status}):`, JSON.stringify(data, null, 2));

    if (!response.ok) {
      console.log(`[API VERIFY] Relay API returned error status: ${response.status}`);
    }

    if (data.success) {
      console.log(`[API VERIFY] SUCCESS! Backend wallet funded: ${data.backendWalletAddress}`);
    } else if (data.alreadyProcessed) {
      console.log(`[API VERIFY] Payment already processed`);
    } else {
      console.log(`[API VERIFY] Verification failed:`, data.error || "Unknown error");
    }

    return NextResponse.json(data, { status: response.status });
  } catch (error) {
    console.error("[API VERIFY] Exception:", error);
    const message = error instanceof Error ? error.message : "Failed to verify payment";
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    );
  }
}
src/app/api/relay/recover/route.ts
import { NextRequest, NextResponse } from "next/server";

/**
 * Payment Recovery API Route
 *
 * Scans blockchain for USDC transfers from user's wallet to the x402 facilitator,
 * then attempts to verify each payment. This recovers funds that were paid but
 * never verified due to network errors, browser close, etc.
 *
 * Flow:
 * 1. Query blockchain for USDC Transfer events from user to facilitator
 * 2. For each transfer, attempt to verify with Net Protocol
 * 3. Return count of recovered vs total found
 */

const RELAY_API_URL = "https://www.netprotocol.app";
const SECRET_KEY = "net-relay-public-access-key-v1";
const BASE_CHAIN_ID = 8453;

// Contract addresses
const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
const X402_FACILITATOR = "0x6462F8f301Bd08c206ee611aA00015bA41acc1D0";

// Transfer event signature: Transfer(address,address,uint256)
const TRANSFER_EVENT_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";

// RPC endpoint for blockchain queries
const RPC_URL = "https://base-mainnet.public.blastapi.io";

interface TransferLog {
  transactionHash: string;
  data: string;
  blockNumber: string;
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { operatorAddress, chainId } = body;

    if (!operatorAddress) {
      return NextResponse.json(
        { success: false, error: "Missing operatorAddress" },
        { status: 400 }
      );
    }

    const chain = chainId || BASE_CHAIN_ID;
    console.log(`[RECOVER] Scanning for unverified payments from ${operatorAddress}`);

    // Step 1: Query blockchain for USDC transfers from user to facilitator
    // Pad addresses to 32 bytes for topics
    const fromTopic = `0x000000000000000000000000${operatorAddress.slice(2).toLowerCase()}`;
    const toTopic = `0x000000000000000000000000${X402_FACILITATOR.slice(2).toLowerCase()}`;

    // Search last ~30 days of blocks (roughly 2.5M blocks on Base at 2s/block)
    // We use a smaller range for performance
    const latestBlockResponse = await fetch(RPC_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        jsonrpc: "2.0",
        method: "eth_blockNumber",
        params: [],
        id: 1,
      }),
    });

    const latestBlockData = await latestBlockResponse.json();
    const latestBlock = parseInt(latestBlockData.result, 16);
    // Search last ~7 days (about 300k blocks)
    const fromBlock = Math.max(0, latestBlock - 300000);

    console.log(`[RECOVER] Searching blocks ${fromBlock.toString(16)} to ${latestBlock.toString(16)}`);

    const logsResponse = await fetch(RPC_URL, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        jsonrpc: "2.0",
        method: "eth_getLogs",
        params: [{
          address: USDC_ADDRESS,
          topics: [
            TRANSFER_EVENT_TOPIC,
            fromTopic,
            toTopic,
          ],
          fromBlock: `0x${fromBlock.toString(16)}`,
          toBlock: "latest",
        }],
        id: 2,
      }),
    });

    const logsData = await logsResponse.json();

    if (logsData.error) {
      console.error(`[RECOVER] RPC error:`, logsData.error);
      return NextResponse.json(
        { success: false, error: `RPC error: ${logsData.error.message}` },
        { status: 500 }
      );
    }

    const transfers: TransferLog[] = logsData.result || [];
    console.log(`[RECOVER] Found ${transfers.length} USDC transfers to facilitator`);

    if (transfers.length === 0) {
      return NextResponse.json({
        success: true,
        recovered: 0,
        total: 0,
        message: "No payments found to recover",
      });
    }

    // Step 2: Attempt to verify each payment
    let recoveredCount = 0;
    const results: { txHash: string; status: string; amount: number }[] = [];

    for (const transfer of transfers) {
      const txHash = transfer.transactionHash;
      const amountWei = parseInt(transfer.data, 16);
      const amountUsdc = amountWei / 1e6;

      console.log(`[RECOVER] Verifying ${txHash.slice(0, 20)}... ($${amountUsdc.toFixed(2)})`);

      try {
        const verifyResponse = await fetch(`${RELAY_API_URL}/api/relay/fund/verify`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            chainId: chain,
            operatorAddress,
            paymentTxHash: txHash,
            secretKey: SECRET_KEY,
          }),
        });

        const verifyData = await verifyResponse.json();

        if (verifyData.success) {
          console.log(`[RECOVER] ✅ Recovered: ${txHash.slice(0, 20)}...`);
          recoveredCount++;
          results.push({ txHash, status: "recovered", amount: amountUsdc });
        } else if (verifyData.alreadyProcessed) {
          console.log(`[RECOVER] ⏭️ Already processed: ${txHash.slice(0, 20)}...`);
          results.push({ txHash, status: "already_processed", amount: amountUsdc });
        } else {
          console.log(`[RECOVER] ❌ Failed: ${txHash.slice(0, 20)}... - ${verifyData.error}`);
          results.push({ txHash, status: "failed", amount: amountUsdc });
        }
      } catch (error) {
        console.error(`[RECOVER] Error verifying ${txHash}:`, error);
        results.push({ txHash, status: "error", amount: amountUsdc });
      }
    }

    console.log(`[RECOVER] Complete: ${recoveredCount}/${transfers.length} recovered`);

    return NextResponse.json({
      success: true,
      recovered: recoveredCount,
      total: transfers.length,
      results,
    });
  } catch (error) {
    console.error("[RECOVER] Error:", error);
    const message = error instanceof Error ? error.message : "Recovery failed";
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    );
  }
}
src/app/api/relay/session/route.ts
import { NextRequest, NextResponse } from "next/server";

const RELAY_API_URL = "https://www.netprotocol.app";
const SECRET_KEY = "net-relay-public-access-key-v1";

/**
 * Session endpoint proxy
 * Creates a relay session token for submitting transactions
 *
 * Accepts: operatorAddress, chainId, secretKey, signature, expiresAt
 * Returns: sessionToken, expiresAt
 *
 * The signature must be an EIP-712 signature of:
 * - domain: { name: "Net Relay Service", version: "1", chainId }
 * - types: RelaySession [operatorAddress, secretKeyHash, expiresAt]
 * - message: { operatorAddress, secretKeyHash: keccak256(secretKey), expiresAt }
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { operatorAddress, signature, expiresAt } = body;

    console.log(`[API SESSION] Request:`, {
      operatorAddress: operatorAddress?.slice(0, 10) + "...",
      hasSignature: !!signature,
      signatureLength: signature?.length,
      expiresAt,
    });

    if (!operatorAddress) {
      return NextResponse.json(
        { success: false, error: "Missing operatorAddress" },
        { status: 400 }
      );
    }

    if (!signature) {
      return NextResponse.json(
        { success: false, error: "Missing signature" },
        { status: 400 }
      );
    }

    const url = `${RELAY_API_URL}/api/relay/session`;
    console.log(`[API SESSION] Calling: ${url}`);

    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Relay-Secret": SECRET_KEY,
      },
      body: JSON.stringify({
        ...body,
        secretKey: SECRET_KEY,
      }),
    });

    const contentType = response.headers.get("content-type") || "";
    if (!contentType.includes("application/json")) {
      const text = await response.text();
      console.error(`[API SESSION] Non-JSON response (${response.status}):`, text.slice(0, 300));
      return NextResponse.json(
        { success: false, error: "Relay service unavailable" },
        { status: 502 }
      );
    }

    const data = await response.json();
    console.log(`[API SESSION] Response:`, {
      status: response.status,
      hasSessionToken: !!data.sessionToken,
      expiresAt: data.expiresAt,
      error: data.error,
    });

    return NextResponse.json(data, { status: response.status });
  } catch (error) {
    console.error("[API SESSION] Error:", error);
    const message = error instanceof Error ? error.message : "Failed to create session";
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    );
  }
}
src/app/api/relay/submit/route.ts
import { NextRequest, NextResponse } from "next/server";

const RELAY_API_URL = "https://www.netprotocol.app";
const SECRET_KEY = "net-relay-public-access-key-v1";

/**
 * Submit endpoint proxy
 * Submits transactions to the relay service
 *
 * Accepts: operatorAddress, chainId, transactions[], sessionToken
 * Returns: transactionHashes[], successfulIndexes[], failedIndexes[], backendWalletAddress
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { operatorAddress, transactions, sessionToken } = body;

    console.log(`[API SUBMIT] Request:`, {
      operatorAddress: operatorAddress?.slice(0, 10) + "...",
      transactionCount: transactions?.length,
      hasSessionToken: !!sessionToken,
      sessionTokenLength: sessionToken?.length,
    });

    if (!operatorAddress) {
      return NextResponse.json(
        { success: false, error: "Missing operatorAddress" },
        { status: 400 }
      );
    }

    if (!transactions || !Array.isArray(transactions)) {
      return NextResponse.json(
        { success: false, error: "Missing transactions array" },
        { status: 400 }
      );
    }

    if (!sessionToken) {
      return NextResponse.json(
        { success: false, error: "Missing sessionToken" },
        { status: 400 }
      );
    }

    const url = `${RELAY_API_URL}/api/relay/submit`;
    console.log(`[API SUBMIT] Calling: ${url} with ${transactions.length} transactions`);

    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Relay-Secret": SECRET_KEY,
      },
      body: JSON.stringify({
        ...body,
        secretKey: SECRET_KEY,
      }),
    });

    const contentType = response.headers.get("content-type") || "";
    if (!contentType.includes("application/json")) {
      const text = await response.text();
      console.error(`[API SUBMIT] Non-JSON response (${response.status}):`, text.slice(0, 300));
      return NextResponse.json(
        { success: false, error: "Relay service unavailable" },
        { status: 502 }
      );
    }

    const data = await response.json();
    console.log(`[API SUBMIT] Response:`, {
      status: response.status,
      transactionHashes: data.transactionHashes?.length,
      successfulIndexes: data.successfulIndexes?.length,
      failedIndexes: data.failedIndexes?.length,
      error: data.error,
    });

    return NextResponse.json(data, { status: response.status });
  } catch (error) {
    console.error("[API SUBMIT] Error:", error);
    const message = error instanceof Error ? error.message : "Failed to submit transactions";
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    );
  }
}
src/app/api/relay/verify/route.ts
import { NextRequest, NextResponse } from "next/server";

const RELAY_API_URL = "https://www.netprotocol.app";
const SECRET_KEY = "net-relay-public-access-key-v1";
const BASE_CHAIN_ID = 8453;

/**
 * Verify x402 Payment Endpoint
 *
 * This endpoint proxies the x402 payment verification to the Net Protocol API.
 * It receives the X-PAYMENT header with the signed EIP-3009 authorization
 * and forwards it to complete the funding process.
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { operatorAddress, chainId } = body;

    // Get the payment header from the request
    const paymentHeader = request.headers.get("X-PAYMENT");

    console.log(`[API VERIFY] Request:`, {
      operatorAddress: operatorAddress?.slice(0, 10) + "...",
      chainId,
      hasPaymentHeader: !!paymentHeader,
    });

    if (!operatorAddress) {
      return NextResponse.json(
        { success: false, error: "Missing operatorAddress" },
        { status: 400 }
      );
    }

    if (!paymentHeader) {
      return NextResponse.json(
        { success: false, error: "Missing X-PAYMENT header" },
        { status: 400 }
      );
    }

    const chain = chainId || BASE_CHAIN_ID;

    // Call the relay API's verify endpoint with the payment header
    // The Net Protocol API expects the payment header to verify and execute the transfer
    const url = `${RELAY_API_URL}/api/relay/${chain}/verify`;

    console.log(`[API VERIFY] Calling relay verify: ${url}`);

    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-PAYMENT": paymentHeader,
      },
      body: JSON.stringify({
        operatorAddress,
        secretKey: SECRET_KEY,
      }),
    });

    // Handle non-JSON responses gracefully
    const contentType = response.headers.get("content-type") || "";
    let data;

    if (contentType.includes("application/json")) {
      data = await response.json();
    } else {
      // Server returned non-JSON (likely an error page)
      const text = await response.text();
      console.error(`[API VERIFY] Relay returned non-JSON response (${response.status}):`);
      console.error(`[API VERIFY] Content-Type: ${contentType}`);
      console.error(`[API VERIFY] Body preview: ${text.slice(0, 500)}`);
      return NextResponse.json(
        {
          success: false,
          error: `Verify endpoint returned HTML instead of JSON. Status: ${response.status}`,
          debug: {
            contentType,
            responseUrl: response.url,
            bodyPreview: text.slice(0, 200),
          }
        },
        { status: 502 }
      );
    }

    console.log(`[API VERIFY] Response status: ${response.status}`);
    console.log(`[API VERIFY] Response data:`, JSON.stringify(data, null, 2));

    // Return the response with same status code
    return NextResponse.json(data, { status: response.status });
  } catch (error) {
    console.error("[API VERIFY] Error:", error);
    const message = error instanceof Error ? error.message : "Failed to verify payment";
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    );
  }
}
src/app/api/resolve-user/route.ts
/* eslint-disable @neynar/no-process-env */
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

// KV cache TTL - 24 hours (user profiles rarely change)
const KV_CACHE_TTL = 24 * 60 * 60 * 1000;

// KV key constants for the agent registry (mirrors agent-auth.ts)
const AGENTS_REGISTRY_KEY = "api-agents-registry";
const AGENT_KEY_PREFIX = "api-agent:";

// Minimal agent shape (only fields we need here)
interface AgentRecord {
  id: string;
  name: string;
  username?: string;
  address?: string;
  pfpUrl?: string;
  fid?: number;
  isActive?: boolean;
}

// Cached user data structure
interface CachedUser {
  username: string;
  pfpUrl: string;
  fid?: number;
  displayName?: string;
  resolved: boolean;
  cachedAt: number;
}

/**
 * Look up a wallet address in the Net Library agent registry.
 * Returns a partial CachedUser if the address belongs to a registered agent, null otherwise.
 * This is the CPIS fallback for agent wallets that have no Farcaster FID — Neynar won't know
 * about them, but our own registry does.
 */
async function lookupAgentByAddress(normalizedAddress: string): Promise<Pick<CachedUser, "username" | "pfpUrl" | "fid" | "displayName"> | null> {
  try {
    const registry = await getKV<string[]>(AGENTS_REGISTRY_KEY);
    if (!registry || !Array.isArray(registry)) return null;

    for (const agentId of registry) {
      const agent = await getKV<AgentRecord>(`${AGENT_KEY_PREFIX}${agentId}`);
      if (!agent) continue;
      if (agent.isActive === false) continue;
      if (!agent.address) continue;
      if (agent.address.toLowerCase() !== normalizedAddress) continue;

      // Found the agent — build a display identity from the registry record
      const username = agent.username || agent.name || agentId;
      const pfpUrl = agent.pfpUrl || `https://api.dicebear.com/7.x/identicon/svg?seed=${agent.address}`;
      return { username, pfpUrl, fid: agent.fid, displayName: agent.name };
    }
    return null;
  } catch (err) {
    console.error("[resolve-user] Agent registry lookup error:", err);
    return null;
  }
}

// KV helpers
async function getKV<T>(key: string): Promise<T | null> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, key)).limit(1);
    if (!result[0]?.value) return null;
    return JSON.parse(result[0].value) as T;
  } catch {
    return null;
  }
}

async function setKV<T>(key: string, value: T): Promise<void> {
  try {
    const json = JSON.stringify(value);
    await db
      .insert(kv)
      .values({ key, value: json })
      .onConflictDoUpdate({ target: kv.key, set: { value: json } });
  } catch (err) {
    console.error("[resolve-user] KV set error:", err);
  }
}

// GET - Resolve wallet address to Farcaster user
export async function GET(request: NextRequest) {
  const address = request.nextUrl.searchParams.get("address");

  if (!address) {
    return NextResponse.json({ error: "Address required" }, { status: 400 });
  }

  const normalizedAddress = address.toLowerCase();
  const cacheKey = `resolved-user:${normalizedAddress}`;

  // Check KV cache first (24 hour TTL)
  const cached = await getKV<CachedUser>(cacheKey);
  if (cached && Date.now() - cached.cachedAt < KV_CACHE_TTL) {
    return NextResponse.json({
      success: true,
      username: cached.username,
      pfpUrl: cached.pfpUrl,
      fid: cached.fid,
      displayName: cached.displayName,
      resolved: cached.resolved,
      cached: true,
    });
  }

  try {
    // Use Neynar API to look up user by verified address
    const neynarApiKey = process.env.NEYNAR_API_KEY;

    if (!neynarApiKey) {
      // Fallback to truncated address if no API key
      const truncated = `${address.slice(0, 6)}...${address.slice(-4)}`;
      const fallbackData: CachedUser = {
        username: truncated,
        pfpUrl: `https://api.dicebear.com/7.x/identicon/svg?seed=${address}`,
        resolved: false,
        cachedAt: Date.now(),
      };
      await setKV(cacheKey, fallbackData);
      return NextResponse.json({
        success: true,
        username: truncated,
        pfpUrl: fallbackData.pfpUrl,
        resolved: false,
      });
    }

    // Neynar API: lookup user by verified address
    let user = null;

    const response = await fetch(
      `https://api.neynar.com/v2/farcaster/user/bulk-by-address?addresses=${normalizedAddress}`,
      {
        headers: {
          accept: "application/json",
          "x-api-key": neynarApiKey,
        },
      }
    );

    if (response.ok) {
      const data = await response.json();
      // Response format: { [address]: [array of users] }
      // Note: Neynar returns checksummed addresses as keys, so we need case-insensitive lookup
      const users = Object.entries(data).find(
        ([key]) => key.toLowerCase() === normalizedAddress.toLowerCase()
      )?.[1] as Array<{ fid: number; username: string; pfp_url: string; display_name: string }> | undefined;
      if (users && users.length > 0) {
        user = users[0];
      }
    }

    // If no user found via verified address, try custody address lookup
    if (!user) {
      try {
        const custodyResponse = await fetch(
          `https://api.neynar.com/v2/farcaster/user/custody-address?custody_address=${normalizedAddress}`,
          {
            headers: {
              accept: "application/json",
              "x-api-key": neynarApiKey,
            },
          }
        );
        if (custodyResponse.ok) {
          const custodyData = await custodyResponse.json();
          if (custodyData.user) {
            user = custodyData.user;
          }
        }
      } catch (custodyError) {
        console.error("[resolve-user] Custody lookup error:", custodyError);
      }
    }

    if (user) {
      // Found user via verified or custody address
      const username = user.username || `fid:${user.fid}`;
      const pfpUrl = user.pfp_url || `https://api.dicebear.com/7.x/identicon/svg?seed=${address}`;

      // Cache the result in KV (24 hour TTL)
      const userData: CachedUser = {
        username,
        pfpUrl,
        fid: user.fid,
        displayName: user.display_name,
        resolved: true,
        cachedAt: Date.now(),
      };
      await setKV(cacheKey, userData);

      return NextResponse.json({
        success: true,
        username,
        pfpUrl,
        fid: user.fid,
        displayName: user.display_name,
        resolved: true,
      });
    }

    // No Farcaster user found — check the Net Library agent registry before falling back to raw address.
    // Agent wallets are Bankr-created and never OAuth-linked, so Neynar won't know about them.
    // But our own agent registry has their username and metadata.
    const agentMatch = await lookupAgentByAddress(normalizedAddress);
    if (agentMatch) {
      const agentData: CachedUser = {
        username: agentMatch.username,
        pfpUrl: agentMatch.pfpUrl,
        fid: agentMatch.fid,
        displayName: agentMatch.displayName,
        resolved: true,
        cachedAt: Date.now(),
      };
      await setKV(cacheKey, agentData);
      return NextResponse.json({
        success: true,
        username: agentMatch.username,
        pfpUrl: agentMatch.pfpUrl,
        fid: agentMatch.fid,
        displayName: agentMatch.displayName,
        resolved: true,
      });
    }

    // No Farcaster user and no agent found — fall back to truncated address
    const truncated = `${address.slice(0, 6)}...${address.slice(-4)}`;

    // Cache the fallback too (24 hour TTL)
    const fallbackData: CachedUser = {
      username: truncated,
      pfpUrl: `https://api.dicebear.com/7.x/identicon/svg?seed=${address}`,
      resolved: false,
      cachedAt: Date.now(),
    };
    await setKV(cacheKey, fallbackData);

    return NextResponse.json({
      success: true,
      username: truncated,
      pfpUrl: fallbackData.pfpUrl,
      resolved: false,
    });
  } catch (error) {
    console.error("[resolve-user] Error:", error);

    // Fallback to truncated address on error
    const truncated = `${address.slice(0, 6)}...${address.slice(-4)}`;
    return NextResponse.json({
      success: true,
      username: truncated,
      pfpUrl: `https://api.dicebear.com/7.x/identicon/svg?seed=${address}`,
      resolved: false,
      error: error instanceof Error ? error.message : "Unknown error",
    });
  }
}

// POST - Batch resolve multiple addresses, FIDs, OR usernames
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { addresses, fids, usernames } = body;

    // Handle username-based lookup
    if (usernames && Array.isArray(usernames) && usernames.length > 0) {
      const neynarApiKey = process.env.NEYNAR_API_KEY;
      if (!neynarApiKey) {
        return NextResponse.json({ success: false, error: "API key not configured", users: [] });
      }

      // Limit to 100 usernames
      const limitedUsernames = usernames.slice(0, 100);

      try {
        // Use Neynar's user search endpoint for each username
        const users = [];
        for (const username of limitedUsernames) {
          const cleanUsername = username.replace("@", "").trim();
          if (!cleanUsername) continue;

          const response = await fetch(
            `https://api.neynar.com/v2/farcaster/user/by_username?username=${encodeURIComponent(cleanUsername)}`,
            {
              headers: {
                accept: "application/json",
                "x-api-key": neynarApiKey,
              },
            }
          );

          if (response.ok) {
            const data = await response.json();
            if (data.user) {
              users.push({
                fid: data.user.fid,
                username: data.user.username,
                pfp_url: data.user.pfp_url,
                display_name: data.user.display_name,
                verified_addresses: data.user.verified_addresses,
              });
            }
          } else {
            console.error(`[resolve-user] Username lookup failed for ${cleanUsername}:`, response.status);
          }
        }

        return NextResponse.json({
          success: true,
          users,
        });
      } catch (usernameError) {
        console.error("[resolve-user] Username lookup error:", usernameError);
        return NextResponse.json({ success: false, error: "Username lookup failed", users: [] });
      }
    }

    // Handle FID-based lookup
    if (fids && Array.isArray(fids) && fids.length > 0) {
      const neynarApiKey = process.env.NEYNAR_API_KEY;
      if (!neynarApiKey) {
        return NextResponse.json({ success: true, users: [] });
      }

      // Limit to 100 FIDs
      const limitedFids = fids.slice(0, 100);

      try {
        const response = await fetch(
          `https://api.neynar.com/v2/farcaster/user/bulk?fids=${limitedFids.join(",")}`,
          {
            headers: {
              accept: "application/json",
              "x-api-key": neynarApiKey,
            },
          }
        );

        if (!response.ok) {
          console.error("[resolve-user] FID bulk lookup error:", response.status);
          return NextResponse.json({ success: true, users: [] });
        }

        const data = await response.json();
        const users = data.users || [];

        return NextResponse.json({
          success: true,
          users: users.map((u: { fid: number; username: string; pfp_url: string; display_name: string; verified_addresses?: { eth_addresses?: string[] } }) => ({
            fid: u.fid,
            username: u.username,
            pfp_url: u.pfp_url,
            display_name: u.display_name,
            verified_addresses: u.verified_addresses, // Include verified addresses for membership lookup
          })),
        });
      } catch (fidError) {
        console.error("[resolve-user] FID lookup error:", fidError);
        return NextResponse.json({ success: true, users: [] });
      }
    }

    // Original address-based lookup
    if (!addresses || !Array.isArray(addresses) || addresses.length === 0) {
      return NextResponse.json({ error: "Addresses or fids array required" }, { status: 400 });
    }

    // Limit to 100 addresses per request
    const limitedAddresses = addresses.slice(0, 100);
    const normalizedAddresses = limitedAddresses.map((a: string) => a.toLowerCase());

    const results: { [address: string]: { username: string; pfpUrl: string; fid?: number; displayName?: string; resolved: boolean } } = {};

    // Check KV cache first (24 hour TTL)
    const uncachedAddresses: string[] = [];
    for (const addr of normalizedAddresses) {
      const cacheKey = `resolved-user:${addr}`;
      const cached = await getKV<CachedUser>(cacheKey);
      if (cached && Date.now() - cached.cachedAt < KV_CACHE_TTL) {
        results[addr] = {
          username: cached.username,
          pfpUrl: cached.pfpUrl,
          fid: cached.fid,
          displayName: cached.displayName,
          resolved: cached.resolved,
        };
      } else {
        uncachedAddresses.push(addr);
      }
    }

    // If all cached, return immediately
    if (uncachedAddresses.length === 0) {
      return NextResponse.json({ success: true, users: results });
    }

    // Fetch uncached from Neynar
    const neynarApiKey = process.env.NEYNAR_API_KEY;

    if (!neynarApiKey) {
      // Fallback for all uncached
      for (const addr of uncachedAddresses) {
        const truncated = `${addr.slice(0, 6)}...${addr.slice(-4)}`;
        const fallbackData: CachedUser = {
          username: truncated,
          pfpUrl: `https://api.dicebear.com/7.x/identicon/svg?seed=${addr}`,
          resolved: false,
          cachedAt: Date.now(),
        };
        await setKV(`resolved-user:${addr}`, fallbackData);
        results[addr] = {
          username: truncated,
          pfpUrl: fallbackData.pfpUrl,
          resolved: false,
        };
      }
      return NextResponse.json({ success: true, users: results });
    }

    // First, try Neynar API bulk lookup by verified addresses
    const response = await fetch(
      `https://api.neynar.com/v2/farcaster/user/bulk-by-address?addresses=${uncachedAddresses.join(",")}`,
      {
        headers: {
          accept: "application/json",
          "x-api-key": neynarApiKey,
        },
      }
    );

    // Track which addresses were NOT found by verified address lookup
    const unresolvedAddresses: string[] = [];

    if (response.ok) {
      const data = await response.json();

      for (const addr of uncachedAddresses) {
        // Note: Neynar returns checksummed addresses as keys, so we need case-insensitive lookup
        const users = Object.entries(data).find(
          ([key]) => key.toLowerCase() === addr.toLowerCase()
        )?.[1] as Array<{ fid: number; username: string; pfp_url: string; display_name: string }> | undefined;
        if (users && users.length > 0) {
          const user = users[0];
          const username = user.username || `fid:${user.fid}`;
          const pfpUrl = user.pfp_url || `https://api.dicebear.com/7.x/identicon/svg?seed=${addr}`;

          // Cache in KV (24 hour TTL)
          const userData: CachedUser = {
            username,
            pfpUrl,
            fid: user.fid,
            displayName: user.display_name,
            resolved: true,
            cachedAt: Date.now(),
          };
          await setKV(`resolved-user:${addr}`, userData);

          results[addr] = { username, pfpUrl, fid: user.fid, displayName: user.display_name, resolved: true };
        } else {
          // Not found by verified address - will try custody address lookup
          unresolvedAddresses.push(addr);
        }
      }
    } else {
      // API error - try all addresses in custody lookup
      unresolvedAddresses.push(...uncachedAddresses);
    }

    // For addresses not found by verified lookup, try custody address lookup
    // This catches users whose connected wallet is their Farcaster custody address
    if (unresolvedAddresses.length > 0) {
      try {
        // Neynar doesn't have bulk custody lookup, so we need to try each one
        // But we can use the "user by custody address" endpoint
        for (const addr of unresolvedAddresses) {
          try {
            const custodyResponse = await fetch(
              `https://api.neynar.com/v2/farcaster/user/custody-address?custody_address=${addr}`,
              {
                headers: {
                  accept: "application/json",
                  "x-api-key": neynarApiKey,
                },
              }
            );

            if (custodyResponse.ok) {
              const custodyData = await custodyResponse.json();
              if (custodyData.user) {
                const user = custodyData.user;
                const username = user.username || `fid:${user.fid}`;
                const pfpUrl = user.pfp_url || `https://api.dicebear.com/7.x/identicon/svg?seed=${addr}`;

                // Cache in KV (24 hour TTL)
                const userData: CachedUser = {
                  username,
                  pfpUrl,
                  fid: user.fid,
                  displayName: user.display_name,
                  resolved: true,
                  cachedAt: Date.now(),
                };
                await setKV(`resolved-user:${addr}`, userData);

                results[addr] = { username, pfpUrl, fid: user.fid, displayName: user.display_name, resolved: true };
                continue; // Found via custody address
              }
            }
          } catch {
            // Individual custody lookup failed, continue to fallback
          }

          // Not found via Neynar — check the agent registry before falling back to raw address
          const agentMatch = await lookupAgentByAddress(addr);
          if (agentMatch) {
            const agentData: CachedUser = {
              username: agentMatch.username,
              pfpUrl: agentMatch.pfpUrl,
              fid: agentMatch.fid,
              displayName: agentMatch.displayName,
              resolved: true,
              cachedAt: Date.now(),
            };
            await setKV(`resolved-user:${addr}`, agentData);
            results[addr] = { username: agentMatch.username, pfpUrl: agentMatch.pfpUrl, fid: agentMatch.fid, displayName: agentMatch.displayName, resolved: true };
            continue;
          }

          // Final fallback - not found via Neynar or agent registry
          const truncated = `${addr.slice(0, 6)}...${addr.slice(-4)}`;
          const fallbackData: CachedUser = {
            username: truncated,
            pfpUrl: `https://api.dicebear.com/7.x/identicon/svg?seed=${addr}`,
            resolved: false,
            cachedAt: Date.now(),
          };
          await setKV(`resolved-user:${addr}`, fallbackData);

          results[addr] = {
            username: truncated,
            pfpUrl: fallbackData.pfpUrl,
            resolved: false,
          };
        }
      } catch (custodyError) {
        console.error("[resolve-user] Custody lookup error:", custodyError);
        // Fallback for all unresolved
        for (const addr of unresolvedAddresses) {
          if (!results[addr]) {
            const truncated = `${addr.slice(0, 6)}...${addr.slice(-4)}`;
            results[addr] = {
              username: truncated,
              pfpUrl: `https://api.dicebear.com/7.x/identicon/svg?seed=${addr}`,
              resolved: false,
            };
          }
        }
      }
    }

    return NextResponse.json({ success: true, users: results });
  } catch (error) {
    console.error("[resolve-user] Batch error:", error);
    return NextResponse.json({ error: "Failed to resolve users" }, { status: 500 });
  }
}
src/app/api/search/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

interface DiscoveryEntry {
  contentKey: string;
  metadataKey: string;
  operator: string;
  title: string;
  author: string;
  categories: string[];
  fileSize: number;
  storageType: string;
  coverUrl?: string;
  timestamp: number;
}

interface DiscoveryIndex {
  entries: DiscoveryEntry[];
  lastUpdated: number;
}

const DISCOVERY_KV_KEY = "discovery-index";

// Helper to fetch discovery index
async function fetchDiscoveryIndex(): Promise<DiscoveryIndex> {
  const empty: DiscoveryIndex = { entries: [], lastUpdated: 0 };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KV_KEY)).limit(1);
    if (!result[0]?.value) return empty;
    const raw = JSON.parse(result[0].value);
    // Handle both storage shapes: flat DiscoveryEntry[] array OR wrapped { entries, lastUpdated }
    if (Array.isArray(raw)) {
      return { entries: raw, lastUpdated: 0 };
    }
    return raw as DiscoveryIndex;
  } catch {
    return empty;
  }
}

// GET - Search items
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const query = searchParams.get("q")?.toLowerCase().trim();
    const category = searchParams.get("category");
    const author = searchParams.get("author");
    const limit = Math.min(parseInt(searchParams.get("limit") || "20"), 50);

    if (!query && !category && !author) {
      return NextResponse.json({ error: "Missing search query" }, { status: 400 });
    }

    // Fetch all entries from the discovery index
    const index = await fetchDiscoveryIndex();
    const entries = index.entries || [];

    let results = entries;

    // Filter by text query (searches title, author)
    if (query) {
      const queryWords = query.split(/\s+/).filter(w => w.length > 1);

      results = results.filter(entry => {
        const titleLower = (entry.title || '').toLowerCase();
        const authorLower = (entry.author || '').toLowerCase();
        const categoriesLower = (entry.categories || []).join(" ").toLowerCase();

        // Check if any query word matches
        return queryWords.some(word =>
          titleLower.includes(word) ||
          authorLower.includes(word) ||
          categoriesLower.includes(word)
        );
      });

      // Sort by relevance (title matches first, then author)
      results.sort((a, b) => {
        const aTitle = (a.title || '').toLowerCase();
        const bTitle = (b.title || '').toLowerCase();
        const aAuthor = (a.author || '').toLowerCase();
        const bAuthor = (b.author || '').toLowerCase();

        // Exact title match first
        const aExactTitle = queryWords.some(w => aTitle === w);
        const bExactTitle = queryWords.some(w => bTitle === w);
        if (aExactTitle && !bExactTitle) return -1;
        if (bExactTitle && !aExactTitle) return 1;

        // Title starts with query
        const aStartsTitle = queryWords.some(w => aTitle.startsWith(w));
        const bStartsTitle = queryWords.some(w => bTitle.startsWith(w));
        if (aStartsTitle && !bStartsTitle) return -1;
        if (bStartsTitle && !aStartsTitle) return 1;

        // Title contains query
        const aTitleMatch = queryWords.some(w => aTitle.includes(w));
        const bTitleMatch = queryWords.some(w => bTitle.includes(w));
        if (aTitleMatch && !bTitleMatch) return -1;
        if (bTitleMatch && !aTitleMatch) return 1;

        // Author match
        const aAuthorMatch = queryWords.some(w => aAuthor.includes(w));
        const bAuthorMatch = queryWords.some(w => bAuthor.includes(w));
        if (aAuthorMatch && !bAuthorMatch) return -1;
        if (bAuthorMatch && !aAuthorMatch) return 1;

        return 0;
      });
    }

    // Filter by category
    if (category) {
      results = results.filter(entry =>
        (entry.categories || []).some(c => c && c.toLowerCase() === category.toLowerCase())
      );
    }

    // Filter by author
    if (author) {
      results = results.filter(entry =>
        (entry.author || '').toLowerCase().includes(author.toLowerCase())
      );
    }

    // Limit results
    results = results.slice(0, limit);

    return NextResponse.json({
      results,
      total: results.length,
      query,
    });
  } catch (error) {
    console.error("[search] GET error:", error);
    return NextResponse.json({ error: "Search failed" }, { status: 500 });
  }
}
src/app/api/social/fetch/route.ts
import { NextRequest, NextResponse } from "next/server";
import type { SocialPlatform, SocialContent } from "@/features/app/components/social-receipt-upload";

// Helper to extract images from Twitter syndication response
// The API returns images in multiple possible locations
function extractTwitterImages(data: Record<string, unknown>): string[] {
  const images: string[] = [];

  // 1. Check data.photos (array of { url, width, height })
  if (Array.isArray(data.photos)) {
    for (const photo of data.photos) {
      if (photo && typeof photo === 'object' && 'url' in photo && typeof photo.url === 'string') {
        images.push(photo.url);
      }
    }
  }

  // 2. Check data.mediaDetails (array with media_url_https)
  if (images.length === 0 && Array.isArray(data.mediaDetails)) {
    for (const media of data.mediaDetails) {
      if (media && typeof media === 'object' && media.type === 'photo') {
        if ('media_url_https' in media && typeof media.media_url_https === 'string') {
          images.push(media.media_url_https);
        }
      }
    }
  }

  // 3. Check data.entities?.media (legacy format)
  if (images.length === 0 && data.entities && typeof data.entities === 'object') {
    const entities = data.entities as { media?: Array<{ type?: string; media_url_https?: string }> };
    if (Array.isArray(entities.media)) {
      for (const media of entities.media) {
        if (media?.type === 'photo' && media.media_url_https) {
          images.push(media.media_url_https);
        }
      }
    }
  }

  // 4. Check data.extended_entities?.media (for multi-image tweets)
  if (images.length === 0 && data.extended_entities && typeof data.extended_entities === 'object') {
    const extEntities = data.extended_entities as { media?: Array<{ type?: string; media_url_https?: string }> };
    if (Array.isArray(extEntities.media)) {
      for (const media of extEntities.media) {
        if (media?.type === 'photo' && media.media_url_https) {
          images.push(media.media_url_https);
        }
      }
    }
  }

  // 5. Check card?.binding_values for link preview images (Twitter cards)
  if (images.length === 0 && data.card && typeof data.card === 'object') {
    const card = data.card as { binding_values?: { thumbnail_image_large?: { image_value?: { url?: string } }; thumbnail_image?: { image_value?: { url?: string } } } };
    const thumbnailLarge = card.binding_values?.thumbnail_image_large?.image_value?.url;
    const thumbnail = card.binding_values?.thumbnail_image?.image_value?.url;
    if (thumbnailLarge) images.push(thumbnailLarge);
    else if (thumbnail) images.push(thumbnail);
  }

  return images;
}

// Platform-specific fetchers
async function fetchTwitter(url: string): Promise<SocialContent> {
  // Extract tweet ID
  const match = url.match(/(?:twitter\.com|x\.com)\/(\w+)\/status\/(\d+)/i);
  if (!match) throw new Error("Invalid Twitter URL");
  const [, username, tweetId] = match;

  // Try syndication API first (no auth needed)
  const syndicationUrl = `https://cdn.syndication.twimg.com/tweet-result?id=${tweetId}&token=0`;
  const response = await fetch(syndicationUrl, {
    headers: { "User-Agent": "Mozilla/5.0" },
  });

  if (response.ok) {
    const data = await response.json();

    // Extract images from all possible locations
    const images = extractTwitterImages(data);

    return {
      platform: "twitter",
      id: tweetId,
      url,
      text: data.text || "",
      author: {
        displayName: data.user?.name || username,
        username: data.user?.screen_name || username,
        avatarUrl: data.user?.profile_image_url_https?.replace("_normal", "_400x400"),
        verified: data.user?.verified || data.user?.is_blue_verified,
      },
      timestamp: new Date(data.created_at || Date.now()),
      images,
      likes: data.favorite_count,
      reposts: data.retweet_count,
      replies: data.reply_count,
    };
  }

  // Fallback to oEmbed
  const oembedUrl = `https://publish.twitter.com/oembed?url=${encodeURIComponent(url)}`;
  const oembedResponse = await fetch(oembedUrl);
  if (oembedResponse.ok) {
    const oembed = await oembedResponse.json();
    // Parse author from oembed
    const authorMatch = oembed.author_name?.match(/(.+)\s+\(@(\w+)\)/);
    return {
      platform: "twitter",
      id: tweetId,
      url,
      text: oembed.html?.replace(/<[^>]+>/g, "").trim() || "",
      author: {
        displayName: authorMatch?.[1] || oembed.author_name || username,
        username: authorMatch?.[2] || username,
      },
      timestamp: new Date(),
    };
  }

  throw new Error("Failed to fetch tweet");
}

async function fetchYouTube(url: string): Promise<SocialContent> {
  // Extract video ID
  let videoId: string | null = null;
  const patterns = [
    /[?&]v=([a-zA-Z0-9_-]{11})/,
    /youtu\.be\/([a-zA-Z0-9_-]{11})/,
    /youtube\.com\/(shorts|live)\/([a-zA-Z0-9_-]{11})/,
  ];
  for (const pattern of patterns) {
    const match = url.match(pattern);
    if (match) {
      videoId = match[pattern.source.includes("shorts|live") ? 2 : 1];
      break;
    }
  }
  if (!videoId) throw new Error("Invalid YouTube URL");

  // Use oEmbed API
  const oembedUrl = `https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=${videoId}&format=json`;
  const response = await fetch(oembedUrl);
  if (!response.ok) throw new Error("Failed to fetch YouTube video");

  const data = await response.json();

  return {
    platform: "youtube",
    id: videoId,
    url,
    text: data.title || "",
    author: {
      displayName: data.author_name || "Unknown",
      username: data.author_url?.split("/").pop() || "unknown",
    },
    timestamp: new Date(),
    thumbnailUrl: data.thumbnail_url || `https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`,
  };
}

async function fetchReddit(url: string): Promise<SocialContent> {
  // Convert to .json URL
  let jsonUrl = url;
  if (!jsonUrl.endsWith(".json")) {
    jsonUrl = jsonUrl.replace(/\/$/, "") + ".json";
  }

  const response = await fetch(jsonUrl, {
    headers: { "User-Agent": "Mozilla/5.0 (compatible; NetLibrary/1.0)" },
  });
  if (!response.ok) throw new Error("Failed to fetch Reddit post");

  const data = await response.json();
  const post = data[0]?.data?.children?.[0]?.data;
  if (!post) throw new Error("Invalid Reddit response");

  return {
    platform: "reddit",
    id: post.id,
    url,
    text: post.title + (post.selftext ? `\n\n${post.selftext}` : ""),
    author: {
      displayName: post.author,
      username: post.author,
    },
    timestamp: new Date(post.created_utc * 1000),
    images: post.url?.match(/\.(jpg|jpeg|png|gif|webp)/i) ? [post.url] :
      post.preview?.images?.[0]?.source?.url?.replace(/&amp;/g, "&") ? [post.preview.images[0].source.url.replace(/&amp;/g, "&")] : [],
    score: post.score,
    replies: post.num_comments,
    subreddit: post.subreddit,
  };
}

async function fetchInstagram(url: string): Promise<SocialContent> {
  // Extract shortcode
  const match = url.match(/instagram\.com\/(p|reel|reels)\/([\w-]+)/i);
  if (!match) throw new Error("Invalid Instagram URL");
  const shortcode = match[2];

  // Use oEmbed API (limited but works without auth)
  const oembedUrl = `https://api.instagram.com/oembed?url=${encodeURIComponent(url)}`;
  const response = await fetch(oembedUrl);

  if (response.ok) {
    const data = await response.json();
    return {
      platform: "instagram",
      id: shortcode,
      url,
      text: data.title || "",
      author: {
        displayName: data.author_name || "Unknown",
        username: data.author_name || "unknown",
      },
      timestamp: new Date(),
      thumbnailUrl: data.thumbnail_url,
    };
  }

  // Minimal fallback
  return {
    platform: "instagram",
    id: shortcode,
    url,
    text: "Instagram post",
    author: {
      displayName: "Instagram User",
      username: "instagram",
    },
    timestamp: new Date(),
  };
}

async function fetchTikTok(url: string): Promise<SocialContent> {
  // Use oEmbed API
  const oembedUrl = `https://www.tiktok.com/oembed?url=${encodeURIComponent(url)}`;
  const response = await fetch(oembedUrl);

  if (!response.ok) throw new Error("Failed to fetch TikTok video");

  const data = await response.json();

  // Extract video ID from URL
  const videoIdMatch = url.match(/video\/(\d+)/);
  const videoId = videoIdMatch?.[1] || data.embed_product_id || "unknown";

  return {
    platform: "tiktok",
    id: videoId,
    url,
    text: data.title || "",
    author: {
      displayName: data.author_name || "TikTok User",
      username: data.author_unique_id || data.author_name || "unknown",
    },
    timestamp: new Date(),
    thumbnailUrl: data.thumbnail_url,
  };
}

async function fetchBluesky(url: string): Promise<SocialContent> {
  // Extract handle and post ID
  const match = url.match(/bsky\.app\/profile\/([\w.]+)\/post\/(\w+)/i);
  if (!match) throw new Error("Invalid Bluesky URL");
  const [, handle, postId] = match;

  // Use public API
  const apiUrl = `https://public.api.bsky.app/xrpc/app.bsky.feed.getPostThread?uri=at://${handle}/app.bsky.feed.post/${postId}&depth=0`;
  const response = await fetch(apiUrl);

  if (!response.ok) throw new Error("Failed to fetch Bluesky post");

  const data = await response.json();
  const post = data.thread?.post;
  if (!post) throw new Error("Invalid Bluesky response");

  return {
    platform: "bluesky",
    id: postId,
    url,
    text: post.record?.text || "",
    author: {
      displayName: post.author?.displayName || handle,
      username: post.author?.handle || handle,
      avatarUrl: post.author?.avatar,
    },
    timestamp: new Date(post.record?.createdAt || Date.now()),
    images: post.embed?.images?.map((img: { fullsize: string }) => img.fullsize) || [],
    likes: post.likeCount,
    reposts: post.repostCount,
    replies: post.replyCount,
  };
}

async function fetchThreads(_url: string): Promise<SocialContent> {
  // Threads does not have a public API for post content.
  // _url is kept in the signature to match the platform dispatch function type.
  throw new Error(
    "Direct archiving for Threads is not yet supported. Copy the post text and use the Text Upload feature instead."
  );
}

async function fetchLinkedIn(_url: string): Promise<SocialContent> {
  // LinkedIn does not have a public API for post content.
  // _url is kept in the signature to match the platform dispatch function type.
  throw new Error(
    "Direct archiving for LinkedIn is not yet supported. Copy the post text and use the Text Upload feature instead."
  );
}

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const platform = searchParams.get("platform") as SocialPlatform | null;
  const url = searchParams.get("url");

  if (!platform || !url) {
    return NextResponse.json(
      { error: "Platform and URL are required" },
      { status: 400 }
    );
  }

  try {
    let content: SocialContent;

    switch (platform) {
      case "twitter":
        content = await fetchTwitter(url);
        break;
      case "youtube":
        content = await fetchYouTube(url);
        break;
      case "reddit":
        content = await fetchReddit(url);
        break;
      case "instagram":
        content = await fetchInstagram(url);
        break;
      case "tiktok":
        content = await fetchTikTok(url);
        break;
      case "bluesky":
        content = await fetchBluesky(url);
        break;
      case "threads":
        content = await fetchThreads(url);
        break;
      case "linkedin":
        content = await fetchLinkedIn(url);
        break;
      case "farcaster":
        // Farcaster is handled client-side via Neynar hook
        return NextResponse.json(
          { error: "Farcaster should be fetched via client-side Neynar SDK" },
          { status: 400 }
        );
      default:
        return NextResponse.json(
          { error: `Unsupported platform: ${platform}` },
          { status: 400 }
        );
    }

    return NextResponse.json({ success: true, content });
  } catch (error) {
    console.error(`[Social Fetch] Error fetching ${platform}:`, error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "Failed to fetch content" },
      { status: 500 }
    );
  }
}
src/app/api/social/receipt/route.tsx
import { NextRequest, NextResponse } from "next/server";
import {
  renderSocialReceipt,
  type SocialContent,
} from "@/lib/receipt-renderer";

export const runtime = "edge";
export const maxDuration = 30;

// POST endpoint to generate receipt image
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const content: SocialContent = body.content;

    if (!content) {
      return NextResponse.json({ error: "content is required" }, { status: 400 });
    }

    const host = request.headers.get("host") || "netlibrary.neynar.com";
    const protocol = host.includes("localhost") ? "http" : "https";
    const appBaseUrl = `${protocol}://${host}`;

    const { dataUrl, coverKey } = await renderSocialReceipt(content, { appBaseUrl });

    // Also upload to cover storage for persistence/caching (fire and forget)
    try {
      await fetch(`${appBaseUrl}/api/covers/${coverKey}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ dataUrl, contentKey: coverKey }),
      });
    } catch (e) {
      console.warn("[Receipt API] Cover storage failed (non-critical):", e);
    }

    return NextResponse.json({ success: true, imageUrl: dataUrl, receiptId: coverKey });
  } catch (error) {
    console.error("[Receipt API] Error generating receipt:", error);
    return NextResponse.json({ error: "Failed to generate receipt image" }, { status: 500 });
  }
}

// GET endpoint to retrieve a previously generated receipt
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const platform = searchParams.get("platform");
  const id = searchParams.get("id");

  if (!platform || !id) {
    return NextResponse.json({ error: "platform and id are required" }, { status: 400 });
  }

  const host = request.headers.get("host") || "netlibrary.neynar.com";
  const protocol = host.includes("localhost") ? "http" : "https";
  const coverKey = `receipt-${platform}-${id}`;
  const coverUrl = `${protocol}://${host}/api/covers/${coverKey}`;

  try {
    const response = await fetch(coverUrl, { method: "HEAD" });
    if (response.ok) {
      return NextResponse.json({ imageUrl: coverUrl });
    }
    return NextResponse.json({ error: "Receipt not found" }, { status: 404 });
  } catch {
    return NextResponse.json({ error: "Receipt not found" }, { status: 404 });
  }
}
src/app/api/social/twitter/route.ts
import { NextRequest, NextResponse } from "next/server";

/**
 * Twitter/X scraping API
 * Fetches tweet data for archival
 *
 * Note: Twitter's API is expensive and requires auth.
 * This implementation uses a combination of:
 * 1. Syndication API (for basic public tweets)
 * 2. OEmbed API (for rendering)
 * 3. Fallback scraping if needed
 */

interface TwitterUser {
  id_str: string;
  name: string;
  screen_name: string;
  profile_image_url_https: string;
  verified?: boolean;
}

interface TwitterMedia {
  type: "photo" | "video" | "animated_gif";
  media_url_https: string;
}

interface _TwitterTweet {
  id_str: string;
  full_text?: string;
  text?: string;
  user: TwitterUser;
  created_at: string;
  favorite_count: number;
  retweet_count: number;
  reply_count?: number;
  extended_entities?: {
    media?: TwitterMedia[];
  };
  entities?: {
    media?: TwitterMedia[];
  };
  is_quote_status?: boolean;
  quoted_status?: _TwitterTweet;
}

interface SocialAuthor {
  displayName: string;
  username: string;
  avatarUrl?: string;
  verified?: boolean;
}

interface SocialContent {
  platform: "twitter";
  id: string;
  url: string;
  text: string;
  author: SocialAuthor;
  timestamp: Date;
  images?: string[];
  likes?: number;
  reposts?: number;
  replies?: number;
  views?: number; // Impressions - may not always be available
}

// Extract tweet ID from URL
function extractTweetId(url: string): string | null {
  const match = url.match(/(?:twitter\.com|x\.com)\/\w+\/status\/(\d+)/i);
  return match ? match[1] : null;
}

// Format date for display
function parseTwitterDate(dateStr: string): Date {
  // Twitter date format: "Wed Oct 10 20:19:24 +0000 2018"
  return new Date(dateStr);
}

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const url = searchParams.get("url");

  if (!url) {
    return NextResponse.json({ error: "URL parameter required" }, { status: 400 });
  }

  const tweetId = extractTweetId(url);
  if (!tweetId) {
    return NextResponse.json({ error: "Invalid Twitter/X URL" }, { status: 400 });
  }

  try {
    // Method 1: Try Twitter's syndication API (public, no auth needed)
    // This is the same API that powers embedded tweets
    const syndicationUrl = `https://syndication.twitter.com/tweet-result?id=${tweetId}&lang=en&token=a`;

    const response = await fetch(syndicationUrl, {
      headers: {
        "User-Agent": "Mozilla/5.0 (compatible; NetLibrary/1.0)",
        "Accept": "application/json",
      },
    });

    if (!response.ok) {
      // Method 2: Try publish.twitter.com OEmbed
      const oembedUrl = `https://publish.twitter.com/oembed?url=${encodeURIComponent(url)}&omit_script=true`;
      const oembedResponse = await fetch(oembedUrl);

      if (oembedResponse.ok) {
        const oembed = await oembedResponse.json();

        // Parse author from the HTML (format: <blockquote>...<a href="...">@username</a></blockquote>)
        const authorMatch = oembed.author_url?.match(/twitter\.com\/(\w+)/i);
        const username = authorMatch ? authorMatch[1] : "unknown";

        // Extract text from HTML (basic parsing)
        const textMatch = oembed.html?.match(/<p[^>]*>([^<]+)<\/p>/);
        const text = textMatch ? textMatch[1] : oembed.html?.replace(/<[^>]+>/g, "") || "";

        const content: SocialContent = {
          platform: "twitter",
          id: tweetId,
          url: url,
          text: text.trim(),
          author: {
            displayName: oembed.author_name || username,
            username: username,
            verified: false,
          },
          timestamp: new Date(),
          likes: 0,
          reposts: 0,
          replies: 0,
        };

        return NextResponse.json({ content });
      }

      return NextResponse.json(
        { error: "Tweet not found or unavailable" },
        { status: 404 }
      );
    }

    const data = await response.json();

    // Handle the syndication response format
    // Note: Format can vary, handle multiple structures
    const tweet = data.__typename === "Tweet" ? data : data;

    // Extract user info
    const user = tweet.user || tweet.core?.user_results?.result?.legacy || {};
    const legacy = tweet.legacy || tweet;

    // Build the social content object
    const content: SocialContent = {
      platform: "twitter",
      id: tweetId,
      url: url,
      text: legacy.full_text || legacy.text || tweet.text || "",
      author: {
        displayName: user.name || user.screen_name || "Unknown",
        username: user.screen_name || "unknown",
        avatarUrl: user.profile_image_url_https?.replace("_normal", "_400x400"),
        verified: user.verified || user.is_blue_verified || false,
      },
      timestamp: legacy.created_at
        ? parseTwitterDate(legacy.created_at)
        : new Date(tweet.created_at || Date.now()),
      images: [],
      likes: legacy.favorite_count || tweet.favorite_count || 0,
      reposts: legacy.retweet_count || tweet.retweet_count || 0,
      replies: legacy.reply_count || tweet.reply_count || 0,
      // Views/impressions - syndication API sometimes includes this
      // Note: Twitter restricts impression data, so this may be undefined
      views: legacy.views?.count || tweet.views?.count || tweet.view_count || undefined,
    };

    // Extract media - Twitter returns images in multiple possible formats
    // 1. data.photos (array of { url, width, height }) - most common in syndication API
    if (Array.isArray(data.photos) && data.photos.length > 0) {
      content.images = data.photos
        .filter((p: { url?: string }) => p.url)
        .map((p: { url: string }) => p.url);
    }
    // 2. mediaDetails (array with media_url_https)
    else if (Array.isArray(tweet.mediaDetails) && tweet.mediaDetails.length > 0) {
      content.images = tweet.mediaDetails
        .filter((m: TwitterMedia) => m.type === "photo")
        .map((m: TwitterMedia) => m.media_url_https);
    }
    // 3. extended_entities or entities (legacy format)
    else {
      const media = legacy.extended_entities?.media || legacy.entities?.media || [];
      if (Array.isArray(media)) {
        content.images = media
          .filter((m: TwitterMedia) => m.type === "photo")
          .map((m: TwitterMedia) => m.media_url_https);
      }
    }
    // 4. Check for card thumbnails (link preview images)
    if (content.images?.length === 0 && data.card?.binding_values) {
      const card = data.card.binding_values as Record<string, { image_value?: { url?: string } }>;
      const thumbnailUrl = card.thumbnail_image_large?.image_value?.url || card.thumbnail_image?.image_value?.url;
      if (thumbnailUrl) {
        content.images = [thumbnailUrl];
      }
    }

    return NextResponse.json({ content });
  } catch (error) {
    console.error("[Twitter API] Error fetching tweet:", error);
    return NextResponse.json(
      { error: "Failed to fetch tweet. The tweet may be private or deleted." },
      { status: 500 }
    );
  }
}
src/app/api/source-files/download/route.ts
import { NextResponse } from "next/server";
import fs from "fs/promises";
import path from "path";
import JSZip from "jszip";
import { redactSecrets } from "@/lib/redact-secrets";

// Download all source files as a ZIP
// GET /api/source-files/download

// Directories under src/ that are platform-internal SDK bundles — not app source.
// Everything else under src/ and the public static files are included automatically.
const EXCLUDED_DIR_PREFIXES = [
  "src/neynar-db-sdk/",
  "src/neynar-farcaster-sdk/",
  "src/neynar-web-sdk/",
];

// Always include these public static files regardless of the src/ walk.
const EXTRA_FILES = [
  "public/netlibrary-eth-landing.html",
  "public/net-library-docs.html",
];

// Recursively collect all file paths under `dir`, returning paths relative to
// `projectRoot`. Skips node_modules, .next, .git, and generated output dirs.
async function collectSourceFiles(
  dir: string,
  projectRoot: string
): Promise<string[]> {
  const results: string[] = [];
  let entries: import("fs").Dirent[];
  try {
    entries = await fs.readdir(dir, { withFileTypes: true });
  } catch {
    return results;
  }

  for (const entry of entries) {
    const absPath = path.join(dir, entry.name);
    const relPath = path.relative(projectRoot, absPath).replace(/\\/g, "/");

    if (entry.isDirectory()) {
      // Skip non-app directories at the src level
      const skipDirs = ["node_modules", ".next", ".git", "dist", "build", ".turbo", "coverage"];
      if (skipDirs.includes(entry.name)) continue;
      // Skip SDK internals
      if (EXCLUDED_DIR_PREFIXES.some(prefix => (relPath + "/").startsWith(prefix))) continue;
      results.push(...await collectSourceFiles(absPath, projectRoot));
    } else if (entry.isFile()) {
      // Only include TypeScript, TSX, JS, JSX, CSS, and JSON source files
      if (/\.(tsx?|jsx?|css|json)$/.test(entry.name)) {
        // Skip generated/lock files
        if (["package-lock.json", "yarn.lock", "pnpm-lock.yaml"].includes(entry.name)) continue;
        results.push(relPath);
      }
    }
  }

  return results;
}

// Generate a standalone HTML file with all code embedded
function generateStandaloneHtml(files: { path: string; content: string }[]): string {
  // Group files by category
  const hooks = files.filter(f => f.path.includes("/hooks/"));
  const components = files.filter(f => f.path.includes("/components/"));
  const apis = files.filter(f => f.path.includes("/api/") && !f.path.includes("/share/"));
  const share = files.filter(f => f.path.includes("/share/"));
  const other = files.filter(f => !hooks.includes(f) && !components.includes(f) && !apis.includes(f) && !share.includes(f));

  const escapeHtml = (str: string) => str
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");

  const renderFileSection = (title: string, emoji: string, fileList: { path: string; content: string }[]) => {
    if (fileList.length === 0) return "";
    return `
    <div class="category">
      <h2>${emoji} ${title} (${fileList.length})</h2>
      ${fileList.map(f => `
        <div class="file">
          <div class="file-header">${f.path}</div>
          <pre class="code"><code>${escapeHtml(f.content)}</code></pre>
        </div>
      `).join("")}
    </div>`;
  };

  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Net Library - Complete Source Code</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body {
      font-family: 'Segoe UI', system-ui, sans-serif;
      background: #0a0a0a;
      color: #e0e0e0;
      line-height: 1.6;
    }
    .header {
      background: linear-gradient(135deg, #0f0f0f, #1a1a1a);
      border-bottom: 2px solid #00ff00;
      padding: 24px;
      text-align: center;
    }
    .header h1 { color: #00ff00; font-size: 28px; margin-bottom: 8px; }
    .header p { color: #888; font-size: 14px; }
    .stats {
      display: flex;
      justify-content: center;
      gap: 24px;
      margin-top: 16px;
      flex-wrap: wrap;
    }
    .stat {
      background: #1a1a1a;
      padding: 12px 20px;
      border-radius: 8px;
      border: 1px solid #333;
    }
    .stat-value { color: #00ff00; font-size: 24px; font-weight: bold; }
    .stat-label { color: #666; font-size: 11px; }
    .toc {
      background: #111;
      padding: 20px;
      border-bottom: 1px solid #222;
    }
    .toc h3 { color: #00ff00; margin-bottom: 12px; }
    .toc a {
      color: #888;
      text-decoration: none;
      display: inline-block;
      margin: 4px 12px 4px 0;
      font-size: 13px;
    }
    .toc a:hover { color: #00ff00; }
    .container { max-width: 1200px; margin: 0 auto; padding: 24px; }
    .category { margin-bottom: 40px; }
    .category h2 {
      color: #00ff00;
      font-size: 20px;
      padding: 12px 0;
      border-bottom: 1px solid #333;
      margin-bottom: 16px;
    }
    .file {
      background: #111;
      border: 1px solid #222;
      border-radius: 8px;
      margin-bottom: 16px;
      overflow: hidden;
    }
    .file-header {
      background: #1a1a1a;
      padding: 10px 16px;
      font-size: 13px;
      color: #00ff00;
      font-family: monospace;
      border-bottom: 1px solid #222;
    }
    .code {
      padding: 16px;
      overflow-x: auto;
      font-family: 'JetBrains Mono', 'Fira Code', monospace;
      font-size: 12px;
      line-height: 1.5;
      color: #ccc;
      white-space: pre;
      tab-size: 2;
    }
    .footer {
      text-align: center;
      padding: 24px;
      color: #444;
      font-size: 12px;
      border-top: 1px solid #222;
    }
  </style>
</head>
<body>
  <div class="header">
    <h1>📚 Net Library Source Code</h1>
    <p>Complete codebase export - ${new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" })}</p>
    <div class="stats">
      <div class="stat">
        <div class="stat-value">${files.length}</div>
        <div class="stat-label">Total Files</div>
      </div>
      <div class="stat">
        <div class="stat-value">${hooks.length}</div>
        <div class="stat-label">Hooks</div>
      </div>
      <div class="stat">
        <div class="stat-value">${components.length}</div>
        <div class="stat-label">Components</div>
      </div>
      <div class="stat">
        <div class="stat-value">${apis.length + share.length}</div>
        <div class="stat-label">API Routes</div>
      </div>
    </div>
  </div>

  <div class="toc">
    <h3>📑 Table of Contents</h3>
    ${hooks.length > 0 ? '<a href="#hooks">🪝 Hooks</a>' : ''}
    ${components.length > 0 ? '<a href="#components">🧩 Components</a>' : ''}
    ${apis.length > 0 ? '<a href="#apis">🔌 APIs</a>' : ''}
    ${share.length > 0 ? '<a href="#share">🔗 Share Routes</a>' : ''}
    ${other.length > 0 ? '<a href="#other">📁 Other</a>' : ''}
  </div>

  <div class="container">
    <div id="hooks">${renderFileSection("Hooks", "🪝", hooks)}</div>
    <div id="components">${renderFileSection("Components", "🧩", components)}</div>
    <div id="apis">${renderFileSection("API Routes", "🔌", apis)}</div>
    <div id="share">${renderFileSection("Share Routes", "🔗", share)}</div>
    <div id="other">${renderFileSection("Other Files", "📁", other)}</div>
  </div>

  <div class="footer">
    <p>Net Library - Built on Net Protocol | Powered by Farcaster</p>
    <p>Generated: ${new Date().toISOString()}</p>
  </div>
</body>
</html>`;
}

export async function GET() {
  try {
    const projectRoot = process.cwd();
    const zip = new JSZip();

    // Discover every file under src/ (except SDK internals) plus static public files.
    // This replaces the old hand-maintained KEY_FILES list so no file is ever silently
    // excluded because someone forgot to add it to the list.
    const srcDir = path.join(projectRoot, "src");
    const discoveredSrcFiles = await collectSourceFiles(srcDir, projectRoot);
    const ALL_FILES = [
      ...discoveredSrcFiles,
      // Public static files (always included, read separately below)
      ...EXTRA_FILES,
    ];

    // Add a README to the zip
    const readme = `# Net Library Source Code

This archive contains the key source files from Net Library.

Generated: ${new Date().toISOString()}

## Quick Start

**Open \`net-library-complete.html\` in any browser** - it's a fully standalone file with all source code embedded. No server required!

## Structure

- \`src/hooks/\` - React hooks for data fetching and state management
- \`src/features/app/components/\` - UI components
- \`src/app/api/\` - Next.js API routes
- \`src/app/share/\` - Share pages with OG metadata
- \`src/lib/\` - Utility functions
- \`src/contexts/\` - React contexts

## Key Files

### Hooks
- \`use-net-upload.ts\` - Core file upload to Net Protocol
- \`use-relay-upload-v2.ts\` - x402 gasless uploads with payment verification & recovery
- \`use-relay-upload.ts\` - x402 gasless uploads (legacy)
- \`use-relay-batch-upload.ts\` - x402 batch uploads
- \`use-upvotes.ts\` - Upvoting system with ETH micropayments
- \`use-stacks.ts\` - Curated stack management
- \`use-discovery-index.ts\` - Content discovery

### Utilities
- \`net-relay.ts\` - x402 relay client for gasless storage transactions

### Components
- \`upload-tab.tsx\` - Main upload interface
- \`book-card.tsx\` - Content card display
- \`upvote-button.tsx\` - Upvote interaction

### APIs
- \`/api/stacks\` - Stack CRUD operations
- \`/api/discovery\` - Content index
- \`/api/upvotes\` - Upvote queries

## Tech Stack

- Next.js 15
- React 19
- TypeScript
- Wagmi v2 / Viem
- Tailwind CSS
- Drizzle ORM

Built on Net Protocol | Powered by Farcaster
`;

    zip.file("README.md", readme);

    // Add all key files to the zip and collect for standalone HTML
    let addedCount = 0;
    const errors: string[] = [];
    const loadedFiles: { path: string; content: string }[] = [];

    for (const filePath of ALL_FILES) {
      try {
        const fullPath = path.join(projectRoot, filePath);
        const rawContent = await fs.readFile(fullPath, "utf-8");
        const content = redactSecrets(rawContent); // Redact sensitive info
        zip.file(filePath, content);
        loadedFiles.push({ path: filePath, content });
        addedCount++;
      } catch {
        errors.push(filePath);
        console.log(`[download] Skipping ${filePath}: not found`);
      }
    }

    // Add a manifest
    const manifest = {
      generated: new Date().toISOString(),
      totalFiles: addedCount,
      skipped: errors,
      files: ALL_FILES.filter(f => !errors.includes(f)),
    };
    zip.file("manifest.json", JSON.stringify(manifest, null, 2));

    // Generate and add standalone HTML file with all code embedded
    const standaloneHtml = generateStandaloneHtml(loadedFiles);
    zip.file("net-library-complete.html", standaloneHtml);

    // Generate the zip as blob
    const zipBlob = await zip.generateAsync({
      type: "blob",
      compression: "DEFLATE",
      compressionOptions: { level: 9 },
    });

    // Return as downloadable file
    return new NextResponse(zipBlob, {
      headers: {
        "Content-Type": "application/zip",
        "Content-Disposition": `attachment; filename="net-library-source-${Date.now()}.zip"`,
      },
    });
  } catch (error) {
    console.error("[download] Error:", error);
    return NextResponse.json(
      { success: false, error: "Failed to generate zip" },
      { status: 500 }
    );
  }
}
src/app/api/source-files/download-json/route.ts
import { NextResponse } from "next/server";
import path from "path";

// Download source files list as JSON file
// GET /api/source-files/download-json

const KEY_FILES = [
  // Core hooks
  "src/hooks/use-net-upload.ts",
  "src/hooks/use-upvotes.ts",
  "src/hooks/use-stacks.ts",
  "src/hooks/use-discovery-index.ts",
  "src/hooks/use-membership.ts",
  "src/hooks/use-membership-status.ts",
  "src/hooks/use-platform-status.ts",
  "src/hooks/use-leaderboard.ts",
  "src/hooks/use-comments.ts",
  "src/hooks/use-user-profile.ts",
  "src/hooks/use-collections.ts",
  "src/hooks/use-trending.ts",
  "src/hooks/use-pdf-cover.ts",
  "src/hooks/use-search.ts",
  "src/hooks/use-batch-upload.ts",
  "src/hooks/use-relay-upload.ts",
  "src/hooks/use-relay-batch-upload.ts",
  "src/hooks/use-cover-upload.ts",

  // Core components
  "src/features/app/components/upvote-button.tsx",
  "src/features/app/components/book-card.tsx",
  "src/features/app/components/stack-detail.tsx",
  "src/features/app/components/pdf-reader.tsx",
  "src/features/app/components/upload-tab.tsx",
  "src/features/app/components/cdn-link-upload.tsx",
  "src/features/app/components/create-stack-modal.tsx",
  "src/features/app/components/share-modal.tsx",
  "src/features/app/components/book-detail.tsx",
  "src/features/app/components/browse-tab.tsx",
  "src/features/app/components/my-library-tab.tsx",
  "src/features/app/components/leaderboard-tab.tsx",
  "src/features/app/components/multimedia-viewer.tsx",
  "src/features/app/components/achievements.tsx",
  "src/features/app/components/enhanced-library-card.tsx",
  "src/features/app/components/text-editor-upload.tsx",
  "src/features/app/components/multi-file-upload.tsx",
  "src/features/app/components/batch-cdn-import.tsx",
  "src/features/app/components/header.tsx",
  "src/features/app/components/member-directory.tsx",
  "src/features/app/components/welcome-popup.tsx",
  "src/features/app/components/user-library-card-modal.tsx",
  "src/features/app/components/cover-backfill.tsx",

  // API routes
  "src/app/api/stacks/route.ts",
  "src/app/api/discovery/route.ts",
  "src/app/api/upvotes/route.ts",
  "src/app/api/membership/route.ts",
  "src/app/api/comments/route.ts",
  "src/app/api/register-cdn-link/route.ts",
  "src/app/api/leaderboard/route.ts",
  "src/app/api/search/route.ts",
  "src/app/api/trending/route.ts",
  "src/app/api/collections/route.ts",
  "src/app/api/reading-progress/route.ts",
  "src/app/api/member-registry/route.ts",
  "src/app/api/active-members/route.ts",
  "src/app/api/backfill-covers/route.ts",
  "src/app/api/upload-cover/route.ts",
  "src/app/api/cover-art/[key]/route.ts",
  "src/app/api/covers/[key]/route.ts",

  // Share image routes
  "src/app/api/share/image/book/route.tsx",
  "src/app/api/share/image/stack/route.tsx",
  "src/app/api/share/image/library-card/route.tsx",
  "src/app/api/share/image/library-card-nft/route.tsx",
  "src/app/api/share/image/achievement/route.tsx",
  "src/app/api/share/image/stats/route.tsx",

  // Share pages
  "src/app/share/book/[key]/page.tsx",
  "src/app/share/book/page.tsx",
  "src/app/share/stack/[id]/page.tsx",
  "src/app/share/library-card/page.tsx",
  "src/app/share/achievement/page.tsx",
  "src/app/share/stats/page.tsx",

  // Types and utilities
  "src/features/app/types.ts",
  "src/lib/net-protocol.ts",
  "src/lib/net-relay.ts",
  "src/lib/relay-feature-flags.ts",
  "src/lib/upload-queue.ts",
  "src/lib/x402-config.ts",
  "src/lib/cover-art-cache.ts",
  "src/lib/cover-url-resolver.ts",

  // Contexts
  "src/contexts/discovery-context.tsx",

  // DB Schema
  "src/db/schema.ts",

  // Resources (public static files)
  "public/netlibrary-eth-landing.html",
];

// Category mapping for organization
const FILE_CATEGORIES: Record<string, string> = {
  "src/hooks": "hooks",
  "src/features/app/components": "components",
  "src/app/api": "api",
  "src/app/share": "share",
  "src/lib": "utilities",
  "src/contexts": "contexts",
  "src/features/app/types.ts": "types",
  "public/": "resources",
};

function getCategory(filePath: string): string {
  for (const [prefix, category] of Object.entries(FILE_CATEGORIES)) {
    if (filePath.startsWith(prefix)) return category;
  }
  return "other";
}

export async function GET() {
  try {
    const files = KEY_FILES.map(filePath => ({
      path: filePath,
      name: path.basename(filePath),
      category: getCategory(filePath),
      extension: path.extname(filePath),
    }));

    // Group by category
    const byCategory: Record<string, typeof files> = {};
    for (const file of files) {
      if (!byCategory[file.category]) {
        byCategory[file.category] = [];
      }
      byCategory[file.category].push(file);
    }

    const data = {
      success: true,
      generated: new Date().toISOString(),
      totalFiles: files.length,
      categories: Object.keys(byCategory),
      files,
      byCategory,
    };

    const jsonString = JSON.stringify(data, null, 2);

    return new NextResponse(jsonString, {
      headers: {
        "Content-Type": "application/json",
        "Content-Disposition": `attachment; filename="net-library-files-${Date.now()}.json"`,
      },
    });
  } catch (error) {
    console.error("[download-json] Error:", error);
    return NextResponse.json(
      { success: false, error: "Failed to generate JSON" },
      { status: 500 }
    );
  }
}
src/app/api/source-files/generate-static/route.ts
import { NextRequest, NextResponse } from "next/server";
import fs from "fs/promises";
import path from "path";
import { redactSecrets } from "@/lib/redact-secrets";

// API to generate a static HTML docs page with all code embedded
// GET /api/source-files/generate-static - Generate and save static docs HTML

// Files to include (same as source-files route)
const KEY_FILES = [
  // Core hooks
  "src/hooks/use-net-upload.ts",
  "src/hooks/use-upvotes.ts",
  "src/hooks/use-stacks.ts",
  "src/hooks/use-discovery-index.ts",
  "src/hooks/use-membership.ts",
  "src/hooks/use-leaderboard.ts",
  "src/hooks/use-comments.ts",
  "src/hooks/use-user-profile.ts",
  "src/hooks/use-collections.ts",
  "src/hooks/use-trending.ts",
  "src/hooks/use-pdf-cover.ts",
  "src/hooks/use-search.ts",

  // Core components
  "src/features/app/components/upvote-button.tsx",
  "src/features/app/components/book-card.tsx",
  "src/features/app/components/stack-detail.tsx",
  "src/features/app/components/pdf-reader.tsx",
  "src/features/app/components/upload-tab.tsx",
  "src/features/app/components/cdn-link-upload.tsx",
  "src/features/app/components/create-stack-modal.tsx",
  "src/features/app/components/share-modal.tsx",
  "src/features/app/components/book-detail.tsx",
  "src/features/app/components/browse-tab.tsx",
  "src/features/app/components/my-library-tab.tsx",
  "src/features/app/components/leaderboard-tab.tsx",

  // API routes
  "src/app/api/stacks/route.ts",
  "src/app/api/discovery/route.ts",
  "src/app/api/upvotes/route.ts",
  "src/app/api/membership/route.ts",
  "src/app/api/comments/route.ts",
  "src/app/api/register-cdn-link/route.ts",
  "src/app/api/leaderboard/route.ts",
  "src/app/api/search/route.ts",
  "src/app/api/trending/route.ts",

  // Share image routes
  "src/app/api/share/image/book/route.tsx",
  "src/app/api/share/image/stack/route.tsx",
  "src/app/api/share/image/library-card/route.tsx",
  "src/app/api/share/image/stats/route.tsx",

  // Share pages
  "src/app/share/book/[key]/page.tsx",
  "src/app/share/stack/[id]/page.tsx",
  "src/app/share/library-card/page.tsx",
  "src/app/share/stats/page.tsx",

  // Types and utilities
  "src/features/app/types.ts",
  "src/lib/net-protocol.ts",

  // Contexts
  "src/contexts/discovery-context.tsx",
];

// Category mapping
const FILE_CATEGORIES: Record<string, string> = {
  "src/hooks": "hooks",
  "src/features/app/components": "components",
  "src/app/api": "api",
  "src/app/share": "share",
  "src/lib": "utilities",
  "src/contexts": "contexts",
  "src/features/app/types.ts": "types",
};

function getCategory(filePath: string): string {
  for (const [prefix, category] of Object.entries(FILE_CATEGORIES)) {
    if (filePath.startsWith(prefix)) return category;
  }
  return "other";
}

function escapeHtml(str: string): string {
  return str
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

export async function GET(_request: NextRequest) {
  try {
    const projectRoot = process.cwd();
    const timestamp = new Date().toISOString();

    // Read all file contents
    const fileContents: Record<string, { content: string; category: string }> = {};

    for (const filePath of KEY_FILES) {
      try {
        const fullPath = path.join(projectRoot, filePath);
        const rawContent = await fs.readFile(fullPath, "utf-8");
        const content = redactSecrets(rawContent); // Redact sensitive info
        fileContents[filePath] = {
          content,
          category: getCategory(filePath),
        };
      } catch {
        console.warn(`[generate-static] Could not read ${filePath}`);
      }
    }

    // Group by category
    const byCategory: Record<string, string[]> = {};
    for (const [filePath, data] of Object.entries(fileContents)) {
      if (!byCategory[data.category]) {
        byCategory[data.category] = [];
      }
      byCategory[data.category].push(filePath);
    }

    // Generate sidebar HTML
    const sidebarHtml = Object.entries(byCategory)
      .map(([category, files]) => `
        <div class="category">
          <h3>${category.charAt(0).toUpperCase() + category.slice(1)}</h3>
          ${files.map(f => `
            <a href="#${f.replace(/[/.]/g, '-')}" class="file-link" data-file="${f}">
              ${path.basename(f)}
            </a>
          `).join('')}
        </div>
      `).join('');

    // Generate code sections HTML
    const codeSectionsHtml = Object.entries(fileContents)
      .map(([filePath, data]) => `
        <section id="${filePath.replace(/[/.]/g, '-')}" class="code-section" data-path="${filePath}" data-category="${data.category}">
          <div class="section-header">
            <h2>${filePath}</h2>
            <button class="copy-btn" onclick="copyCode('${filePath.replace(/[/.]/g, '-')}')">Copy</button>
          </div>
          <pre class="code-block"><code>${escapeHtml(data.content)}</code></pre>
        </section>
      `).join('');

    // Generate the static HTML
    const staticHtml = `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Net Library - Source Code Documentation</title>
  <meta name="description" content="Complete source code documentation for Net Library - A Farcaster mini app for sharing and discovering books">
  <meta name="generated" content="${timestamp}">
  <style>
    :root {
      --bg-dark: #0d1117;
      --bg-card: #161b22;
      --bg-code: #1c2128;
      --text-primary: #e6edf3;
      --text-secondary: #8b949e;
      --accent: #58a6ff;
      --accent-hover: #79b8ff;
      --border: #30363d;
      --success: #3fb950;
    }

    * { box-sizing: border-box; margin: 0; padding: 0; }

    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
      background: var(--bg-dark);
      color: var(--text-primary);
      line-height: 1.6;
    }

    .container {
      display: flex;
      min-height: 100vh;
    }

    /* Sidebar */
    .sidebar {
      width: 280px;
      background: var(--bg-card);
      border-right: 1px solid var(--border);
      padding: 20px;
      position: fixed;
      height: 100vh;
      overflow-y: auto;
    }

    .sidebar h1 {
      font-size: 1.25rem;
      margin-bottom: 8px;
      color: var(--text-primary);
    }

    .sidebar .subtitle {
      font-size: 0.875rem;
      color: var(--text-secondary);
      margin-bottom: 20px;
    }

    .search-box {
      width: 100%;
      padding: 10px 12px;
      background: var(--bg-code);
      border: 1px solid var(--border);
      border-radius: 6px;
      color: var(--text-primary);
      font-size: 0.875rem;
      margin-bottom: 20px;
    }

    .search-box:focus {
      outline: none;
      border-color: var(--accent);
    }

    .category {
      margin-bottom: 20px;
    }

    .category h3 {
      font-size: 0.75rem;
      text-transform: uppercase;
      letter-spacing: 0.05em;
      color: var(--text-secondary);
      margin-bottom: 8px;
      padding-bottom: 4px;
      border-bottom: 1px solid var(--border);
    }

    .file-link {
      display: block;
      padding: 6px 10px;
      color: var(--text-secondary);
      text-decoration: none;
      font-size: 0.875rem;
      border-radius: 4px;
      margin-bottom: 2px;
      transition: all 0.15s ease;
    }

    .file-link:hover {
      background: var(--bg-code);
      color: var(--accent);
    }

    .file-link.active {
      background: var(--accent);
      color: var(--bg-dark);
    }

    /* Main content */
    .main {
      flex: 1;
      margin-left: 280px;
      padding: 40px;
    }

    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30px;
      padding-bottom: 20px;
      border-bottom: 1px solid var(--border);
    }

    .header h1 {
      font-size: 1.5rem;
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }

    .btn {
      padding: 10px 16px;
      border-radius: 6px;
      font-size: 0.875rem;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.15s ease;
      text-decoration: none;
      display: inline-flex;
      align-items: center;
      gap: 6px;
    }

    .btn-primary {
      background: var(--accent);
      color: var(--bg-dark);
      border: none;
    }

    .btn-primary:hover {
      background: var(--accent-hover);
    }

    .stats {
      display: flex;
      gap: 20px;
      margin-bottom: 30px;
    }

    .stat {
      background: var(--bg-card);
      padding: 16px 20px;
      border-radius: 8px;
      border: 1px solid var(--border);
    }

    .stat-value {
      font-size: 1.5rem;
      font-weight: 600;
      color: var(--accent);
    }

    .stat-label {
      font-size: 0.875rem;
      color: var(--text-secondary);
    }

    /* Code sections */
    .code-section {
      background: var(--bg-card);
      border: 1px solid var(--border);
      border-radius: 8px;
      margin-bottom: 24px;
      overflow: hidden;
    }

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 16px;
      background: var(--bg-code);
      border-bottom: 1px solid var(--border);
    }

    .section-header h2 {
      font-size: 0.875rem;
      font-weight: 500;
      color: var(--text-secondary);
      font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
    }

    .copy-btn {
      padding: 6px 12px;
      background: transparent;
      border: 1px solid var(--border);
      border-radius: 4px;
      color: var(--text-secondary);
      font-size: 0.75rem;
      cursor: pointer;
      transition: all 0.15s ease;
    }

    .copy-btn:hover {
      background: var(--bg-dark);
      color: var(--text-primary);
    }

    .copy-btn.copied {
      background: var(--success);
      border-color: var(--success);
      color: white;
    }

    .code-block {
      padding: 16px;
      overflow-x: auto;
      font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace;
      font-size: 0.8125rem;
      line-height: 1.5;
      background: var(--bg-card);
    }

    .code-block code {
      white-space: pre;
    }

    .hidden {
      display: none !important;
    }

    .timestamp {
      font-size: 0.75rem;
      color: var(--text-secondary);
      margin-top: 40px;
      text-align: center;
    }

    /* Responsive */
    @media (max-width: 768px) {
      .sidebar {
        display: none;
      }
      .main {
        margin-left: 0;
        padding: 20px;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <aside class="sidebar">
      <h1>Net Library</h1>
      <p class="subtitle">Source Code Documentation</p>
      <input type="text" class="search-box" placeholder="Search files..." id="searchInput" onkeyup="filterFiles()">
      ${sidebarHtml}
    </aside>

    <main class="main">
      <div class="header">
        <h1>Complete Source Code</h1>
        <div class="header-actions">
          <a href="/api/source-files/download" class="btn btn-primary">
            <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor"><path d="M7.47 10.78a.75.75 0 001.06 0l3.75-3.75a.75.75 0 00-1.06-1.06L8.75 8.44V1.75a.75.75 0 00-1.5 0v6.69L4.78 5.97a.75.75 0 00-1.06 1.06l3.75 3.75zM3.75 13a.75.75 0 000 1.5h8.5a.75.75 0 000-1.5h-8.5z"/></svg>
            Download ZIP
          </a>
        </div>
      </div>

      <div class="stats">
        <div class="stat">
          <div class="stat-value">${Object.keys(fileContents).length}</div>
          <div class="stat-label">Source Files</div>
        </div>
        <div class="stat">
          <div class="stat-value">${Object.keys(byCategory).length}</div>
          <div class="stat-label">Categories</div>
        </div>
        <div class="stat">
          <div class="stat-value">${Math.round(Object.values(fileContents).reduce((acc, f) => acc + f.content.length, 0) / 1024)}KB</div>
          <div class="stat-label">Total Code</div>
        </div>
      </div>

      ${codeSectionsHtml}

      <p class="timestamp">Generated: ${timestamp}</p>
    </main>
  </div>

  <script>
    function filterFiles() {
      const query = document.getElementById('searchInput').value.toLowerCase();
      const sections = document.querySelectorAll('.code-section');
      const links = document.querySelectorAll('.file-link');

      sections.forEach(section => {
        const path = section.dataset.path.toLowerCase();
        const content = section.querySelector('code').textContent.toLowerCase();
        const matches = path.includes(query) || content.includes(query);
        section.classList.toggle('hidden', !matches);
      });

      links.forEach(link => {
        const file = link.dataset.file.toLowerCase();
        link.classList.toggle('hidden', !file.includes(query));
      });
    }

    function copyCode(sectionId) {
      const section = document.getElementById(sectionId);
      const code = section.querySelector('code').textContent;
      const btn = section.querySelector('.copy-btn');

      navigator.clipboard.writeText(code).then(() => {
        btn.textContent = 'Copied!';
        btn.classList.add('copied');
        setTimeout(() => {
          btn.textContent = 'Copy';
          btn.classList.remove('copied');
        }, 2000);
      });
    }

    // Highlight active file on scroll
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const path = entry.target.dataset.path;
          document.querySelectorAll('.file-link').forEach(link => {
            link.classList.toggle('active', link.dataset.file === path);
          });
        }
      });
    }, { threshold: 0.3 });

    document.querySelectorAll('.code-section').forEach(section => {
      observer.observe(section);
    });
  </script>
</body>
</html>`;

    // Write to public directory
    const outputPath = path.join(projectRoot, "public", "net-library-docs-static.html");
    await fs.writeFile(outputPath, staticHtml, "utf-8");

    return NextResponse.json({
      success: true,
      message: "Static docs generated successfully",
      outputPath: "/net-library-docs-static.html",
      stats: {
        filesIncluded: Object.keys(fileContents).length,
        categories: Object.keys(byCategory).length,
        totalSize: `${Math.round(staticHtml.length / 1024)}KB`,
        generatedAt: timestamp,
      },
    });
  } catch (error) {
    console.error("[generate-static] Error:", error);
    return NextResponse.json(
      { success: false, error: "Failed to generate static docs" },
      { status: 500 }
    );
  }
}
src/app/api/source-files/route.ts
import { NextRequest, NextResponse } from "next/server";
import fs from "fs/promises";
import path from "path";
import { redactSecrets } from "@/lib/redact-secrets";

// API to serve source files for documentation
// GET /api/source-files - List all source files
// GET /api/source-files?file=path/to/file.ts - Get specific file content

// Define the source directories we want to expose
const _SOURCE_DIRS = [
  "src/hooks",
  "src/features/app/components",
  "src/app/api",
  "src/lib",
  "src/contexts",
  "src/features/app",
];

// Files to explicitly include
const KEY_FILES = [
  // Core hooks
  "src/hooks/use-net-upload.ts",
  "src/hooks/use-upvotes.ts",
  "src/hooks/use-stacks.ts",
  "src/hooks/use-discovery-index.ts",
  "src/hooks/use-membership.ts",
  "src/hooks/use-membership-status.ts",
  "src/hooks/use-platform-status.ts",
  "src/hooks/use-leaderboard.ts",
  "src/hooks/use-comments.ts",
  "src/hooks/use-user-profile.ts",
  "src/hooks/use-collections.ts",
  "src/hooks/use-trending.ts",
  "src/hooks/use-pdf-cover.ts",
  "src/hooks/use-search.ts",
  "src/hooks/use-batch-upload.ts",
  "src/hooks/use-relay-upload-v2.ts",
  "src/hooks/use-relay-batch-upload-v2.ts",
  "src/hooks/use-cover-upload.ts",

  // Core components
  "src/features/app/components/upvote-button.tsx",
  "src/features/app/components/book-card.tsx",
  "src/features/app/components/stack-detail.tsx",
  "src/features/app/components/pdf-reader.tsx",
  "src/features/app/components/upload-tab.tsx",
  "src/features/app/components/cdn-link-upload.tsx",
  "src/features/app/components/create-stack-modal.tsx",
  "src/features/app/components/share-modal.tsx",
  "src/features/app/components/book-detail.tsx",
  "src/features/app/components/browse-tab.tsx",
  "src/features/app/components/my-library-tab.tsx",
  "src/features/app/components/leaderboard-tab.tsx",
  "src/features/app/components/multimedia-viewer.tsx",
  "src/features/app/components/achievements.tsx",
  "src/features/app/components/enhanced-library-card.tsx",
  "src/features/app/components/text-editor-upload.tsx",
  "src/features/app/components/multi-file-upload.tsx",
  "src/features/app/components/batch-cdn-import.tsx",
  "src/features/app/components/header.tsx",
  "src/features/app/components/member-directory.tsx",
  "src/features/app/components/welcome-popup.tsx",
  "src/features/app/components/user-library-card-modal.tsx",
  "src/features/app/components/cover-backfill.tsx",

  // Image Editor (Create Something)
  "src/features/app/components/image-editor/image-editor.tsx",
  "src/features/app/components/image-editor/types.ts",
  "src/features/app/components/image-editor/use-canvas-history.ts",
  "src/features/app/components/image-editor/meme-templates.ts",
  "src/features/app/components/create-image-upload.tsx",

  // Embed Viewer
  "src/features/app/components/embed-viewer.tsx",
  "src/features/app/components/member-resources-section.tsx",

  // Grids feature
  "src/hooks/use-grids.ts",
  "src/hooks/use-grid-archive.ts",
  "src/hooks/use-grid-upvotes.ts",
  "src/features/app/components/grids-tab.tsx",
  "src/features/app/components/grid-detail.tsx",
  "src/features/app/components/grid-archive-modal.tsx",
  "src/features/app/components/create-grid-modal.tsx",
  "src/features/app/components/grid-share-modal.tsx",
  "src/app/api/grids/route.ts",
  "src/app/api/grid-cells/route.ts",
  "src/app/api/grid-archives/route.ts",

  // Social Receipts feature
  "src/features/app/components/social-receipt-upload.tsx",
  "src/features/app/components/social-receipt-share-modal.tsx",
  "src/features/app/components/media-type-filter.tsx",
  "src/app/api/social/fetch/route.ts",
  "src/app/share/social/[key]/page.tsx",

  // Filesystem Stacks feature
  "src/features/app/components/folder-upload-modal.tsx",
  "src/features/app/components/zip-import-modal.tsx",
  "src/features/app/components/github-import-modal.tsx",
  "src/features/app/components/folder-tree-view.tsx",
  "src/features/app/types-filesystem.ts",
  "src/app/api/v1/github-tree/route.ts",

  // API routes
  "src/app/api/stacks/route.ts",
  "src/app/api/discovery/route.ts",
  "src/app/api/upvotes/route.ts",
  "src/app/api/membership/route.ts",
  "src/app/api/comments/route.ts",
  "src/app/api/register-cdn-link/route.ts",
  "src/app/api/leaderboard/route.ts",
  "src/app/api/search/route.ts",
  "src/app/api/trending/route.ts",
  "src/app/api/collections/route.ts",
  "src/app/api/reading-progress/route.ts",
  "src/app/api/member-registry/route.ts",
  "src/app/api/active-members/route.ts",
  "src/app/api/stats/route.ts",
  "src/app/api/backfill-covers/route.ts",
  "src/app/api/upload-cover/route.ts",
  "src/app/api/cover-art/[key]/route.ts",
  "src/app/api/covers/[key]/route.ts",

  // Share image routes
  "src/app/api/share/image/book/route.tsx",
  "src/app/api/share/image/stack/route.tsx",
  "src/app/api/share/image/library-card/route.tsx",
  "src/app/api/share/image/library-card-nft/route.tsx",
  "src/app/api/share/image/achievement/route.tsx",
  "src/app/api/share/image/stats/route.tsx",
  "src/app/api/share/image/grid/route.tsx",

  // Share pages
  "src/app/share/book/[key]/page.tsx",
  "src/app/share/book/page.tsx",
  "src/app/share/stack/[id]/page.tsx",
  "src/app/share/library-card/page.tsx",
  "src/app/share/achievement/page.tsx",
  "src/app/share/stats/page.tsx",
  "src/app/share/grid/[gridId]/page.tsx",

  // Embeddable Widgets
  "src/app/embed/stats/stats-widget.tsx",
  "src/app/embed/feed/feed-widget.tsx",
  "src/app/embed/item/[contentKey]/item-widget.tsx",
  "src/app/embed/user/[address]/user-widget.tsx",
  "src/app/embed/stack/[stackId]/stack-widget.tsx",
  "src/app/embed/card/[address]/library-card-widget.tsx",
  "src/app/embed/components/embed-footer.tsx",

  // Types and utilities
  "src/features/app/types.ts",
  "src/lib/net-protocol.ts",
  "src/lib/net-relay.ts",
  "src/lib/relay-feature-flags.ts",
  "src/lib/relay-upload-utils.ts",
  "src/lib/upload-queue.ts",
  "src/lib/x402-config.ts",
  "src/lib/cover-art-cache.ts",
  "src/lib/cover-url-resolver.ts",

  // Contexts
  "src/contexts/discovery-context.tsx",

  // DB Schema
  "src/db/schema.ts",

  // Resources (public static files)
  "public/netlibrary-eth-landing.html",

  // Agent API v2.0 routes
  "src/app/api/v1/agents/route.ts",
  "src/app/api/v1/agents/me/route.ts",
  "src/app/api/v1/agents/tasks/route.ts",
  "src/app/api/v1/agents/membership/route.ts",
  "src/app/api/v1/agents/verify-8004/route.ts",
  "src/app/api/v1/library/write/route.ts",
  "src/app/api/v1/library/upload/route.ts",
  "src/app/api/v1/archive/route.ts",
  "src/app/api/v1/stacks/write/route.ts",
  "src/app/api/v1/capabilities/route.ts",
  "src/app/api/v1/webhooks/farcaster/route.ts",
  "src/app/api/v1/embeds/card/[address]/route.ts",
  "src/app/api/v1/embeds/grid/[gridId]/route.ts",
  "src/app/api/v1/embeds/user/[address]/route.ts",
  "src/lib/agent-auth.ts",

  // Documentation (markdown files)
  "docs/FEATURE-TOPOLOGY.md",
  "docs/UPLOAD-SYSTEM.md",
  "docs/REQUIREMENTS.md",
  "docs/VIBE-SPEC.md",
  "docs/WEB-PLATFORM-SPEC.md",
  "docs/GRIDS-SPEC.md",
  "docs/NET-RELAY-X402-INTEGRATION.md",
  "docs/CHANGELOG-PROTOCOL.md",
  "docs/DOC-UPDATE-PROTOCOL.md",
  "docs/KNOWN-ISSUES.md",
  "docs/NET-LIBRARY-V2-SPEC.md",
  "docs/SDK-DRAFT.md",
];

// Category mapping for organization
const FILE_CATEGORIES: Record<string, string> = {
  "src/hooks": "hooks",
  "src/features/app/components": "components",
  "src/app/api": "api",
  "src/app/share": "share",
  "src/app/embed": "embed",
  "src/lib": "utilities",
  "src/contexts": "contexts",
  "src/features/app/types.ts": "types",
  "public/": "resources",
  "docs/": "markdown",
};

function getCategory(filePath: string): string {
  for (const [prefix, category] of Object.entries(FILE_CATEGORIES)) {
    if (filePath.startsWith(prefix)) return category;
  }
  return "other";
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const requestedFile = searchParams.get("file");
    const category = searchParams.get("category");

    const projectRoot = process.cwd();

    // If specific file requested, return its content
    if (requestedFile) {
      // Security: Only allow files from our whitelist
      if (!KEY_FILES.includes(requestedFile)) {
        return NextResponse.json(
          { success: false, error: "File not in allowed list" },
          { status: 403 }
        );
      }

      const filePath = path.join(projectRoot, requestedFile);

      try {
        const rawContent = await fs.readFile(filePath, "utf-8");
        const content = redactSecrets(rawContent); // Redact sensitive info
        const stats = await fs.stat(filePath);

        return NextResponse.json({
          success: true,
          file: {
            path: requestedFile,
            name: path.basename(requestedFile),
            content,
            size: stats.size,
            category: getCategory(requestedFile),
            extension: path.extname(requestedFile),
            lastModified: stats.mtime.toISOString(),
          },
        });
      } catch {
        return NextResponse.json(
          { success: false, error: "File not found" },
          { status: 404 }
        );
      }
    }

    // Return list of all available files (optionally filtered by category)
    const files = KEY_FILES
      .filter(f => !category || getCategory(f) === category)
      .map(filePath => ({
        path: filePath,
        name: path.basename(filePath),
        category: getCategory(filePath),
        extension: path.extname(filePath),
      }));

    // Group by category
    const byCategory: Record<string, typeof files> = {};
    for (const file of files) {
      if (!byCategory[file.category]) {
        byCategory[file.category] = [];
      }
      byCategory[file.category].push(file);
    }

    return NextResponse.json({
      success: true,
      totalFiles: files.length,
      categories: Object.keys(byCategory),
      files,
      byCategory,
    });
  } catch (error) {
    console.error("[source-files] Error:", error);
    return NextResponse.json(
      { success: false, error: "Failed to fetch source files" },
      { status: 500 }
    );
  }
}
src/app/api/stacks/route.ts
/* eslint-disable @neynar/no-process-env */
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { isMember, isMemberByFid, type MemberRegistry, type DiscoveryEntry } from "@/lib/net-protocol";
import { verifyUsdcPayment, markTxUsed } from "@/lib/agent-auth";
import { keccak256, encodePacked } from "viem";
import type { Stack, StackItem } from "@/features/app/types";

// Discovery index key for cover lookups
const DISCOVERY_INDEX_KEY = "discovery-index";

// KV Keys
const STACKS_REGISTRY_KEY = "stacks-registry"; // List of all stack IDs
const STACK_PREFIX = "stack:"; // stack:{stackId} -> Stack metadata
const STACK_ITEMS_PREFIX = "stack-items:"; // stack-items:{stackId} -> StackItem[]
const USER_STACKS_PREFIX = "user-stacks:"; // user-stacks:{address} -> stackId[]
const ITEM_STACKS_PREFIX = "item-stacks:"; // item-stacks:{contentKey} -> stackId[]
const MEMBER_REGISTRY_KEY = "member-registry"; // Member registry for membership check
const ITEM_PREVIOUS_STACKS_PREFIX = "item-prev-stacks:"; // item-prev-stacks:{contentKey} -> { stackIds: string[], hiddenAt: number }

// Constants
const DEFAULT_ITEM_LIMIT = 20;
const STACK_CREATION_COST_NON_MEMBER = 5; // $5 USDC
const STACK_UNLOCK_COST = 5; // $5 USDC

// Helper: Generate unique stack ID
function generateStackId(owner: string, name: string): string {
  const hash = keccak256(
    encodePacked(
      ["address", "string", "uint256"],
      [owner as `0x${string}`, name, BigInt(Date.now())]
    )
  );
  return hash.slice(0, 18); // Short ID for URLs
}

// Helper: Get KV value
async function getKV<T>(key: string): Promise<T | null> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, key)).limit(1);
    if (!result[0]?.value) return null;
    return JSON.parse(result[0].value) as T;
  } catch (error) {
    console.error(`[getKV] Error fetching ${key}:`, error);
    return null;
  }
}

// Helper: Set KV value
async function setKV(key: string, value: unknown): Promise<boolean> {
  try {
    const jsonValue = JSON.stringify(value);
    await db.insert(kv).values({ key, value: jsonValue }).onConflictDoUpdate({
      target: kv.key,
      set: { value: jsonValue },
    });
    return true;
  } catch (error) {
    console.error(`[setKV] Error storing ${key}:`, error);
    return false;
  }
}

// Helper: Fetch member registry
async function fetchMemberRegistry(): Promise<MemberRegistry> {
  const emptyRegistry: MemberRegistry = {
    members: [],
    nextMemberId: 1,
    lastUpdated: Date.now(),
  };

  try {
    const result = await db.select().from(kv).where(eq(kv.key, MEMBER_REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) return emptyRegistry;
    return JSON.parse(result[0].value) as MemberRegistry;
  } catch (error) {
    console.error("[fetchMemberRegistry] Error:", error);
    return emptyRegistry;
  }
}

// Helper: Check if user is a member (by address or FID)
async function checkMembership(address: string, fid?: number): Promise<boolean> {
  const registry = await fetchMemberRegistry();
  const memberByAddress = isMember(registry, address);
  if (memberByAddress) return true;
  if (fid) {
    const memberByFidResult = isMemberByFid(registry, fid);
    if (memberByFidResult) return true;
  }
  return false;
}

// Helper: Convert IPFS/Arweave URLs to gateway URLs
function toGatewayUrl(url: string): string {
  if (!url) return "";
  if (url.startsWith("ipfs://")) return `https://ipfs.io/ipfs/${url.slice(7)}`;
  if (url.startsWith("ar://")) return `https://arweave.net/${url.slice(5)}`;
  return url;
}

// Helper: Get best cover URL - prefers coverUrl, falls back to cdnUrl for visual content
function getEffectiveCoverUrl(entry: { coverUrl?: string; cdnUrl?: string; mediaType?: string }): string | undefined {
  // If explicit cover art is set, use it (converted to gateway URL if needed)
  if (entry.coverUrl) {
    return toGatewayUrl(entry.coverUrl);
  }

  // For image/video content, cdnUrl IS the visual content - use it as thumbnail
  if (entry.cdnUrl && entry.mediaType && ["image", "video"].includes(entry.mediaType)) {
    return entry.cdnUrl;
  }

  // No cover available
  return undefined;
}

// Track which stacks have already had their itemCount synced this process lifetime.
// This prevents a burst of N concurrent KV writes the first time a user loads their
// stacks list after deployment.  The Set is per-instance (server process), so counts
// are re-checked after a cold start but not on every hot request.
const syncedItemCountKeys = new Set<string>();

// Helper: Enrich stacks with preview covers from discovery index
// Also filters out hidden items and returns accurate visible item counts
async function enrichStacksWithPreviews(stacks: Stack[]): Promise<(Stack & { visibleItemCount: number })[]> {
  if (stacks.length === 0) return [];

  // Fetch discovery index once
  const discoveryIndex = await getKV<DiscoveryEntry[]>(DISCOVERY_INDEX_KEY) || [];
  // Only include non-hidden entries in the map
  const visibleEntryMap = new Map(
    discoveryIndex
      .filter(e => !e.hidden)
      .map(e => [e.contentKey, e])
  );

  // For each stack, get preview covers and calculate visible item count
  const enrichedStacks: (Stack & { visibleItemCount: number })[] = [];

  for (const stack of stacks) {
    const items = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${stack.id}`) || [];

    // Filter to only visible items (exist in discovery and not hidden)
    const visibleItems = items.filter(item => visibleEntryMap.has(item.contentKey));
    const previewCovers: string[] = [];

    for (const item of visibleItems.slice(0, 5)) {
      const entry = visibleEntryMap.get(item.contentKey);
      if (entry) {
        // Use best available cover URL (avoids broken /api/covers/ URLs)
        const coverUrl = getEffectiveCoverUrl(entry);
        if (coverUrl) {
          previewCovers.push(coverUrl);
        }
      }
    }

    // Compute the authoritative item count without mutating the input object yet.
    const correctedCount = visibleItems.length;

    // Lazily persist the correction when itemCount has drifted.
    // Gate on syncedItemCountKeys so this only fires once per stack per process lifetime.
    if (stack.itemCount !== correctedCount && !syncedItemCountKeys.has(stack.id)) {
      syncedItemCountKeys.add(stack.id);
      // Use a shallow copy for the KV write so the caller-owned stack object is never mutated.
      // The spread below also uses correctedCount directly, keeping the response correct regardless.
      const updatedStack = { ...stack, itemCount: correctedCount };
      setKV(`${STACK_PREFIX}${updatedStack.id}`, updatedStack).catch(err => {
        console.error("[enrichStacksWithPreviews] Failed to sync itemCount:", err);
      });
    }

    enrichedStacks.push({
      ...stack,
      itemCount: correctedCount,    // always use the fresh count in the response
      previewCovers,
      visibleItemCount: correctedCount,
    });
  }

  return enrichedStacks;
}

// GET: Fetch stacks (all, by owner, or single stack)
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const stackId = searchParams.get("id");
  const owner = searchParams.get("owner");
  const contentKey = searchParams.get("contentKey"); // Get stacks containing this item
  const popular = searchParams.get("popular"); // Get popular stacks
  const viewer = searchParams.get("viewer"); // Current viewer's address (for privacy filtering)

  try {
    // Single stack by ID
    if (stackId) {
      const stack = await getKV<Stack>(`${STACK_PREFIX}${stackId}`);
      if (!stack) {
        return NextResponse.json({ success: false, error: "Stack not found" }, { status: 404 });
      }

      // Check if private stack is being accessed by non-owner
      if (stack.isPrivate && (!viewer || viewer.toLowerCase() !== stack.owner.toLowerCase())) {
        return NextResponse.json({
          success: false,
          error: "This stack is private. The owner has chosen to keep this content hidden from the public.",
          isPrivate: true,
        }, { status: 403 });
      }

      // Get items
      const allItems = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${stackId}`) || [];

      // Filter out hidden items - items that failed to upload or were manually hidden
      // should not appear in stacks even though they're stored in the stack-items array
      const discoveryIndex = await getKV<DiscoveryEntry[]>(DISCOVERY_INDEX_KEY) || [];
      const visibleContentKeys = new Set(
        discoveryIndex
          .filter(entry => !entry.hidden)
          .map(entry => entry.contentKey)
      );
      const items = allItems.filter(item => visibleContentKeys.has(item.contentKey));

      // Merge any mutations into a single setKV call to avoid a race where two
      // concurrent fire-and-forget writes overwrite each other on the same object.
      let needsWrite = false;

      if (viewer && viewer.toLowerCase() !== stack.owner.toLowerCase()) {
        stack.views = (stack.views || 0) + 1;
        needsWrite = true;
      }

      if (stack.itemCount !== items.length) {
        stack.itemCount = items.length;
        needsWrite = true;
      }

      if (needsWrite) {
        setKV(`${STACK_PREFIX}${stackId}`, stack).catch(err => {
          console.error("[GET /api/stacks] Failed to persist stack update:", err);
        });
      }

      return NextResponse.json({
        success: true,
        stack,
        items,
        visibleItemCount: items.length,
      });
    }

    // Stacks by owner - includes private stacks if viewer is the owner
    if (owner) {
      const userStackIds = await getKV<string[]>(`${USER_STACKS_PREFIX}${owner.toLowerCase()}`) || [];
      const stacks: Stack[] = [];
      const isOwnProfile = viewer && viewer.toLowerCase() === owner.toLowerCase();

      for (const id of userStackIds) {
        const stack = await getKV<Stack>(`${STACK_PREFIX}${id}`);
        // Include stack if: not private, OR viewer is the owner
        if (stack && (!stack.isPrivate || isOwnProfile)) {
          stacks.push(stack);
        }
      }

      // Enrich with preview covers
      const enrichedStacks = await enrichStacksWithPreviews(stacks);

      return NextResponse.json({
        success: true,
        stacks: enrichedStacks,
      });
    }

    // Stacks containing a specific item - filter out private stacks unless viewer is owner
    if (contentKey) {
      const stackIds = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${contentKey}`) || [];
      const stacks: Stack[] = [];

      for (const id of stackIds) {
        const stack = await getKV<Stack>(`${STACK_PREFIX}${id}`);
        // Include stack if: not private, OR viewer is the owner
        if (stack && (!stack.isPrivate || (viewer && viewer.toLowerCase() === stack.owner.toLowerCase()))) {
          stacks.push(stack);
        }
      }

      // Enrich with preview covers
      const enrichedStacks = await enrichStacksWithPreviews(stacks);

      return NextResponse.json({
        success: true,
        stacks: enrichedStacks,
      });
    }

    // Popular stacks or sorted stacks - filter out private stacks
    const sortBy = searchParams.get("sortBy"); // upvotes | recent | items
    const page = parseInt(searchParams.get("page") || "1", 10);
    const pageSize = parseInt(searchParams.get("pageSize") || "10", 10);

    if (popular === "true" || sortBy) {
      const allStackIds = await getKV<string[]>(STACKS_REGISTRY_KEY) || [];
      const stacks: Stack[] = [];

      for (const id of allStackIds) {
        const stack = await getKV<Stack>(`${STACK_PREFIX}${id}`);
        // Filter out private stacks from public feeds
        if (stack && !stack.isPrivate) stacks.push(stack);
      }

      // Sort based on sortBy parameter (default to upvotes for backward compatibility)
      const sortOption = sortBy || "upvotes";
      switch (sortOption) {
        case "items":
          stacks.sort((a, b) => (b.itemCount || 0) - (a.itemCount || 0));
          break;
        case "recent":
          stacks.sort((a, b) => b.createdAt - a.createdAt);
          break;
        case "upvotes":
        default:
          // Sort by upvotes descending (highest first)
          // Use Number() to ensure proper numeric comparison
          stacks.sort((a, b) => Number(b.upvotes || 0) - Number(a.upvotes || 0));
          break;
      }

      // Support both legacy limit and new pagination
      const limit = parseInt(searchParams.get("limit") || "0", 10);
      if (limit > 0) {
        // Legacy behavior - enrich with preview covers
        const enrichedStacks = await enrichStacksWithPreviews(stacks.slice(0, limit));
        return NextResponse.json({
          success: true,
          stacks: enrichedStacks,
          total: stacks.length,
        });
      }

      // New pagination
      const startIndex = (page - 1) * pageSize;
      const paginatedStacks = stacks.slice(startIndex, startIndex + pageSize);

      // Enrich with preview covers
      const enrichedStacks = await enrichStacksWithPreviews(paginatedStacks);

      return NextResponse.json({
        success: true,
        stacks: enrichedStacks,
        total: stacks.length,
        page,
        pageSize,
        totalPages: Math.ceil(stacks.length / pageSize),
      });
    }

    // All stacks (recent first) - filter out private stacks, with pagination
    const allStackIds = await getKV<string[]>(STACKS_REGISTRY_KEY) || [];
    const stacks: Stack[] = [];

    for (const id of allStackIds) {
      const stack = await getKV<Stack>(`${STACK_PREFIX}${id}`);
      // Filter out private stacks from public feeds
      if (stack && !stack.isPrivate) stacks.push(stack);
    }

    // Sort by creation date descending
    stacks.sort((a, b) => b.createdAt - a.createdAt);

    // Apply pagination
    const startIndex = (page - 1) * pageSize;
    const paginatedStacks = stacks.slice(startIndex, startIndex + pageSize);

    // Enrich with preview covers
    const enrichedStacks = await enrichStacksWithPreviews(paginatedStacks);

    return NextResponse.json({
      success: true,
      stacks: enrichedStacks,
      total: stacks.length,
      page,
      pageSize,
      totalPages: Math.ceil(stacks.length / pageSize),
    });
  } catch (error) {
    console.error("[GET /api/stacks] Error:", error);
    return NextResponse.json({ success: false, error: "Internal error" }, { status: 500 });
  }
}

// POST: Create a new stack
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { name, description, owner, ownerFid, ownerUsername, ownerPfpUrl, txHash, isPrivate } = body;

    if (!name || !owner) {
      return NextResponse.json(
        { success: false, error: "Name and owner are required" },
        { status: 400 }
      );
    }

    // Check membership
    const memberStatus = await checkMembership(owner, ownerFid);

    // Non-members must provide payment txHash
    if (!memberStatus && !txHash) {
      return NextResponse.json(
        {
          success: false,
          error: "Payment required",
          requiresPayment: true,
          cost: STACK_CREATION_COST_NON_MEMBER,
        },
        { status: 402 }
      );
    }

    // Verify USDC payment for non-members
    if (!memberStatus && txHash) {
      const paymentResult = await verifyUsdcPayment(txHash, STACK_CREATION_COST_NON_MEMBER, owner);
      if (!paymentResult.valid) {
        return NextResponse.json(
          {
            success: false,
            error: paymentResult.error || "Payment verification failed",
            requiresPayment: true,
            cost: STACK_CREATION_COST_NON_MEMBER,
          },
          { status: 402 }
        );
      }
      // Mark tx as used to prevent replay
      await markTxUsed(txHash, "stack-creation");
    }

    // Generate stack ID
    const stackId = generateStackId(owner, name);

    // Create stack object
    const stack: Stack = {
      id: stackId,
      name: name.trim(),
      description: description?.trim(),
      owner: owner.toLowerCase(),
      ownerFid,
      ownerUsername,
      ownerPfpUrl,
      createdAt: Date.now(),
      creationTxHash: memberStatus ? undefined : txHash,
      unlocked: false,
      itemCount: 0,
      isPrivate: isPrivate || false,
    };

    // Store stack
    await setKV(`${STACK_PREFIX}${stackId}`, stack);

    // Initialize empty items array
    await setKV(`${STACK_ITEMS_PREFIX}${stackId}`, []);

    // Add to user's stacks
    const userStacks = await getKV<string[]>(`${USER_STACKS_PREFIX}${owner.toLowerCase()}`) || [];
    userStacks.push(stackId);
    await setKV(`${USER_STACKS_PREFIX}${owner.toLowerCase()}`, userStacks);

    // Add to global registry
    const allStacks = await getKV<string[]>(STACKS_REGISTRY_KEY) || [];
    allStacks.push(stackId);
    await setKV(STACKS_REGISTRY_KEY, allStacks);

    return NextResponse.json({
      success: true,
      stack,
    });
  } catch (error) {
    console.error("[POST /api/stacks] Error:", error);
    return NextResponse.json({ success: false, error: "Internal error" }, { status: 500 });
  }
}

// PUT: Update stack (add/remove items, unlock, update metadata, reorder items)
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    const { stackId, action, owner, ownerFid, contentKey, txHash, name, description, itemOrder } = body;

    if (!stackId || !owner) {
      return NextResponse.json(
        { success: false, error: "Stack ID and owner are required" },
        { status: 400 }
      );
    }

    // Fetch stack
    const stack = await getKV<Stack>(`${STACK_PREFIX}${stackId}`);
    if (!stack) {
      return NextResponse.json({ success: false, error: "Stack not found" }, { status: 404 });
    }

    // Verify ownership (check address and FID for cross-platform)
    const isOwner =
      stack.owner.toLowerCase() === owner.toLowerCase() ||
      (ownerFid && stack.ownerFid === ownerFid);

    if (!isOwner) {
      return NextResponse.json({ success: false, error: "Not authorized" }, { status: 403 });
    }

    // Handle different actions
    switch (action) {
      case "add-item": {
        if (!contentKey) {
          return NextResponse.json({ success: false, error: "Content key required" }, { status: 400 });
        }

        // Check item limit
        if (!stack.unlocked && stack.itemCount >= DEFAULT_ITEM_LIMIT) {
          return NextResponse.json(
            {
              success: false,
              error: "Stack is full",
              requiresUnlock: true,
              cost: STACK_UNLOCK_COST,
            },
            { status: 402 }
          );
        }

        // Get current items
        const items = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${stackId}`) || [];

        // Check if item already in stack
        if (items.some(item => item.contentKey === contentKey)) {
          return NextResponse.json({ success: false, error: "Item already in stack" }, { status: 400 });
        }

        // Add item
        const newItem: StackItem = {
          contentKey,
          addedAt: Date.now(),
          addedBy: owner.toLowerCase(),
        };
        items.push(newItem);
        await setKV(`${STACK_ITEMS_PREFIX}${stackId}`, items);

        // Update item count
        stack.itemCount = items.length;
        await setKV(`${STACK_PREFIX}${stackId}`, stack);

        // Update reverse index
        const itemStacks = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${contentKey}`) || [];
        if (!itemStacks.includes(stackId)) {
          itemStacks.push(stackId);
          await setKV(`${ITEM_STACKS_PREFIX}${contentKey}`, itemStacks);
        }

        // Track removed stacks for potential restore
        const removedFromStacks: Array<{ id: string; name: string }> = [];

        // If adding to a private stack, this is EXCLUSIVE - remove from all other stacks and hide
        if (stack.isPrivate) {
          // First, find all OTHER stacks this item is in and remove it from them
          const otherStackIds = itemStacks.filter(id => id !== stackId);
          for (const otherStackId of otherStackIds) {
            const otherStack = await getKV<Stack>(`${STACK_PREFIX}${otherStackId}`);
            if (otherStack) {
              // Track the stack name for the restore prompt
              removedFromStacks.push({ id: otherStackId, name: otherStack.name });

              // Remove item from other stack
              const otherItems = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${otherStackId}`) || [];
              const filteredOtherItems = otherItems.filter(item => item.contentKey !== contentKey);
              await setKV(`${STACK_ITEMS_PREFIX}${otherStackId}`, filteredOtherItems);

              // Update other stack's item count
              otherStack.itemCount = filteredOtherItems.length;
              await setKV(`${STACK_PREFIX}${otherStackId}`, otherStack);
            }
          }

          // Update reverse index to ONLY contain this private stack
          await setKV(`${ITEM_STACKS_PREFIX}${contentKey}`, [stackId]);

          // Save previous stacks info for potential restore
          if (removedFromStacks.length > 0) {
            await setKV(`${ITEM_PREVIOUS_STACKS_PREFIX}${contentKey}`, {
              stackIds: removedFromStacks.map(s => s.id),
              stackNames: removedFromStacks.map(s => s.name),
              hiddenAt: Date.now(),
            });
          }

          // Hide the item from public feeds
          try {
            const hideResponse = await fetch(`${process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3021"}/api/discovery`, {
              method: "PUT",
              headers: { "Content-Type": "application/json" },
              body: JSON.stringify({
                contentKey,
                operator: owner,
                hidden: true,
              }),
            });
            if (!hideResponse.ok) {
              console.warn("[add-item] Failed to hide item in private stack:", await hideResponse.text());
            }
          } catch (err) {
            console.warn("[add-item] Error hiding item:", err);
          }
        }

        return NextResponse.json({
          success: true,
          stack,
          itemCount: items.length,
          itemHidden: stack.isPrivate,
          removedFromStacks: removedFromStacks.length > 0 ? removedFromStacks : undefined,
        });
      }

      case "add-fs-item": {
        // Add item with filesystem metadata (for filesystem mode stacks)
        const { path, fileName, fileSize, mimeType, isDirectory, parentPath } = body;

        if (!contentKey || !path) {
          return NextResponse.json({ success: false, error: "Missing contentKey or path" }, { status: 400 });
        }

        // Sanitize path - ensure it starts with / and has no double slashes
        const cleanPath = ("/" + path.replace(/^\/+/, "")).replace(/\/\//g, "/");

        // Get current items
        const items = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${stackId}`) || [];

        // Check if already exists
        if (items.some(item => item.contentKey === contentKey)) {
          return NextResponse.json({ success: false, error: "Item already in stack" }, { status: 409 });
        }

        // Check limits (same as add-item)
        if (!stack.unlocked && items.length >= DEFAULT_ITEM_LIMIT) {
          return NextResponse.json({
            success: false,
            error: "Stack item limit reached",
            requiresUnlock: true,
            cost: STACK_UNLOCK_COST,
          }, { status: 403 });
        }

        // Add item with filesystem metadata
        const newItem: StackItem = {
          contentKey,
          addedAt: Date.now(),
          addedBy: owner.toLowerCase(),
          path: cleanPath,
          fileName: fileName || cleanPath.split("/").pop() || "unknown",
          fileSize: fileSize || 0,
          mimeType: mimeType || undefined,
          isDirectory: isDirectory || false,
          parentPath: parentPath || "/" + cleanPath.split("/").slice(0, -1).filter(Boolean).join("/"),
        };

        items.push(newItem);
        await setKV(`${STACK_ITEMS_PREFIX}${stackId}`, items);

        // Update stack metadata
        stack.itemCount = items.length;
        if (stack.isFileSystem) {
          stack.fileCount = items.filter(i => !(i as StackItem & { isDirectory?: boolean }).isDirectory).length;
          stack.totalSize = items.reduce((sum, i) => sum + ((i as StackItem & { fileSize?: number }).fileSize || 0), 0);
        }
        await setKV(`${STACK_PREFIX}${stackId}`, stack);

        // Update item-stacks index
        const itemStacks = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${contentKey}`) || [];
        if (!itemStacks.includes(stackId)) {
          itemStacks.push(stackId);
          await setKV(`${ITEM_STACKS_PREFIX}${contentKey}`, itemStacks);
        }

        return NextResponse.json({ success: true, item: newItem });
      }

      case "set-filesystem-mode": {
        // Set filesystem mode on the stack
        stack.isFileSystem = true;
        stack.sourceType = body.sourceType || "upload";
        stack.sourceUrl = body.sourceUrl || undefined;
        stack.sourceCommit = body.sourceCommit || undefined;
        stack.totalSize = body.totalSize || 0;
        stack.fileCount = body.fileCount || 0;

        await setKV(`${STACK_PREFIX}${stackId}`, stack);

        return NextResponse.json({ success: true, stack });
      }

      case "remove-item": {
        if (!contentKey) {
          return NextResponse.json({ success: false, error: "Content key required" }, { status: 400 });
        }

        // Get current items
        const items = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${stackId}`) || [];

        // Remove item
        const filteredItems = items.filter(item => item.contentKey !== contentKey);
        if (filteredItems.length === items.length) {
          return NextResponse.json({ success: false, error: "Item not in stack" }, { status: 400 });
        }
        await setKV(`${STACK_ITEMS_PREFIX}${stackId}`, filteredItems);

        // Update item count
        stack.itemCount = filteredItems.length;
        await setKV(`${STACK_PREFIX}${stackId}`, stack);

        // Update reverse index
        const itemStacks = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${contentKey}`) || [];
        const updatedItemStacks = itemStacks.filter(id => id !== stackId);
        await setKV(`${ITEM_STACKS_PREFIX}${contentKey}`, updatedItemStacks);

        return NextResponse.json({ success: true, stack, itemCount: filteredItems.length });
      }

      case "unlock": {
        if (stack.unlocked) {
          return NextResponse.json({ success: false, error: "Stack already unlocked" }, { status: 400 });
        }

        if (!txHash) {
          return NextResponse.json(
            {
              success: false,
              error: "Payment required",
              requiresPayment: true,
              cost: STACK_UNLOCK_COST,
            },
            { status: 402 }
          );
        }

        // Verify USDC payment for stack unlock
        const paymentResult = await verifyUsdcPayment(txHash, STACK_UNLOCK_COST, owner);
        if (!paymentResult.valid) {
          return NextResponse.json(
            {
              success: false,
              error: paymentResult.error || "Payment verification failed",
              requiresPayment: true,
              cost: STACK_UNLOCK_COST,
            },
            { status: 402 }
          );
        }
        // Mark tx as used to prevent replay
        await markTxUsed(txHash, `stack-unlock:${stackId}`);

        stack.unlocked = true;
        stack.unlockTxHash = txHash;
        await setKV(`${STACK_PREFIX}${stackId}`, stack);

        return NextResponse.json({ success: true, stack });
      }

      case "update-metadata": {
        if (name) stack.name = name.trim();
        if (description !== undefined) stack.description = description?.trim() || undefined;
        // Support filesystem source metadata updates
        if (body.sourceUrl !== undefined) stack.sourceUrl = body.sourceUrl || undefined;
        if (body.sourceType !== undefined) stack.sourceType = body.sourceType || undefined;
        if (body.sourceCommit !== undefined) stack.sourceCommit = body.sourceCommit || undefined;
        await setKV(`${STACK_PREFIX}${stackId}`, stack);

        return NextResponse.json({ success: true, stack });
      }

      case "reorder-items": {
        if (!itemOrder || !Array.isArray(itemOrder)) {
          return NextResponse.json({ success: false, error: "Item order array required" }, { status: 400 });
        }

        // Get current items
        const items = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${stackId}`) || [];

        // Create a map of contentKey -> item for quick lookup
        const itemMap = new Map(items.map(item => [item.contentKey, item]));

        // Verify all contentKeys in order exist in the stack
        for (const key of itemOrder) {
          if (!itemMap.has(key)) {
            return NextResponse.json({ success: false, error: "Invalid item in order" }, { status: 400 });
          }
        }

        // Reorder items based on the provided order
        const reorderedItems: StackItem[] = itemOrder
          .map(key => itemMap.get(key))
          .filter((item): item is StackItem => item !== undefined);

        await setKV(`${STACK_ITEMS_PREFIX}${stackId}`, reorderedItems);

        return NextResponse.json({ success: true, items: reorderedItems });
      }

      case "toggle-privacy": {
        const newPrivacyState = !stack.isPrivate;
        stack.isPrivate = newPrivacyState;
        await setKV(`${STACK_PREFIX}${stackId}`, stack);

        // If making public, return a flag to prompt user to share
        return NextResponse.json({
          success: true,
          stack,
          madePublic: !newPrivacyState ? false : false, // Only true when going from private to public
          promptShare: stack.isPrivate === false && body.wasPrivate === true,
        });
      }

      case "set-privacy": {
        // Explicitly set privacy state (used when we need to know the transition)
        const makePrivate = body.isPrivate === true;
        const wasPrivate = stack.isPrivate || false;
        stack.isPrivate = makePrivate;
        await setKV(`${STACK_PREFIX}${stackId}`, stack);

        // Track items that had previous stacks (for restore prompt)
        const itemsWithPreviousStacks: Array<{
          contentKey: string;
          title?: string;
          previousStacks: Array<{ id: string; name: string }>;
        }> = [];

        // If transitioning from private to public, unhide all items in the stack
        if (wasPrivate && !makePrivate) {
          const stackItems = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${stackId}`) || [];
          for (const item of stackItems) {
            try {
              // Unhide the item
              const unhideResponse = await fetch(`${process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3021"}/api/discovery`, {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                  contentKey: item.contentKey,
                  operator: owner,
                  hidden: false,
                }),
              });
              if (!unhideResponse.ok) {
                console.warn("[set-privacy] Failed to unhide item:", await unhideResponse.text());
              }

              // Check if this item had previous stacks
              const previousStacksData = await getKV<{
                stackIds: string[];
                stackNames: string[];
                hiddenAt: number;
              }>(`${ITEM_PREVIOUS_STACKS_PREFIX}${item.contentKey}`);

              if (previousStacksData && previousStacksData.stackIds.length > 0) {
                // Get item title from discovery for better UX
                let itemTitle: string | undefined;
                try {
                  const discoveryResponse = await fetch(`${process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3021"}/api/discovery?contentKey=${item.contentKey}`);
                  if (discoveryResponse.ok) {
                    const discoveryData = await discoveryResponse.json();
                    itemTitle = discoveryData.entry?.title;
                  }
                } catch {
                  // Ignore discovery errors
                }

                itemsWithPreviousStacks.push({
                  contentKey: item.contentKey,
                  title: itemTitle,
                  previousStacks: previousStacksData.stackIds.map((id, idx) => ({
                    id,
                    name: previousStacksData.stackNames[idx] || "Unknown Stack",
                  })),
                });
              }
            } catch (err) {
              console.warn("[set-privacy] Error unhiding item:", err);
            }
          }
        }

        // If transitioning from public to private, hide all items and remove from other stacks
        if (!wasPrivate && makePrivate) {
          const stackItems = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${stackId}`) || [];
          for (const item of stackItems) {
            try {
              // Find and remove from all OTHER stacks
              const itemStackIds = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${item.contentKey}`) || [];
              const otherStackIds = itemStackIds.filter(id => id !== stackId);
              const removedFromStacks: Array<{ id: string; name: string }> = [];

              for (const otherStackId of otherStackIds) {
                const otherStack = await getKV<Stack>(`${STACK_PREFIX}${otherStackId}`);
                if (otherStack) {
                  removedFromStacks.push({ id: otherStackId, name: otherStack.name });

                  // Remove item from other stack
                  const otherItems = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${otherStackId}`) || [];
                  const filteredOtherItems = otherItems.filter(i => i.contentKey !== item.contentKey);
                  await setKV(`${STACK_ITEMS_PREFIX}${otherStackId}`, filteredOtherItems);

                  // Update other stack's item count
                  otherStack.itemCount = filteredOtherItems.length;
                  await setKV(`${STACK_PREFIX}${otherStackId}`, otherStack);
                }
              }

              // Update reverse index to only contain this stack
              await setKV(`${ITEM_STACKS_PREFIX}${item.contentKey}`, [stackId]);

              // Save previous stacks for potential restore
              if (removedFromStacks.length > 0) {
                await setKV(`${ITEM_PREVIOUS_STACKS_PREFIX}${item.contentKey}`, {
                  stackIds: removedFromStacks.map(s => s.id),
                  stackNames: removedFromStacks.map(s => s.name),
                  hiddenAt: Date.now(),
                });
              }

              // Hide the item
              const hideResponse = await fetch(`${process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3021"}/api/discovery`, {
                method: "PUT",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                  contentKey: item.contentKey,
                  operator: owner,
                  hidden: true,
                }),
              });
              if (!hideResponse.ok) {
                console.warn("[set-privacy] Failed to hide item:", await hideResponse.text());
              }
            } catch (err) {
              console.warn("[set-privacy] Error hiding item:", err);
            }
          }
        }

        // If transitioning from private to public, flag for share prompt
        const shouldPromptShare = wasPrivate && !makePrivate;

        return NextResponse.json({
          success: true,
          stack,
          promptShare: shouldPromptShare,
          itemsWithPreviousStacks: itemsWithPreviousStacks.length > 0 ? itemsWithPreviousStacks : undefined,
        });
      }

      case "restore-to-stacks": {
        // Restore an item to its previous stacks after making it public
        if (!contentKey) {
          return NextResponse.json({ success: false, error: "Content key required" }, { status: 400 });
        }

        const targetStackIds = body.stackIds as string[] | undefined;
        if (!targetStackIds || !Array.isArray(targetStackIds) || targetStackIds.length === 0) {
          return NextResponse.json({ success: false, error: "Stack IDs required" }, { status: 400 });
        }

        const restoredTo: string[] = [];
        const errors: string[] = [];

        for (const targetStackId of targetStackIds) {
          const targetStack = await getKV<Stack>(`${STACK_PREFIX}${targetStackId}`);
          if (!targetStack) {
            errors.push(`Stack ${targetStackId} not found`);
            continue;
          }

          // Verify ownership of target stack
          const isTargetOwner =
            targetStack.owner.toLowerCase() === owner.toLowerCase() ||
            (ownerFid && targetStack.ownerFid === ownerFid);

          if (!isTargetOwner) {
            errors.push(`Not authorized for stack ${targetStack.name}`);
            continue;
          }

          // Check item limit
          if (!targetStack.unlocked && targetStack.itemCount >= DEFAULT_ITEM_LIMIT) {
            errors.push(`Stack "${targetStack.name}" is full`);
            continue;
          }

          // Get target stack items
          const targetItems = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${targetStackId}`) || [];

          // Check if already in stack
          if (targetItems.some(item => item.contentKey === contentKey)) {
            errors.push(`Already in "${targetStack.name}"`);
            continue;
          }

          // Add to target stack
          targetItems.push({
            contentKey,
            addedAt: Date.now(),
            addedBy: owner.toLowerCase(),
          });
          await setKV(`${STACK_ITEMS_PREFIX}${targetStackId}`, targetItems);

          // Update target stack count
          targetStack.itemCount = targetItems.length;
          await setKV(`${STACK_PREFIX}${targetStackId}`, targetStack);

          // Update reverse index
          const itemStacks = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${contentKey}`) || [];
          if (!itemStacks.includes(targetStackId)) {
            itemStacks.push(targetStackId);
            await setKV(`${ITEM_STACKS_PREFIX}${contentKey}`, itemStacks);
          }

          restoredTo.push(targetStack.name);
        }

        // Clear the previous stacks record since we've handled the restore
        await setKV(`${ITEM_PREVIOUS_STACKS_PREFIX}${contentKey}`, null);

        return NextResponse.json({
          success: true,
          restoredTo,
          errors: errors.length > 0 ? errors : undefined,
        });
      }

      default:
        return NextResponse.json({ success: false, error: "Invalid action" }, { status: 400 });
    }
  } catch (error) {
    console.error("[PUT /api/stacks] Error:", error);
    return NextResponse.json({ success: false, error: "Internal error" }, { status: 500 });
  }
}

// DELETE: Delete a stack
export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const stackId = searchParams.get("id");
    const owner = searchParams.get("owner");
    const ownerFid = searchParams.get("fid");

    if (!stackId || !owner) {
      return NextResponse.json(
        { success: false, error: "Stack ID and owner are required" },
        { status: 400 }
      );
    }

    // Fetch stack
    const stack = await getKV<Stack>(`${STACK_PREFIX}${stackId}`);
    if (!stack) {
      return NextResponse.json({ success: false, error: "Stack not found" }, { status: 404 });
    }

    // Verify ownership
    const isOwner =
      stack.owner.toLowerCase() === owner.toLowerCase() ||
      (ownerFid && stack.ownerFid === parseInt(ownerFid));

    if (!isOwner) {
      return NextResponse.json({ success: false, error: "Not authorized" }, { status: 403 });
    }

    // Get items to clean up reverse index
    const items = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${stackId}`) || [];

    // Clean up reverse index for each item
    for (const item of items) {
      const itemStacks = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${item.contentKey}`) || [];
      const updated = itemStacks.filter(id => id !== stackId);
      await setKV(`${ITEM_STACKS_PREFIX}${item.contentKey}`, updated);
    }

    // Remove from user's stacks
    const userStacks = await getKV<string[]>(`${USER_STACKS_PREFIX}${owner.toLowerCase()}`) || [];
    const updatedUserStacks = userStacks.filter(id => id !== stackId);
    await setKV(`${USER_STACKS_PREFIX}${owner.toLowerCase()}`, updatedUserStacks);

    // Remove from global registry
    const allStacks = await getKV<string[]>(STACKS_REGISTRY_KEY) || [];
    const updatedAllStacks = allStacks.filter(id => id !== stackId);
    await setKV(STACKS_REGISTRY_KEY, updatedAllStacks);

    // Delete stack data (we could also just mark as deleted instead)
    // For now, we actually delete since items remain on Net Protocol
    await setKV(`${STACK_PREFIX}${stackId}`, null);
    await setKV(`${STACK_ITEMS_PREFIX}${stackId}`, null);

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("[DELETE /api/stacks] Error:", error);
    return NextResponse.json({ success: false, error: "Internal error" }, { status: 500 });
  }
}
src/app/api/stats/route.ts
import { NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { createPublicClient, http, keccak256, encodePacked } from "viem";
import { base } from "viem/chains";
import type { DiscoveryEntry, MemberRegistry } from "@/lib/net-protocol";

// Contract addresses for upvote queries (same as main app)
const SCORE_CONTRACT = "0x0000000FA09B022E5616E5a173b4b67FA2FBcF28" as const;
const PURE_ALPHA_STRATEGY = "0x00000001b1bcdeddeafd5296aaf4f3f3e21ae876" as const;
const UPVOTE_STORAGE_APP = "0x000000060CEB69D023227DF64CfB75eC37c75B62" as const;

const SCORE_ABI = [
  {
    name: "getAppStrategyKeyScores",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "app", type: "address" },
      { name: "strategy", type: "address" },
      { name: "scoreKeys", type: "bytes32[]" },
    ],
    outputs: [{ name: "counts", type: "int256[]" }],
  },
] as const;

const publicClient = createPublicClient({
  chain: base,
  transport: http("https://mainnet.base.org"),
});

// Generate scoreKey - exact same logic as use-upvotes.ts
function generateScoreKey(storageKey: string, operatorAddress: string): `0x${string}` {
  let key = storageKey.startsWith("0x") ? storageKey : `0x${storageKey}`;

  if (key.length < 66) {
    const hexPart = key.slice(2);
    const paddedHex = hexPart.padStart(64, "0");
    key = `0x${paddedHex}`;
  }

  if (key.length > 66) {
    key = key.slice(0, 66);
  }

  return keccak256(
    encodePacked(
      ["bytes32", "address"],
      [key as `0x${string}`, operatorAddress.toLowerCase() as `0x${string}`]
    )
  );
}

// GET - Fetch global stats (single source of truth for embeds and main app)
export async function GET() {
  try {
    // Fetch discovery index
    const discoveryResult = await db.select().from(kv).where(eq(kv.key, "discovery-index")).limit(1);
    const entries: DiscoveryEntry[] = discoveryResult[0]?.value
      ? JSON.parse(discoveryResult[0].value)
      : [];

    const visibleEntries = entries.filter(e => !e.hidden);

    // Fetch member registry
    const registryResult = await db.select().from(kv).where(eq(kv.key, "member-registry")).limit(1);
    const registry: MemberRegistry | null = registryResult[0]?.value
      ? JSON.parse(registryResult[0].value)
      : null;

    // Basic stats
    const totalItems = visibleEntries.length;
    const totalMembers = registry?.members?.length || 0;
    const totalBytes = visibleEntries.reduce((sum, e) => sum + (e.fileSize || 0), 0);
    const uniqueUploaders = new Set(visibleEntries.map(e => e.operator.toLowerCase())).size;

    // Count stacks
    let totalStacks = 0;
    const stacksResult = await db.select().from(kv).where(eq(kv.key, "stacks-registry")).limit(1);
    if (stacksResult[0]?.value) {
      const stackIds = JSON.parse(stacksResult[0].value);
      totalStacks = Array.isArray(stackIds) ? stackIds.length : 0;
    }

    // Count grids
    let totalGrids = 0;
    const gridsResult = await db.select().from(kv).where(eq(kv.key, "grids-registry")).limit(1);
    if (gridsResult[0]?.value) {
      const gridIds = JSON.parse(gridsResult[0].value);
      totalGrids = Array.isArray(gridIds) ? gridIds.length : 0;
    }

    // Count upvotes from onchain - same method as main app's leaderboard-tab
    let totalUpvotes = 0;
    if (visibleEntries.length > 0) {
      try {
        // Use uploaderAddress (user's actual wallet) if present, falling back to operator
        // (backend relay wallet) — must match the address used when casting upvotes
        const scoreKeys = visibleEntries.map(e =>
          generateScoreKey(e.contentKey, e.uploaderAddress || e.operator)
        );

        // Query in batches
        const batchSize = 100;
        for (let i = 0; i < scoreKeys.length; i += batchSize) {
          const batch = scoreKeys.slice(i, i + batchSize);
          const result = await publicClient.readContract({
            address: SCORE_CONTRACT,
            abi: SCORE_ABI,
            functionName: "getAppStrategyKeyScores",
            args: [
              UPVOTE_STORAGE_APP,
              PURE_ALPHA_STRATEGY,
              batch,
            ],
          });

          const counts = result as bigint[];
          for (const count of counts) {
            totalUpvotes += Number(count);
          }
        }
      } catch (upvoteError) {
        console.error("[stats] Failed to fetch onchain upvotes:", upvoteError);
        // Don't fallback - if onchain fails, return 0 to indicate issue
      }
    }

    return NextResponse.json({
      success: true,
      stats: {
        totalItems,
        totalStacks,
        totalGrids,
        totalBytes,
        totalMembers,
        uniqueUploaders,
        totalUpvotes,
      },
      timestamp: Date.now(),
    });
  } catch (error) {
    console.error("[stats] Error:", error);
    return NextResponse.json(
      { error: "Failed to fetch stats" },
      { status: 500 }
    );
  }
}
src/app/api/streaks/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { UserStreak } from "@/lib/net-protocol";

const STREAKS_KV_KEY = "net-library-streaks";

interface StreaksIndex {
  users: Record<string, UserStreak>;
}

// GET - Fetch user's reading streak
export async function GET(request: NextRequest) {
  const address = request.nextUrl.searchParams.get("address");

  if (!address) {
    return NextResponse.json({ error: "Address required" }, { status: 400 });
  }

  try {
    // Fetch streaks from KV store
    const result = await db
      .select()
      .from(kv)
      .where(eq(kv.key, STREAKS_KV_KEY))
      .limit(1);

    if (result.length === 0) {
      return NextResponse.json({
        success: true,
        streak: null,
      });
    }

    const streaksIndex: StreaksIndex = JSON.parse(result[0].value);
    const userStreak = streaksIndex?.users?.[address.toLowerCase()] || null;

    return NextResponse.json({
      success: true,
      streak: userStreak,
    });
  } catch (error) {
    console.error("Streaks GET error:", error);
    return NextResponse.json({ error: "Failed to fetch streak" }, { status: 500 });
  }
}

// POST - Update user's reading streak (called when they read a book)
export async function POST(request: NextRequest) {
  try {
    const { userAddress } = await request.json();

    if (!userAddress) {
      return NextResponse.json({ error: "userAddress required" }, { status: 400 });
    }

    const normalizedAddress = userAddress.toLowerCase();
    const today = new Date().toISOString().split("T")[0]; // YYYY-MM-DD

    // Fetch existing streaks
    const result = await db
      .select()
      .from(kv)
      .where(eq(kv.key, STREAKS_KV_KEY))
      .limit(1);

    let streaksIndex: StreaksIndex = { users: {} };

    if (result.length > 0) {
      streaksIndex = JSON.parse(result[0].value);
    }

    // Get or create user streak
    let userStreak = streaksIndex.users[normalizedAddress];

    if (!userStreak) {
      userStreak = {
        address: normalizedAddress,
        currentStreak: 0,
        longestStreak: 0,
        lastReadDate: "",
        totalDaysActive: 0,
        readingHistory: [],
      };
    }

    // Check if already read today
    if (userStreak.lastReadDate === today) {
      return NextResponse.json({
        success: true,
        streak: userStreak,
        message: "Already recorded today",
      });
    }

    // Calculate if streak continues or breaks
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);
    const yesterdayStr = yesterday.toISOString().split("T")[0];

    if (userStreak.lastReadDate === yesterdayStr) {
      // Streak continues
      userStreak.currentStreak += 1;
    } else if (userStreak.lastReadDate === "") {
      // First day
      userStreak.currentStreak = 1;
    } else {
      // Streak broken, start new
      userStreak.currentStreak = 1;
    }

    // Update longest streak
    if (userStreak.currentStreak > userStreak.longestStreak) {
      userStreak.longestStreak = userStreak.currentStreak;
    }

    // Update tracking
    userStreak.lastReadDate = today;
    userStreak.totalDaysActive += 1;
    userStreak.readingHistory = [...(userStreak.readingHistory || []).slice(-30), today];

    // Save back to KV
    streaksIndex.users[normalizedAddress] = userStreak;

    if (result.length > 0) {
      await db
        .update(kv)
        .set({ value: JSON.stringify(streaksIndex) })
        .where(eq(kv.key, STREAKS_KV_KEY));
    } else {
      await db.insert(kv).values({
        key: STREAKS_KV_KEY,
        value: JSON.stringify(streaksIndex),
      });
    }

    return NextResponse.json({
      success: true,
      streak: userStreak,
    });
  } catch (error) {
    console.error("Streaks POST error:", error);
    return NextResponse.json({ error: "Failed to update streak" }, { status: 500 });
  }
}
src/app/api/trending/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

// Trending criteria: 100+ upvotes in the last hour
const TRENDING_THRESHOLD = 100;
const TRENDING_WINDOW_MS = 60 * 60 * 1000; // 1 hour in milliseconds

const UPVOTE_EVENTS_KEY = "upvote-events-index";

type UpvoteEvent = {
  id: string;
  upvoter: string;
  storageKey: string;
  operator: string;
  amount: number;
  timestamp: number;
  transactionHash: string;
  contentKey?: string;
};

interface UpvoteEventsIndex {
  events: UpvoteEvent[];
  lastUpdated: number;
}

// Fetch upvote events from KV
async function fetchUpvoteEvents(): Promise<UpvoteEventsIndex> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, UPVOTE_EVENTS_KEY)).limit(1);
    if (!result[0]?.value) return { events: [], lastUpdated: Date.now() };
    return JSON.parse(result[0].value) as UpvoteEventsIndex;
  } catch (error) {
    console.error("[trending] fetchUpvoteEvents error:", error);
    return { events: [], lastUpdated: Date.now() };
  }
}

// GET - Check trending status for content keys
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const contentKeysParam = searchParams.get("contentKeys");

    if (!contentKeysParam) {
      return NextResponse.json(
        { error: "Missing contentKeys parameter" },
        { status: 400 }
      );
    }

    const contentKeys = contentKeysParam.split(",").map(k => k.trim().toLowerCase());
    const now = Date.now();
    const windowStart = now - TRENDING_WINDOW_MS;

    console.log(`[trending] Checking ${contentKeys.length} items for trending status`);

    const eventsIndex = await fetchUpvoteEvents();
    const events = eventsIndex.events;

    // Filter to events within the trending window
    const recentEvents = events.filter(e => e.timestamp >= windowStart);

    // Calculate upvotes per content key in the time window
    const upvotesInWindow = new Map<string, number>();

    for (const event of recentEvents) {
      // Use contentKey if available, otherwise use storageKey
      const key = (event.contentKey || event.storageKey).toLowerCase();
      const current = upvotesInWindow.get(key) || 0;
      upvotesInWindow.set(key, current + event.amount);
    }

    // Build response with trending status for each requested content key
    const trendingStatus: Record<string, { isTrending: boolean; upvotesInLastHour: number }> = {};

    for (const contentKey of contentKeys) {
      const upvotes = upvotesInWindow.get(contentKey) || 0;
      trendingStatus[contentKey] = {
        isTrending: upvotes >= TRENDING_THRESHOLD,
        upvotesInLastHour: upvotes,
      };
    }

    // Also return list of all currently trending items (useful for discovery)
    const allTrending = Array.from(upvotesInWindow.entries())
      .filter(([, count]) => count >= TRENDING_THRESHOLD)
      .map(([key, count]) => ({ contentKey: key, upvotesInLastHour: count }))
      .sort((a, b) => b.upvotesInLastHour - a.upvotesInLastHour);

    console.log(`[trending] Found ${allTrending.length} trending items, checked ${contentKeys.length} keys`);

    return NextResponse.json({
      success: true,
      trendingStatus,
      allTrending,
      threshold: TRENDING_THRESHOLD,
      windowMs: TRENDING_WINDOW_MS,
    });
  } catch (error) {
    console.error("[trending] Error:", error);
    return NextResponse.json(
      { error: "Failed to check trending status" },
      { status: 500 }
    );
  }
}
src/app/api/upload-activity/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

const ACHIEVEMENTS_KEY = "user-achievements-index";
const UPLOAD_STATS_KEY = "user-upload-stats";

interface UserAchievement {
  id: string;
  earnedAt: number;
}

interface UserAchievements {
  address: string;
  achievements: UserAchievement[];
}

interface AchievementsIndex {
  users: { [address: string]: UserAchievements };
  lastUpdated: number;
}

interface UserUploadStats {
  address: string;
  totalUploads: number;
  uploadedContentKeys: string[];
  categoriesContributed: string[]; // Track unique categories for future achievements
  firstUploadAt?: number;
  lastUploadAt: number;
}

interface UploadStatsIndex {
  users: { [address: string]: UserUploadStats };
  lastUpdated: number;
}

// Fetch achievements index from KV
async function fetchAchievementsIndex(): Promise<AchievementsIndex> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, ACHIEVEMENTS_KEY)).limit(1);
    if (!result[0]?.value) return { users: {}, lastUpdated: Date.now() };
    return JSON.parse(result[0].value) as AchievementsIndex;
  } catch {
    return { users: {}, lastUpdated: Date.now() };
  }
}

// Store achievements index to KV
async function storeAchievementsIndex(data: AchievementsIndex): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: ACHIEVEMENTS_KEY, value: JSON.stringify(data) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(data) },
    });
    return true;
  } catch (error) {
    console.error("storeAchievementsIndex error:", error);
    return false;
  }
}

// Fetch upload stats from KV
async function fetchUploadStats(): Promise<UploadStatsIndex> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, UPLOAD_STATS_KEY)).limit(1);
    if (!result[0]?.value) return { users: {}, lastUpdated: Date.now() };
    return JSON.parse(result[0].value) as UploadStatsIndex;
  } catch {
    return { users: {}, lastUpdated: Date.now() };
  }
}

// Store upload stats to KV
async function storeUploadStats(data: UploadStatsIndex): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: UPLOAD_STATS_KEY, value: JSON.stringify(data) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(data) },
    });
    return true;
  } catch (error) {
    console.error("storeUploadStats error:", error);
    return false;
  }
}

// Check and award upload achievements
function checkUploadAchievements(uploadStats: UserUploadStats, currentAchievements: UserAchievement[]): UserAchievement[] {
  const earned = [...currentAchievements];
  const hasAchievement = (id: string) => earned.some(a => a.id === id);

  // First upload achievement
  if (uploadStats.totalUploads >= 1 && !hasAchievement("first-upload")) {
    earned.push({ id: "first-upload", earnedAt: Date.now() });
  }

  // Contributor achievements
  if (uploadStats.totalUploads >= 5 && !hasAchievement("contributor-5")) {
    earned.push({ id: "contributor-5", earnedAt: Date.now() });
  }
  if (uploadStats.totalUploads >= 25 && !hasAchievement("contributor-25")) {
    earned.push({ id: "contributor-25", earnedAt: Date.now() });
  }
  if (uploadStats.totalUploads >= 100 && !hasAchievement("contributor-100")) {
    earned.push({ id: "contributor-100", earnedAt: Date.now() });
  }

  return earned;
}

// GET - Fetch user's upload stats and achievements
export async function GET(request: NextRequest) {
  const address = request.nextUrl.searchParams.get("address");

  if (!address) {
    return NextResponse.json({ error: "Address required" }, { status: 400 });
  }

  const normalizedAddress = address.toLowerCase();

  try {
    const uploadStatsIndex = await fetchUploadStats();
    const achievementsIndex = await fetchAchievementsIndex();

    const userStats = uploadStatsIndex.users[normalizedAddress] || {
      address: normalizedAddress,
      totalUploads: 0,
      uploadedContentKeys: [],
      lastUploadAt: 0,
    };

    const userAchievements = achievementsIndex.users[normalizedAddress]?.achievements || [];

    return NextResponse.json({
      success: true,
      stats: userStats,
      achievements: userAchievements,
    });
  } catch (error) {
    console.error("Upload activity GET error:", error);
    return NextResponse.json({ error: "Failed to fetch upload activity" }, { status: 500 });
  }
}

// POST - Record upload activity and award achievements
export async function POST(request: NextRequest) {
  try {
    const { userAddress, contentKey, action, categories } = await request.json();

    if (!userAddress || !action) {
      return NextResponse.json({ error: "userAddress and action required" }, { status: 400 });
    }

    const normalizedAddress = userAddress.toLowerCase();
    const now = Date.now();

    // Fetch current indexes
    const uploadStatsIndex = await fetchUploadStats();
    const achievementsIndex = await fetchAchievementsIndex();

    // Get or create user stats
    let userStats = uploadStatsIndex.users[normalizedAddress] || {
      address: normalizedAddress,
      totalUploads: 0,
      uploadedContentKeys: [],
      categoriesContributed: [],
      lastUploadAt: 0,
    };

    // Initialize categoriesContributed if not present (for existing users)
    if (!userStats.categoriesContributed) {
      userStats.categoriesContributed = [];
    }

    // Get or create user achievements
    let userAchievements = achievementsIndex.users[normalizedAddress] || {
      address: normalizedAddress,
      achievements: [],
    };

    if (action === "upload-complete" && contentKey) {
      // Check if this content key was already recorded (avoid duplicates)
      if (!userStats.uploadedContentKeys.includes(contentKey)) {
        userStats.totalUploads += 1;
        userStats.uploadedContentKeys.push(contentKey);
        userStats.lastUploadAt = now;

        // Track categories (for future achievements)
        if (categories && Array.isArray(categories)) {
          for (const cat of categories) {
            if (!userStats.categoriesContributed.includes(cat)) {
              userStats.categoriesContributed.push(cat);
            }
          }
        }

        // Set first upload time if not set
        if (!userStats.firstUploadAt) {
          userStats.firstUploadAt = now;
        }

        // Check for new achievements
        const newAchievements = checkUploadAchievements(userStats, userAchievements.achievements);
        const earnedNew = newAchievements.length > userAchievements.achievements.length;
        const newlyEarned = newAchievements.filter(
          a => !userAchievements.achievements.some(existing => existing.id === a.id)
        );
        userAchievements.achievements = newAchievements;

        // Update indexes
        uploadStatsIndex.users[normalizedAddress] = userStats;
        uploadStatsIndex.lastUpdated = now;

        achievementsIndex.users[normalizedAddress] = userAchievements;
        achievementsIndex.lastUpdated = now;

        // Store updates
        await storeUploadStats(uploadStatsIndex);
        await storeAchievementsIndex(achievementsIndex);

        return NextResponse.json({
          success: true,
          stats: userStats,
          achievements: userAchievements.achievements,
          newAchievements: earnedNew,
          newlyEarnedAchievements: newlyEarned.map(a => a.id),
        });
      }
    }

    return NextResponse.json({
      success: true,
      stats: userStats,
      achievements: userAchievements.achievements,
      newAchievements: false,
    });
  } catch (error) {
    console.error("Upload activity POST error:", error);
    return NextResponse.json({ error: "Failed to record upload activity" }, { status: 500 });
  }
}
src/app/api/upload-check/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry, UserUploadStats, UploadEligibility } from "@/lib/net-protocol";
import {
  checkForDuplicateContent,
  checkUploadEligibility,
  WARMUP_PERIOD_DAYS,
  WARMUP_DAILY_LIMIT,
  REGULAR_DAILY_LIMIT,
  UPLOAD_PASS_DAILY_LIMIT,
  APP_CREATOR_FIDS,
} from "@/lib/net-protocol";

const DISCOVERY_KEY = "discovery-index";
const UPLOAD_STATS_KEY = "upload-stats-index";
const UPLOAD_PASSES_KEY = "upload-passes-index"; // Track who has purchased Upload Pass
const MEMBERS_KEY = "member-registry"; // Must match the key used in /api/membership

interface UploadStatsIndex {
  users: {
    [address: string]: {
      totalUploads: number;
      totalBytesUploaded: number;
      firstUploadAt: number;
      lastUploadAt: number;
      dailyUploads: { [date: string]: number }; // ISO date -> count
    };
  };
  lastUpdated: number;
}

interface UploadPassesIndex {
  passes: {
    [address: string]: {
      purchasedAt: number;
      txHash?: string;
    };
  };
  lastUpdated: number;
}

interface MemberEntry {
  memberId: number;
  address: string;
  joinedAt: number;
  linkedAddresses?: string[];
  signupPlatform?: string;
  fid?: number;
}

// Fetch discovery index
async function fetchDiscoveryIndex(): Promise<DiscoveryEntry[]> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    if (!result[0]?.value) return [];
    return JSON.parse(result[0].value) as DiscoveryEntry[];
  } catch {
    return [];
  }
}

// Fetch upload stats
async function fetchUploadStats(): Promise<UploadStatsIndex> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, UPLOAD_STATS_KEY)).limit(1);
    if (!result[0]?.value) return { users: {}, lastUpdated: Date.now() };
    return JSON.parse(result[0].value) as UploadStatsIndex;
  } catch {
    return { users: {}, lastUpdated: Date.now() };
  }
}

// Store upload stats
async function storeUploadStats(stats: UploadStatsIndex): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: UPLOAD_STATS_KEY, value: JSON.stringify(stats) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(stats) },
    });
    return true;
  } catch (error) {
    console.error("storeUploadStats error:", error);
    return false;
  }
}

// Fetch upload passes
async function fetchUploadPasses(): Promise<UploadPassesIndex> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, UPLOAD_PASSES_KEY)).limit(1);
    if (!result[0]?.value) return { passes: {}, lastUpdated: Date.now() };
    return JSON.parse(result[0].value) as UploadPassesIndex;
  } catch {
    return { passes: {}, lastUpdated: Date.now() };
  }
}

// Store upload passes
async function storeUploadPasses(passes: UploadPassesIndex): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: UPLOAD_PASSES_KEY, value: JSON.stringify(passes) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(passes) },
    });
    return true;
  } catch (error) {
    console.error("storeUploadPasses error:", error);
    return false;
  }
}

// Fetch members to get join date (from member-registry which has { members: [...], nextMemberId, lastUpdated })
async function fetchMembers(): Promise<MemberEntry[]> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, MEMBERS_KEY)).limit(1);
    if (!result[0]?.value) return [];
    const registry = JSON.parse(result[0].value);
    // Handle both old format (array) and new format (registry object with members array)
    if (Array.isArray(registry)) {
      return registry as MemberEntry[];
    }
    return registry.members || [];
  } catch {
    return [];
  }
}

// Get today's date string (for daily limits)
function getTodayString(): string {
  return new Date().toISOString().split("T")[0];
}

// Get all addresses associated with a user (for cross-platform identity)
function getAllUserAddresses(address: string, fid: number | undefined, members: MemberEntry[]): Set<string> {
  const addresses = new Set<string>();
  addresses.add(address.toLowerCase());

  // Find all memberships for this user by address or FID
  for (const member of members) {
    if (!member.address) continue;
    const memberAddr = member.address.toLowerCase();
    const isMatch =
      memberAddr === address.toLowerCase() ||
      member.linkedAddresses?.some(linked => linked && linked.toLowerCase() === address.toLowerCase()) ||
      (fid && member.fid === fid);

    if (isMatch) {
      // Add this member's address
      addresses.add(memberAddr);
      // Add any linked addresses
      if (member.linkedAddresses) {
        for (const linked of member.linkedAddresses) {
          if (linked) addresses.add(linked.toLowerCase());
        }
      }
    }
  }

  return addresses;
}

// Get user's upload stats.
// Accept an optional pre-fetched members array so callers that have already read
// the member registry (e.g. to derive isMember server-side) can pass it in and
// avoid a redundant KV read.
async function getUserUploadStats(
  address: string,
  fid?: number,
  prefetchedMembers?: MemberEntry[]
): Promise<UserUploadStats> {
  const normalizedAddress = address.toLowerCase();
  const uploadStats = await fetchUploadStats();
  const uploadPasses = await fetchUploadPasses();
  const members = prefetchedMembers ?? await fetchMembers();
  const discoveryIndex = await fetchDiscoveryIndex();

  // Get ALL addresses associated with this user (cross-platform identity)
  const allUserAddresses = getAllUserAddresses(normalizedAddress, fid, members);

  // Aggregate upload stats across ALL user addresses
  let totalUploads = 0;
  let totalBytesUploaded = 0;
  let uploadsToday = 0;
  let hasUploadPass = false;
  let hasStackPass = false; // Unlimited Pass = warmup jailbreak
  const todayString = getTodayString();

  for (const addr of allUserAddresses) {
    // Check upload stats index
    const stats = uploadStats.users[addr];
    if (stats) {
      totalUploads += stats.totalUploads || 0;
      totalBytesUploaded += stats.totalBytesUploaded || 0;
      uploadsToday += stats.dailyUploads?.[todayString] || 0;
    }

    // Check upload passes (legacy)
    if (uploadPasses.passes[addr]) {
      hasUploadPass = true;
    }
  }

  // Check for Stack Pass in membership (Stack Pass = warmup jailbreak)
  for (const member of members) {
    const isMatch =
      allUserAddresses.has(member.address.toLowerCase()) ||
      (fid && member.fid === fid);

    if (isMatch && (member as MemberEntry & { hasStackPass?: boolean }).hasStackPass) {
      hasStackPass = true;
      break;
    }
  }

  // Stack Pass grants the same privileges as Upload Pass (warmup bypass)
  if (hasStackPass) {
    hasUploadPass = true;
  }

  // Also count from discovery index for any addresses without stats
  const discoveryUploads = discoveryIndex.filter(e =>
    allUserAddresses.has(e.operator.toLowerCase())
  );

  // Use discovery count if higher (stats might be incomplete)
  if (discoveryUploads.length > totalUploads) {
    totalUploads = discoveryUploads.length;
    totalBytesUploaded = discoveryUploads.reduce((sum, e) => sum + e.fileSize, 0);
  }

  // Get membership join date - find earliest membership
  // This ensures cross-platform users get their correct membership benefits
  let earliestJoinDate: number | null = null;
  for (const member of members) {
    const isMatch =
      allUserAddresses.has(member.address.toLowerCase()) ||
      (fid && member.fid === fid);

    if (isMatch && member.joinedAt && member.joinedAt > 0) {
      if (earliestJoinDate === null || member.joinedAt < earliestJoinDate) {
        earliestJoinDate = member.joinedAt;
      }
    }
  }

  // If no membership found, default to now (will show as in warm-up)
  const memberJoinedAt = earliestJoinDate ?? Date.now();
  let daysSinceMembership = Math.floor((Date.now() - memberJoinedAt) / (1000 * 60 * 60 * 24));

  // App creators/team bypass warm-up period entirely
  if (fid && APP_CREATOR_FIDS.has(fid)) {
    daysSinceMembership = Math.max(daysSinceMembership, WARMUP_PERIOD_DAYS + 1);
  }

  return {
    totalUploads,
    totalMBUploaded: totalBytesUploaded / (1024 * 1024),
    daysSinceMembership,
    uploadsToday,
    hasUploadPass,
  };
}

// POST - Check upload eligibility (content hash + limits + duplicate detection)
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    // isMember is intentionally ignored from the body — derived server-side below.
    const { contentHash, title, author, isbn, fileSize, address, fid } = body;

    if (!address) {
      return NextResponse.json({ error: "Address required" }, { status: 400 });
    }

    // Derive membership status server-side from the registry.
    // Trusting isMember from the request body would allow a non-member to spoof
    // member-level upload limits (100/day vs 0).
    const members = await fetchMembers();
    const normalizedAddress = address.toLowerCase();
    const isMember = members.some((m) => {
      if (!m.address) return false;
      if (m.address.toLowerCase() === normalizedAddress) return true;
      if (fid && m.fid === fid) return true;
      if (m.linkedAddresses?.some((la) => la && la.toLowerCase() === normalizedAddress)) return true;
      return false;
    });

    // Pass the already-fetched members array to avoid a second KV read inside getUserUploadStats.
    const stats = await getUserUploadStats(address, fid, members);

    // Check upload eligibility — pass FID so team members get bypassed inside the function
    const eligibility = checkUploadEligibility(stats, fileSize || 0, isMember, fid);

    // Check for duplicate content using comprehensive multi-field detection
    let duplicateCheck = null;
    if (contentHash || title || author || isbn) {
      const entries = await fetchDiscoveryIndex();
      duplicateCheck = checkForDuplicateContent(
        {
          contentHash: contentHash || undefined,
          title: title || "",
          author: author || undefined,
          isbn: isbn || undefined,
        },
        entries
      );
    }

    return NextResponse.json({
      success: true,
      eligibility,
      duplicateCheck,
      stats,
    });
  } catch (error) {
    console.error("Upload check error:", error);
    return NextResponse.json({ error: "Failed to check upload eligibility" }, { status: 500 });
  }
}

// GET - Get user's upload stats and limits
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const address = searchParams.get("address");
  const fidStr = searchParams.get("fid");
  const fid = fidStr ? parseInt(fidStr, 10) : undefined;

  if (!address) {
    return NextResponse.json({ error: "Address required" }, { status: 400 });
  }

  try {
    // Derive membership status server-side from the registry rather than trusting
    // the isMember query param (which is client-controlled and could be spoofed to
    // receive member-level limits as a non-member).
    const members = await fetchMembers();
    const normalizedAddress = address.toLowerCase();
    const isMember = members.some((m) => {
      if (!m.address) return false;
      if (m.address.toLowerCase() === normalizedAddress) return true;
      if (fid && m.fid === fid) return true;
      if (m.linkedAddresses?.some((la) => la && la.toLowerCase() === normalizedAddress)) return true;
      return false;
    });

    // Pass the already-fetched members array to avoid a second KV read inside getUserUploadStats.
    const stats = await getUserUploadStats(address, fid, members);
    const eligibility: UploadEligibility = checkUploadEligibility(stats, 0, isMember, fid);

    // Calculate current daily limit for display
    const isInWarmup = stats.daysSinceMembership < WARMUP_PERIOD_DAYS;
    const dailyLimit = isInWarmup
      ? (stats.hasUploadPass ? UPLOAD_PASS_DAILY_LIMIT : WARMUP_DAILY_LIMIT)
      : REGULAR_DAILY_LIMIT;

    return NextResponse.json({
      success: true,
      stats,
      uploadsRemaining: eligibility.uploadsRemaining,
      maxFileSizeAllowed: eligibility.maxFileSizeAllowed,
      dailyLimit,
      isInWarmupPeriod: eligibility.isInWarmupPeriod,
      daysRemainingInWarmup: eligibility.daysRemainingInWarmup,
      hasUploadPass: stats.hasUploadPass,
    });
  } catch (error) {
    console.error("Get upload stats error:", error);
    return NextResponse.json({ error: "Failed to get upload stats" }, { status: 500 });
  }
}

// PUT - Record a completed upload (updates stats)
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();
    const { address, fileSize, contentKey: _contentKey, fid: fidRaw } = body;
    const fid = fidRaw ? Number(fidRaw) : undefined;

    // fileSize can be 0 for CDN imports (no actual file upload, just metadata registration)
    if (!address || fileSize === undefined || fileSize === null) {
      return NextResponse.json({ error: "Address and fileSize required" }, { status: 400 });
    }

    const normalizedAddress = address.toLowerCase();
    const stats = await fetchUploadStats();
    const todayString = getTodayString();

    // Initialize user if needed
    if (!stats.users[normalizedAddress]) {
      stats.users[normalizedAddress] = {
        totalUploads: 0,
        totalBytesUploaded: 0,
        firstUploadAt: Date.now(),
        lastUploadAt: Date.now(),
        dailyUploads: {},
      };
    }

    // Update stats
    stats.users[normalizedAddress].totalUploads += 1;
    stats.users[normalizedAddress].totalBytesUploaded += fileSize;
    stats.users[normalizedAddress].lastUploadAt = Date.now();
    stats.users[normalizedAddress].dailyUploads[todayString] =
      (stats.users[normalizedAddress].dailyUploads[todayString] || 0) + 1;

    // Clean up old daily uploads (keep last 7 days).
    // Use UTC arithmetic to match getTodayString() which uses toISOString().
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setUTCDate(sevenDaysAgo.getUTCDate() - 7);
    const cutoffDate = sevenDaysAgo.toISOString().split("T")[0];

    for (const date of Object.keys(stats.users[normalizedAddress].dailyUploads)) {
      if (date < cutoffDate) {
        delete stats.users[normalizedAddress].dailyUploads[date];
      }
    }

    stats.lastUpdated = Date.now();
    await storeUploadStats(stats);

    // Get updated stats — pass FID so team members see 99999 for uploadsRemaining
    const updatedStats = await getUserUploadStats(address, fid);
    const eligibility = checkUploadEligibility(updatedStats, 0, true, fid);

    return NextResponse.json({
      success: true,
      stats: updatedStats,
      uploadsRemaining: eligibility.uploadsRemaining,
    });
  } catch (error) {
    console.error("Record upload error:", error);
    return NextResponse.json({ error: "Failed to record upload" }, { status: 500 });
  }
}

// PATCH - Record Upload Pass purchase
export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const { address, txHash } = body;

    if (!address) {
      return NextResponse.json({ error: "Address required" }, { status: 400 });
    }

    const normalizedAddress = address.toLowerCase();
    const passes = await fetchUploadPasses();

    // Record the purchase
    passes.passes[normalizedAddress] = {
      purchasedAt: Date.now(),
      txHash: txHash || undefined,
    };
    passes.lastUpdated = Date.now();

    await storeUploadPasses(passes);

    return NextResponse.json({
      success: true,
      hasUploadPass: true,
    });
  } catch (error) {
    console.error("Record upload pass error:", error);
    return NextResponse.json({ error: "Failed to record upload pass" }, { status: 500 });
  }
}
src/app/api/upload-cover/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";

/**
 * Upload Cover Image API
 * Converts base64 cover images to hosted URLs via our KV database
 *
 * This solves the problem where:
 * 1. Covers are extracted as base64 data URLs during upload
 * 2. Base64 URLs are too large to pass in OG image URL params
 * 3. Share images were falling back to placeholder instead of showing actual cover
 *
 * Now uses KV storage instead of Vercel Blob for simplicity and reliability.
 */

const COVER_PREFIX = "cover:";
const MAX_COVER_SIZE = 500 * 1024; // 500KB max per cover

// POST - Upload a base64 image and return a hosted URL
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { dataUrl, contentKey } = body;

    if (!dataUrl) {
      return NextResponse.json({ error: "Missing dataUrl" }, { status: 400 });
    }

    // Validate it's actually a data URL
    if (!dataUrl.startsWith("data:image/")) {
      return NextResponse.json({ error: "Invalid data URL format" }, { status: 400 });
    }

    // Extract the base64 data and content type
    const matches = dataUrl.match(/^data:image\/(png|jpeg|jpg|webp|gif);base64,(.+)$/);
    if (!matches) {
      return NextResponse.json({ error: "Could not parse data URL" }, { status: 400 });
    }

    const imageType = matches[1] === "jpg" ? "jpeg" : matches[1];
    const base64Data = matches[2];

    // Check size
    const sizeBytes = Math.ceil(base64Data.length * 0.75); // Approximate decoded size
    if (sizeBytes > MAX_COVER_SIZE) {
      return NextResponse.json({
        error: `Cover too large (${Math.round(sizeBytes/1024)}KB). Max: ${MAX_COVER_SIZE/1024}KB`
      }, { status: 400 });
    }

    // Generate a unique key
    const timestamp = Date.now();
    const safeContentKey = contentKey
      ? contentKey.replace(/[^a-zA-Z0-9-]/g, "").slice(0, 32)
      : `cover-${timestamp}`;
    const key = `${safeContentKey}-${timestamp}`;
    const coverKey = `${COVER_PREFIX}${key}`;

    // Store in KV database
    const coverData = {
      base64: base64Data,
      contentType: `image/${imageType}`,
      contentKey: contentKey || key,
      storedAt: timestamp,
    };

    await db.insert(kv).values({
      key: coverKey,
      value: JSON.stringify(coverData),
    }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(coverData) },
    });

    // Return the URL to access this cover - ALWAYS use production domain
    // This ensures the URL works when shared to Twitter/Farcaster
    const productionHost = "netlibrary.neynar.com";
    const coverUrl = `https://${productionHost}/api/covers/${key}`;

    console.log(`[upload-cover] Stored cover: ${coverUrl} (${Math.round(sizeBytes/1024)}KB)`);

    return NextResponse.json({
      success: true,
      url: coverUrl,
      contentType: `image/${imageType}`,
      size: sizeBytes,
    });
  } catch (error) {
    console.error("[upload-cover] Error:", error);

    return NextResponse.json({
      error: "Failed to upload cover",
      details: error instanceof Error ? error.message : "Unknown error",
    }, { status: 500 });
  }
}
src/app/api/upload-diagnostics/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

// Store upload diagnostics for debugging
// GET: Retrieve recent diagnostics sessions
// POST: Store a new diagnostics session

const DIAGNOSTICS_KEY = "upload-diagnostics";
const MAX_SESSIONS = 50; // Keep last 50 sessions

export interface StoredDiagnostics {
  sessionId: string;
  startTime: number;
  endTime: number;
  fileName: string;
  fileSize: number;
  fileSizeMB: string;
  storageType: string;
  walletConnector: string;
  walletAddress: string;
  chainId: number;
  totalChunks: number;
  completedChunks: number;
  outcome: "success" | "error" | "cancelled";
  errorMessage?: string;
  errorCategory?: string;
  totalDurationMs: number;
  totalDurationSec: string;
  // Phase breakdown
  phases: {
    name: string;
    durationMs: number;
    success: boolean;
    error?: string;
  }[];
  // Failed chunks summary
  failedChunks: {
    index: number;
    key: string;
    calldataKB: string;
    error: string;
    retryCount: number;
  }[];
  // Timing stats
  avgChunkSubmitMs?: number;
  avgChunkConfirmMs?: number;
  // Raw data for deep debugging
  rawChunks?: {
    index: number;
    key: string;
    calldataSize: number;
    submittedAt?: number;
    confirmedAt?: number;
    txHash?: string;
    error?: string;
    retryCount: number;
  }[];
}

// Fetch diagnostics from KV
async function fetchDiagnostics(): Promise<StoredDiagnostics[]> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, DIAGNOSTICS_KEY)).limit(1);
    if (!result[0]?.value) return [];
    return JSON.parse(result[0].value) as StoredDiagnostics[];
  } catch (error) {
    console.error("[upload-diagnostics] fetchDiagnostics error:", error);
    return [];
  }
}

// Store diagnostics to KV
async function storeDiagnostics(sessions: StoredDiagnostics[]): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: DIAGNOSTICS_KEY, value: JSON.stringify(sessions) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(sessions) },
    });
    return true;
  } catch (error) {
    console.error("[upload-diagnostics] storeDiagnostics error:", error);
    return false;
  }
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const sessionId = searchParams.get("sessionId");
    const limit = parseInt(searchParams.get("limit") || "10", 10);
    const includeRaw = searchParams.get("includeRaw") === "true";

    // Get all sessions
    const sessions = await fetchDiagnostics();

    if (sessionId) {
      // Return specific session
      const session = sessions.find((s: StoredDiagnostics) => s.sessionId === sessionId);
      if (!session) {
        return NextResponse.json({ error: "Session not found" }, { status: 404 });
      }
      return NextResponse.json({ session });
    }

    // Return recent sessions (without raw chunk data unless requested)
    const recentSessions = sessions.slice(-limit).reverse();

    const result = includeRaw
      ? recentSessions
      : recentSessions.map((s: StoredDiagnostics) => {
          const { rawChunks: _rawChunks, ...rest } = s;
          return rest;
        });

    return NextResponse.json({
      sessions: result,
      total: sessions.length,
    });
  } catch (error) {
    console.error("[upload-diagnostics] GET error:", error);
    return NextResponse.json(
      { error: "Failed to retrieve diagnostics" },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    // Validate required fields
    if (!body.sessionId || !body.outcome) {
      return NextResponse.json(
        { error: "Missing required fields: sessionId, outcome" },
        { status: 400 }
      );
    }

    // Build stored diagnostics from the raw data
    const stored: StoredDiagnostics = {
      sessionId: body.sessionId,
      startTime: body.startTime,
      endTime: Date.now(),
      fileName: body.fileName,
      fileSize: body.fileSize,
      fileSizeMB: (body.fileSize / 1024 / 1024).toFixed(2),
      storageType: body.storageType,
      walletConnector: body.walletConnector,
      walletAddress: body.walletAddress,
      chainId: body.chainId,
      totalChunks: body.totalChunks,
      completedChunks: body.chunks?.filter((c: { confirmedAt?: number }) => c.confirmedAt).length || 0,
      outcome: body.outcome,
      errorMessage: body.errorMessage,
      errorCategory: body.errorCategory,
      totalDurationMs: body.totalDurationMs || (Date.now() - body.startTime),
      totalDurationSec: ((body.totalDurationMs || (Date.now() - body.startTime)) / 1000).toFixed(1),
      phases: (body.phases || []).map((p: { name: string; startTime: number; endTime?: number; success?: boolean; error?: string }) => ({
        name: p.name,
        durationMs: p.endTime ? p.endTime - p.startTime : 0,
        success: p.success ?? false,
        error: p.error,
      })),
      failedChunks: (body.chunks || [])
        .filter((c: { error?: string }) => c.error)
        .map((c: { index: number; key: string; calldataSize: number; error: string; retryCount: number }) => ({
          index: c.index,
          key: c.key?.slice(0, 20) + "...",
          calldataKB: (c.calldataSize / 1024).toFixed(1),
          error: c.error,
          retryCount: c.retryCount,
        })),
      rawChunks: body.chunks,
    };

    // Calculate timing stats
    const confirmedChunks = (body.chunks || []).filter((c: { confirmedAt?: number; submittedAt?: number }) => c.confirmedAt && c.submittedAt);
    if (confirmedChunks.length > 0) {
      const submitTimes = confirmedChunks.map((c: { submittedAt: number }) => c.submittedAt - body.startTime);
      const confirmTimes = confirmedChunks.map((c: { submittedAt: number; confirmedAt: number }) => c.confirmedAt - c.submittedAt);

      stored.avgChunkSubmitMs = Math.round(submitTimes.reduce((a: number, b: number) => a + b, 0) / submitTimes.length);
      stored.avgChunkConfirmMs = Math.round(confirmTimes.reduce((a: number, b: number) => a + b, 0) / confirmTimes.length);
    }

    // Get existing sessions and append
    const sessions = await fetchDiagnostics();
    sessions.push(stored);

    // Keep only last N sessions
    const trimmedSessions = sessions.slice(-MAX_SESSIONS);
    await storeDiagnostics(trimmedSessions);

    console.log(`[upload-diagnostics] Stored session ${stored.sessionId}: ${stored.outcome} (${stored.totalDurationSec}s, ${stored.completedChunks}/${stored.totalChunks} chunks)`);

    return NextResponse.json({
      success: true,
      sessionId: stored.sessionId,
      summary: {
        outcome: stored.outcome,
        duration: stored.totalDurationSec + "s",
        chunks: `${stored.completedChunks}/${stored.totalChunks}`,
        error: stored.errorMessage,
      }
    });
  } catch (error) {
    console.error("[upload-diagnostics] POST error:", error);
    return NextResponse.json(
      { error: "Failed to store diagnostics" },
      { status: 500 }
    );
  }
}
src/app/api/upvote-events/backfill/route.ts
import { NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { createPublicClient, http, decodeAbiParameters } from "viem";
import { base } from "viem/chains";
import { awardAchievements, checkUpvoteGivenAchievements, checkUpvoteReceivedAchievements } from "@/lib/achievements-service";

const UPVOTE_EVENTS_KEY = "upvote-events-index";
const UPVOTE_STORAGE_APP = "0x000000060CEB69D023227DF64CfB75eC37c75B62" as const;
// The actual upvote function selector from transactions is 0x35dc7fbc
const UPVOTE_SELECTOR = "0x35dc7fbc";

// Create public client for Base with reliable RPC
const publicClient = createPublicClient({
  chain: base,
  transport: http("https://base.llamarpc.com", {
    timeout: 60_000,
    retryCount: 3,
    retryDelay: 1000,
  }),
});

interface UpvoteEvent {
  id: string;
  upvoter: string;
  storageKey: string;
  operator: string;
  amount: number;
  timestamp: number;
  transactionHash: string;
  contentKey?: string;
}

interface UpvoteEventsIndex {
  events: UpvoteEvent[];
  lastUpdated: number;
}

// Fetch existing upvote events from KV
async function fetchUpvoteEvents(): Promise<UpvoteEventsIndex> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, UPVOTE_EVENTS_KEY)).limit(1);
    if (!result[0]?.value) return { events: [], lastUpdated: Date.now() };
    return JSON.parse(result[0].value) as UpvoteEventsIndex;
  } catch (error) {
    console.error("[backfill] fetchUpvoteEvents error:", error);
    return { events: [], lastUpdated: Date.now() };
  }
}

// Store upvote events to KV
async function storeUpvoteEvents(data: UpvoteEventsIndex): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: UPVOTE_EVENTS_KEY, value: JSON.stringify(data) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(data) },
    });
    return true;
  } catch (error) {
    console.error("[backfill] storeUpvoteEvents error:", error);
    return false;
  }
}

// POST - Backfill historical upvotes from blockchain
export async function POST() {
  try {
    console.log("[backfill] Starting blockchain backfill...");

    // Get current block number
    const currentBlock = await publicClient.getBlockNumber();

    // Fetch from last ~30 days (~216000 blocks on Base at ~12s/block)
    // Smaller range to avoid RPC limits
    const fromBlock = currentBlock - BigInt(216000);

    console.log(`[backfill] Scanning blocks ${fromBlock} to ${currentBlock}`);

    // Query logs in smaller chunks to avoid RPC limits
    const chunkSize = BigInt(10000);
    const allLogs: Awaited<ReturnType<typeof publicClient.getLogs>> = [];

    for (let start = fromBlock; start < currentBlock; start += chunkSize) {
      const end = start + chunkSize > currentBlock ? currentBlock : start + chunkSize;
      try {
        const logs = await publicClient.getLogs({
          address: UPVOTE_STORAGE_APP,
          fromBlock: start,
          toBlock: end,
        });
        allLogs.push(...logs);
        console.log(`[backfill] Scanned blocks ${start} to ${end}, found ${logs.length} logs`);
      } catch (err) {
        console.error(`[backfill] Error scanning blocks ${start} to ${end}:`, err);
        // Continue with next chunk
      }
    }

    const logs = allLogs;
    console.log(`[backfill] Found ${logs.length} total logs from UpvoteStorageApp`);

    // Get unique transaction hashes (filter out nulls)
    const txHashes = [...new Set(logs.map(log => log.transactionHash).filter((h): h is `0x${string}` => h !== null))];
    console.log(`[backfill] Found ${txHashes.length} unique transactions`);

    // Load existing events to check for duplicates
    const eventsIndex = await fetchUpvoteEvents();
    const existingIds = new Set(eventsIndex.events.map(e => e.id));

    // Process transactions to extract upvote details
    const newEvents: UpvoteEvent[] = [];
    const processedTxs = new Set<string>();
    let duplicateCount = 0;

    // Process in batches
    const batchSize = 10;
    const maxTxs = txHashes.length; // Process all transactions

    for (let i = 0; i < maxTxs; i += batchSize) {
      const batch = txHashes.slice(i, i + batchSize);

      await Promise.all(batch.map(async (txHash) => {
        if (processedTxs.has(txHash)) return;
        processedTxs.add(txHash);

        try {
          const tx = await publicClient.getTransaction({ hash: txHash });

          // Check if this is an upvote transaction
          if (tx && tx.to?.toLowerCase() === UPVOTE_STORAGE_APP.toLowerCase()) {
            const input = tx.input;

            // Check for upvote function selector
            if (input.startsWith(UPVOTE_SELECTOR)) {
              try {
                // Decode the parameters: (strategy, operator, storageKey, scoreDelta, context)
                const params = decodeAbiParameters(
                  [
                    { name: "strategy", type: "address" },
                    { name: "operator", type: "address" },
                    { name: "storageKey", type: "bytes32" },
                    { name: "scoreDelta", type: "int256" },
                    { name: "context", type: "bytes" },
                  ],
                  `0x${input.slice(10)}` as `0x${string}`
                );

                const operator = params[1] as string;
                const storageKey = params[2] as string;
                const scoreDelta = Number(params[3]);

                // Only include positive upvotes
                if (scoreDelta > 0) {
                  const eventId = `${txHash}-${storageKey}`.toLowerCase();

                  // Skip if already exists
                  if (existingIds.has(eventId)) {
                    duplicateCount++;
                    return;
                  }

                  // Get block for timestamp
                  const block = await publicClient.getBlock({ blockNumber: tx.blockNumber! });

                  newEvents.push({
                    id: eventId,
                    upvoter: tx.from.toLowerCase(),
                    storageKey: storageKey.toLowerCase(),
                    operator: operator.toLowerCase(),
                    amount: scoreDelta,
                    timestamp: Number(block.timestamp) * 1000,
                    transactionHash: txHash.toLowerCase(),
                  });

                  console.log(`[backfill] Found upvote: ${tx.from.slice(0, 10)}... gave ${scoreDelta} to ${storageKey.slice(0, 10)}...`);
                }
              } catch {
                // Silently skip transactions that can't be decoded
              }
            }
          }
        } catch (err) {
          console.error(`[backfill] Error processing tx ${txHash}:`, err);
        }
      }));

      // Log progress
      if ((i + batchSize) % 50 === 0) {
        console.log(`[backfill] Processed ${Math.min(i + batchSize, maxTxs)}/${maxTxs} transactions...`);
      }
    }

    console.log(`[backfill] Found ${newEvents.length} new events, ${duplicateCount} duplicates skipped`);

    // Add new events to the index
    if (newEvents.length > 0) {
      eventsIndex.events.push(...newEvents);
      eventsIndex.lastUpdated = Date.now();

      await storeUpvoteEvents(eventsIndex);
      console.log(`[backfill] Stored ${eventsIndex.events.length} total events`);
    }

    // Award achievements to all upvoters based on their total upvotes GIVEN
    const upvoterTotals = new Map<string, number>();
    for (const event of eventsIndex.events) {
      const key = event.upvoter.toLowerCase();
      upvoterTotals.set(key, (upvoterTotals.get(key) || 0) + event.amount);
    }

    const achievementResults: { address: string; awarded: string[]; type: string }[] = [];
    for (const [address, totalUpvotesGiven] of upvoterTotals.entries()) {
      const achievementsToAward = checkUpvoteGivenAchievements({ totalUpvotesGiven });
      if (achievementsToAward.length > 0) {
        const result = await awardAchievements(address, achievementsToAward);
        if (result.awarded.length > 0) {
          achievementResults.push({ address, awarded: result.awarded, type: "upvotes-given" });
          console.log(`[backfill] Awarded upvote-given achievements to ${address}:`, result.awarded);
        }
      }
    }

    // Award achievements to all content creators based on their total upvotes RECEIVED
    const creatorTotals = new Map<string, number>();
    for (const event of eventsIndex.events) {
      const key = event.operator.toLowerCase();
      creatorTotals.set(key, (creatorTotals.get(key) || 0) + event.amount);
    }

    for (const [address, totalUpvotesReceived] of creatorTotals.entries()) {
      const achievementsToAward = checkUpvoteReceivedAchievements({ totalUpvotesReceived });
      if (achievementsToAward.length > 0) {
        const result = await awardAchievements(address, achievementsToAward);
        if (result.awarded.length > 0) {
          achievementResults.push({ address, awarded: result.awarded, type: "upvotes-received" });
          console.log(`[backfill] Awarded upvote-received achievements to ${address}:`, result.awarded);
        }
      }
    }

    return NextResponse.json({
      success: true,
      newEventsAdded: newEvents.length,
      duplicatesSkipped: duplicateCount,
      totalEvents: eventsIndex.events.length,
      achievementsAwarded: achievementResults,
      blocksScanned: {
        from: fromBlock.toString(),
        to: currentBlock.toString(),
      },
    });
  } catch (error) {
    console.error("[backfill] Error:", error);
    return NextResponse.json(
      { error: "Failed to backfill upvote events", details: String(error) },
      { status: 500 }
    );
  }
}

// GET - Check backfill status
export async function GET() {
  try {
    const eventsIndex = await fetchUpvoteEvents();

    return NextResponse.json({
      success: true,
      totalEvents: eventsIndex.events.length,
      lastUpdated: eventsIndex.lastUpdated,
      oldestEvent: eventsIndex.events.length > 0
        ? Math.min(...eventsIndex.events.map(e => e.timestamp))
        : null,
      newestEvent: eventsIndex.events.length > 0
        ? Math.max(...eventsIndex.events.map(e => e.timestamp))
        : null,
    });
  } catch (error) {
    console.error("[backfill] GET error:", error);
    return NextResponse.json(
      { error: "Failed to get backfill status" },
      { status: 500 }
    );
  }
}
src/app/api/upvote-events/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { awardAchievements, checkUpvoteGivenAchievements, checkUpvoteReceivedAchievements } from "@/lib/achievements-service";

const UPVOTE_EVENTS_KEY = "upvote-events-index";

export type UpvoteEvent = {
  id: string; // txHash + storageKey for uniqueness
  upvoter: string;
  storageKey: string;
  operator: string;
  amount: number;
  timestamp: number;
  transactionHash: string;
  contentKey?: string; // Optional reference to content
};

interface UpvoteEventsIndex {
  events: UpvoteEvent[];
  lastUpdated: number;
}

// Fetch all upvote events from KV
async function fetchUpvoteEvents(): Promise<UpvoteEventsIndex> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, UPVOTE_EVENTS_KEY)).limit(1);
    if (!result[0]?.value) return { events: [], lastUpdated: Date.now() };
    return JSON.parse(result[0].value) as UpvoteEventsIndex;
  } catch (error) {
    console.error("[upvote-events] fetchUpvoteEvents error:", error);
    return { events: [], lastUpdated: Date.now() };
  }
}

// Store upvote events to KV
async function storeUpvoteEvents(data: UpvoteEventsIndex): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: UPVOTE_EVENTS_KEY, value: JSON.stringify(data) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(data) },
    });
    return true;
  } catch (error) {
    console.error("[upvote-events] storeUpvoteEvents error:", error);
    return false;
  }
}

// GET - Fetch all upvote events, aggregated by upvoter
export async function GET() {
  try {
    console.log("[upvote-events] Fetching from KV storage...");

    const eventsIndex = await fetchUpvoteEvents();
    const events = eventsIndex.events;

    console.log(`[upvote-events] Found ${events.length} events in KV`);

    // Aggregate by upvoter
    const upvoterStats = new Map<string, {
      totalUpvotes: number;
      items: Array<{ storageKey: string; operator: string; amount: number; timestamp: number; contentKey?: string }>
    }>();

    for (const event of events) {
      const upvoterKey = event.upvoter.toLowerCase();
      const existing = upvoterStats.get(upvoterKey) || { totalUpvotes: 0, items: [] };
      existing.totalUpvotes += event.amount;
      existing.items.push({
        storageKey: event.storageKey,
        operator: event.operator,
        amount: event.amount,
        timestamp: event.timestamp,
        contentKey: event.contentKey,
      });
      upvoterStats.set(upvoterKey, existing);
    }

    // Convert to sorted array
    const topUpvoters = Array.from(upvoterStats.entries())
      .map(([address, stats]) => ({
        address,
        totalUpvotes: stats.totalUpvotes,
        itemsUpvoted: stats.items,
      }))
      .sort((a, b) => b.totalUpvotes - a.totalUpvotes);

    console.log(`[upvote-events] Returning ${topUpvoters.length} unique upvoters`);

    return NextResponse.json({
      success: true,
      topUpvoters,
      totalEvents: events.length,
      lastUpdated: eventsIndex.lastUpdated,
    });
  } catch (error) {
    console.error("[upvote-events] Error:", error);
    return NextResponse.json(
      {
        error: "Failed to fetch upvote events",
        topUpvoters: [],
        totalEvents: 0,
      },
      { status: 500 }
    );
  }
}

// POST - Record a new upvote event
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { upvoter, storageKey, operator, amount, transactionHash, contentKey } = body;

    if (!upvoter || !storageKey || !operator || !amount || !transactionHash) {
      return NextResponse.json(
        { error: "Missing required fields: upvoter, storageKey, operator, amount, transactionHash" },
        { status: 400 }
      );
    }

    console.log(`[upvote-events] Recording upvote: ${upvoter} gave ${amount} to ${storageKey.slice(0, 10)}...`);

    const eventsIndex = await fetchUpvoteEvents();

    // Generate unique ID
    const eventId = `${transactionHash}-${storageKey}`.toLowerCase();

    // Check for duplicate
    const existingEvent = eventsIndex.events.find(e => e.id === eventId);
    if (existingEvent) {
      console.log(`[upvote-events] Duplicate event ${eventId}, skipping`);
      return NextResponse.json({ success: true, duplicate: true });
    }

    // Add new event
    const newEvent: UpvoteEvent = {
      id: eventId,
      upvoter: upvoter.toLowerCase(),
      storageKey: storageKey.toLowerCase(),
      operator: operator.toLowerCase(),
      amount: Number(amount),
      timestamp: Date.now(),
      transactionHash: transactionHash.toLowerCase(),
      contentKey: contentKey || undefined,
    };

    eventsIndex.events.push(newEvent);
    eventsIndex.lastUpdated = Date.now();

    await storeUpvoteEvents(eventsIndex);

    // Calculate total upvotes GIVEN by the upvoter for achievement checking
    const userUpvotes = eventsIndex.events.filter(
      e => e.upvoter.toLowerCase() === upvoter.toLowerCase()
    );
    const totalUpvotesGiven = userUpvotes.reduce((sum, e) => sum + e.amount, 0);

    // Check and award upvote-given achievements to the upvoter
    const givenAchievementsToAward = checkUpvoteGivenAchievements({ totalUpvotesGiven });
    let awardedAchievements: string[] = [];

    if (givenAchievementsToAward.length > 0) {
      const result = await awardAchievements(upvoter, givenAchievementsToAward);
      awardedAchievements = result.awarded;
      if (awardedAchievements.length > 0) {
        console.log(`[upvote-events] Awarded upvote-given achievements to ${upvoter}:`, awardedAchievements);
      }
    }

    // Calculate total upvotes RECEIVED by the content creator (operator)
    const creatorUpvotes = eventsIndex.events.filter(
      e => e.operator.toLowerCase() === operator.toLowerCase()
    );
    const totalUpvotesReceived = creatorUpvotes.reduce((sum, e) => sum + e.amount, 0);

    // Check and award upvote-received achievements to the content creator
    const receivedAchievementsToAward = checkUpvoteReceivedAchievements({ totalUpvotesReceived });
    let creatorAwardedAchievements: string[] = [];

    if (receivedAchievementsToAward.length > 0) {
      const result = await awardAchievements(operator, receivedAchievementsToAward);
      creatorAwardedAchievements = result.awarded;
      if (creatorAwardedAchievements.length > 0) {
        console.log(`[upvote-events] Awarded upvote-received achievements to ${operator}:`, creatorAwardedAchievements);
      }
    }

    console.log(`[upvote-events] Recorded event. Total events: ${eventsIndex.events.length}, upvoter total: ${totalUpvotesGiven}, creator total: ${totalUpvotesReceived}`);

    return NextResponse.json({
      success: true,
      eventId,
      totalEvents: eventsIndex.events.length,
      awardedAchievements,
      creatorAwardedAchievements,
    });
  } catch (error) {
    console.error("[upvote-events] POST error:", error);
    return NextResponse.json(
      { error: "Failed to record upvote event" },
      { status: 500 }
    );
  }
}
src/app/api/upvotes/route.ts
import { NextRequest, NextResponse } from "next/server";
import { createPublicClient, http } from "viem";
import { base } from "viem/chains";

// Contract addresses
const SCORE_CONTRACT = "0x0000000FA09B022E5616E5a173b4b67FA2FBcF28" as const;
const PURE_ALPHA_STRATEGY = "0x00000001b1bcdeddeafd5296aaf4f3f3e21ae876" as const;
const UPVOTE_STORAGE_APP = "0x000000060CEB69D023227DF64CfB75eC37c75B62" as const;

// ABI for Score contract (querying)
const SCORE_ABI = [
  {
    name: "getAppStrategyKeyScores",
    type: "function",
    stateMutability: "view",
    inputs: [
      { name: "app", type: "address" },
      { name: "strategy", type: "address" },
      { name: "scoreKeys", type: "bytes32[]" },
    ],
    outputs: [{ name: "counts", type: "int256[]" }],
  },
] as const;

// Create public client for Base
const publicClient = createPublicClient({
  chain: base,
  transport: http("https://mainnet.base.org"),
});

// POST - Fetch upvote counts for multiple items
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { scoreKeys, contentKeys } = body;

    if (!scoreKeys || !Array.isArray(scoreKeys) || scoreKeys.length === 0) {
      return NextResponse.json({ error: "scoreKeys required" }, { status: 400 });
    }

    console.log("[upvotes] Fetching counts for", scoreKeys.length, "items");

    // Query the Score contract
    const result = await publicClient.readContract({
      address: SCORE_CONTRACT,
      abi: SCORE_ABI,
      functionName: "getAppStrategyKeyScores",
      args: [
        UPVOTE_STORAGE_APP,
        PURE_ALPHA_STRATEGY,
        scoreKeys as `0x${string}`[],
      ],
    });

    // Convert BigInt results to numbers
    const counts = (result as bigint[]).map((count) => Number(count));

    console.log("[upvotes] Fetched counts:", counts);

    return NextResponse.json({
      success: true,
      counts,
      contentKeys,
    });
  } catch (error) {
    console.error("[upvotes] Error:", error);
    return NextResponse.json(
      { error: "Failed to fetch upvote counts", counts: [] },
      { status: 500 }
    );
  }
}

// GET - Fetch single upvote count
export async function GET(request: NextRequest) {
  const scoreKey = request.nextUrl.searchParams.get("scoreKey");

  if (!scoreKey) {
    return NextResponse.json({ error: "scoreKey required" }, { status: 400 });
  }

  try {
    const result = await publicClient.readContract({
      address: SCORE_CONTRACT,
      abi: SCORE_ABI,
      functionName: "getAppStrategyKeyScores",
      args: [
        UPVOTE_STORAGE_APP,
        PURE_ALPHA_STRATEGY,
        [scoreKey as `0x${string}`],
      ],
    });

    const count = Number((result as bigint[])[0] || 0n);

    return NextResponse.json({
      success: true,
      count,
      scoreKey,
    });
  } catch (error) {
    console.error("[upvotes] Error:", error);
    return NextResponse.json(
      { error: "Failed to fetch upvote count", count: 0 },
      { status: 500 }
    );
  }
}
src/app/api/user-net-link/route.ts
import { NextRequest, NextResponse } from "next/server";
import { kvGet, kvSet } from "@/neynar-db-sdk";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { awardAchievement } from "@/lib/achievements-service";
import type { MemberRegistry } from "@/lib/net-protocol";

// KV key prefix for user net links
const NET_LINK_KEY_PREFIX = "user-net-link:";
const REGISTRY_KEY = "member-registry";

// Get all linked addresses for a user (including FID-linked memberships)
async function getAllLinkedAddresses(address: string, fid?: number): Promise<string[]> {
  const addresses = new Set<string>([address.toLowerCase()]);

  try {
    const result = await db.select().from(kv).where(eq(kv.key, REGISTRY_KEY)).limit(1);
    if (!result[0]?.value) return [address.toLowerCase()];

    const registry = JSON.parse(result[0].value) as MemberRegistry;

    // Find all memberships for this user
    for (const member of registry.members) {
      if (!member.address) continue;
      const memberAddr = member.address.toLowerCase();
      const linkedAddrs = member.linkedAddresses?.filter(a => a).map(a => a.toLowerCase()) || [];

      // Check if this member belongs to the user (by address, linked address, or FID)
      if (
        memberAddr === address.toLowerCase() ||
        linkedAddrs.includes(address.toLowerCase()) ||
        (fid && member.fid === fid)
      ) {
        addresses.add(memberAddr);
        linkedAddrs.forEach(a => addresses.add(a));
      }
    }
  } catch (error) {
    console.error("[getAllLinkedAddresses] Error:", error);
  }

  return Array.from(addresses);
}

interface NetLinkData {
  url: string;
  label: string;
  updatedAt: number;
}

// Validate Net Protocol URL
function isValidNetProtocolUrl(url: string): boolean {
  try {
    const parsed = new URL(url);
    // Accept URLs from netprotocol.app, storedon.net, or net protocol storage URLs
    const validHosts = [
      "netprotocol.app",
      "www.netprotocol.app",
      "storedon.net",
      "www.storedon.net",
    ];
    return validHosts.some(
      (host) => parsed.hostname === host || parsed.hostname.endsWith(`.${host}`)
    );
  } catch {
    return false;
  }
}

// GET - Fetch user's net link (checks all linked addresses)
export async function GET(request: NextRequest) {
  const address = request.nextUrl.searchParams.get("address");
  const fidStr = request.nextUrl.searchParams.get("fid");
  const fid = fidStr ? parseInt(fidStr, 10) : undefined;

  if (!address) {
    return NextResponse.json({ error: "Address required" }, { status: 400 });
  }

  try {
    // Get all linked addresses for this user
    const allAddresses = await getAllLinkedAddresses(address, fid);

    // Check each address for a net link (first found wins)
    for (const addr of allAddresses) {
      const key = `${NET_LINK_KEY_PREFIX}${addr}`;
      const data = await kvGet(key);

      if (data) {
        const linkData = JSON.parse(data) as NetLinkData;
        return NextResponse.json({
          success: true,
          link: linkData,
          foundOnAddress: addr,
          allAddresses,
        });
      }
    }

    return NextResponse.json({ success: true, link: null, allAddresses });
  } catch (error) {
    console.error("Failed to fetch net link:", error);
    return NextResponse.json(
      { success: false, error: "Failed to fetch link" },
      { status: 500 }
    );
  }
}

// POST - Save user's net link (syncs to all linked addresses)
export async function POST(request: NextRequest) {
  try {
    const { address, url, label, fid } = await request.json();

    if (!address) {
      return NextResponse.json({ error: "Address required" }, { status: 400 });
    }

    if (!url || !label) {
      return NextResponse.json(
        { error: "URL and label required" },
        { status: 400 }
      );
    }

    // Validate Net Protocol URL
    if (!isValidNetProtocolUrl(url)) {
      return NextResponse.json(
        {
          success: false,
          error: "Invalid Net Protocol URL. Please enter a valid link from netprotocol.app or storedon.net",
        },
        { status: 400 }
      );
    }

    const linkData: NetLinkData = {
      url,
      label,
      updatedAt: Date.now(),
    };

    // Get all linked addresses and save to each one (auto-sync across platforms)
    const allAddresses = await getAllLinkedAddresses(address, fid);

    for (const addr of allAddresses) {
      const key = `${NET_LINK_KEY_PREFIX}${addr}`;
      await kvSet(key, JSON.stringify(linkData));
    }

    console.log(`[user-net-link] Synced link to ${allAddresses.length} address(es):`, allAddresses);

    // Award the "linked" achievement to all addresses
    const achievementResults = await Promise.all(
      allAddresses.map(addr => awardAchievement(addr, "linked"))
    );
    const anyAwarded = achievementResults.some(r => r.awarded);

    return NextResponse.json({
      success: true,
      link: linkData,
      syncedToAddresses: allAddresses,
      achievementAwarded: anyAwarded,
    });
  } catch (error) {
    console.error("Failed to save net link:", error);
    return NextResponse.json(
      { success: false, error: "Failed to save link" },
      { status: 500 }
    );
  }
}

// DELETE - Remove user's net link
export async function DELETE(request: NextRequest) {
  try {
    const { address } = await request.json();

    if (!address) {
      return NextResponse.json({ error: "Address required" }, { status: 400 });
    }

    const key = `${NET_LINK_KEY_PREFIX}${address.toLowerCase()}`;
    await kvSet(key, ""); // Clear the value

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error("Failed to delete net link:", error);
    return NextResponse.json(
      { success: false, error: "Failed to delete link" },
      { status: 500 }
    );
  }
}
src/app/api/user-stats/route.ts
import { NextRequest, NextResponse } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import {
  UserStreak,
  StreaksIndex,
  UserAchievements,
  AchievementsIndex,
  AchievementId,
  ACHIEVEMENTS,
} from "@/lib/net-protocol";

const STREAKS_KV_KEY = "net-library-streaks";
const ACHIEVEMENTS_KV_KEY = "net-library-achievements";

// Helper to fetch existing index from KV database
async function fetchIndex<T>(kvKey: string): Promise<T | null> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, kvKey)).limit(1);
    if (!result[0]?.value) return null;
    return JSON.parse(result[0].value) as T;
  } catch {
    return null;
  }
}

// Helper to store index to KV database
async function storeIndex(kvKey: string, data: unknown): Promise<boolean> {
  try {
    await db.insert(kv).values({
      key: kvKey,
      value: JSON.stringify(data),
    }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(data) },
    });
    return true;
  } catch (error) {
    console.error("storeIndex error:", error);
    return false;
  }
}

// GET - Fetch user stats
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const address = searchParams.get("address")?.toLowerCase();
  const type = searchParams.get("type"); // "streak" | "achievements" | "all"

  if (!address) {
    return NextResponse.json({ error: "Address required" }, { status: 400 });
  }

  const result: { streak?: UserStreak; achievements?: UserAchievements } = {};

  if (type === "streak" || type === "all" || !type) {
    const streaksIndex = await fetchIndex<StreaksIndex>(STREAKS_KV_KEY);
    result.streak = streaksIndex?.users[address] || {
      address,
      currentStreak: 0,
      longestStreak: 0,
      lastReadDate: "",
      totalDaysActive: 0,
      readingHistory: [],
    };
  }

  if (type === "achievements" || type === "all" || !type) {
    const achievementsIndex = await fetchIndex<AchievementsIndex>(ACHIEVEMENTS_KV_KEY);
    result.achievements = achievementsIndex?.users[address] || {
      address,
      earnedAchievements: [],
    };
  }

  return NextResponse.json(result);
}

// POST - Update user stats (log reading, unlock achievement)
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { address, action, data } = body;

    if (!address) {
      return NextResponse.json({ error: "Address required" }, { status: 400 });
    }

    const normalizedAddress = address.toLowerCase();

    // Handle different actions
    switch (action) {
      case "log-reading": {
        // User read something today - update streak
        const streaksIndex: StreaksIndex = (await fetchIndex<StreaksIndex>(STREAKS_KV_KEY)) || {
          users: {},
          topStreaks: [],
          lastUpdated: Date.now(),
        };

        const today = new Date().toISOString().split("T")[0];
        const userStreak = streaksIndex.users[normalizedAddress] || {
          address: normalizedAddress,
          currentStreak: 0,
          longestStreak: 0,
          lastReadDate: "",
          totalDaysActive: 0,
          readingHistory: [],
        };

        // Check if already logged today
        if (userStreak.lastReadDate === today) {
          return NextResponse.json({ message: "Already logged today", streak: userStreak });
        }

        // Calculate new streak
        const yesterday = new Date();
        yesterday.setDate(yesterday.getDate() - 1);
        const yesterdayStr = yesterday.toISOString().split("T")[0];

        let newStreak = 1;
        if (userStreak.lastReadDate === yesterdayStr) {
          newStreak = userStreak.currentStreak + 1;
        }

        // Update user streak
        userStreak.currentStreak = newStreak;
        userStreak.longestStreak = Math.max(userStreak.longestStreak, newStreak);
        userStreak.lastReadDate = today;
        userStreak.totalDaysActive = (userStreak.totalDaysActive || 0) + 1;

        // Keep last 30 days of history
        userStreak.readingHistory = [
          ...userStreak.readingHistory.filter((d) => {
            const date = new Date(d);
            const thirtyDaysAgo = new Date();
            thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
            return date >= thirtyDaysAgo;
          }),
          today,
        ];

        streaksIndex.users[normalizedAddress] = userStreak;
        streaksIndex.lastUpdated = Date.now();

        await storeIndex(STREAKS_KV_KEY, streaksIndex);

        // Streak achievements were removed - streaks are now tracked but don't unlock achievements
        const newAchievements: AchievementId[] = [];

        return NextResponse.json({
          success: true,
          streak: userStreak,
          newAchievements,
        });
      }

      case "unlock-achievement": {
        const { achievementId } = data;
        if (!achievementId || !ACHIEVEMENTS.find((a) => a.id === achievementId)) {
          return NextResponse.json({ error: "Invalid achievement ID" }, { status: 400 });
        }

        const achievementsIndex = (await fetchIndex<AchievementsIndex>(ACHIEVEMENTS_KV_KEY)) || {
          users: {},
          recentUnlocks: [],
          lastUpdated: Date.now(),
        };

        const userAchievements = achievementsIndex.users[normalizedAddress] || {
          address: normalizedAddress,
          earnedAchievements: [],
        };

        // Check if already earned
        if (userAchievements.earnedAchievements.some((a) => a.id === achievementId)) {
          return NextResponse.json({ message: "Already earned", achievements: userAchievements });
        }

        // Add achievement
        const earnedAt = Date.now();
        userAchievements.earnedAchievements.push({ id: achievementId, earnedAt });

        // Update recent unlocks (keep last 50)
        achievementsIndex.recentUnlocks = [
          { address: normalizedAddress, achievementId, earnedAt },
          ...achievementsIndex.recentUnlocks.slice(0, 49),
        ];

        achievementsIndex.users[normalizedAddress] = userAchievements;
        achievementsIndex.lastUpdated = Date.now();

        await storeIndex(ACHIEVEMENTS_KV_KEY, achievementsIndex);

        return NextResponse.json({
          success: true,
          achievements: userAchievements,
          unlockedAchievement: ACHIEVEMENTS.find((a) => a.id === achievementId),
        });
      }

      case "check-achievements": {
        // Check and award any earned achievements based on stats
        const { stats } = data;
        const achievementsIndex = (await fetchIndex<AchievementsIndex>(ACHIEVEMENTS_KV_KEY)) || {
          users: {},
          recentUnlocks: [],
          lastUpdated: Date.now(),
        };

        const userAchievements = achievementsIndex.users[normalizedAddress] || {
          address: normalizedAddress,
          earnedAchievements: [],
        };

        const earnedIds = new Set(userAchievements.earnedAchievements.map((a) => a.id));
        const newlyEarned: AchievementId[] = [];
        const earnedAt = Date.now();

        // Check upload achievements
        if (stats.uploads >= 1 && !earnedIds.has("first-upload")) {
          newlyEarned.push("first-upload");
        }
        if (stats.uploads >= 5 && !earnedIds.has("contributor-5")) {
          newlyEarned.push("contributor-5");
        }
        if (stats.uploads >= 25 && !earnedIds.has("contributor-25")) {
          newlyEarned.push("contributor-25");
        }
        if (stats.uploads >= 100 && !earnedIds.has("contributor-100")) {
          newlyEarned.push("contributor-100");
        }

        // Check member number achievements
        if (stats.memberId && stats.memberId <= 100 && !earnedIds.has("founding-member")) {
          newlyEarned.push("founding-member");
        }
        if (stats.memberId && stats.memberId <= 1000 && !earnedIds.has("og-member")) {
          newlyEarned.push("og-member");
        }

        // Add new achievements
        for (const id of newlyEarned) {
          userAchievements.earnedAchievements.push({ id, earnedAt });
          achievementsIndex.recentUnlocks.unshift({ address: normalizedAddress, achievementId: id, earnedAt });
        }

        if (newlyEarned.length > 0) {
          achievementsIndex.recentUnlocks = achievementsIndex.recentUnlocks.slice(0, 50);
          achievementsIndex.users[normalizedAddress] = userAchievements;
          achievementsIndex.lastUpdated = Date.now();
          await storeIndex(ACHIEVEMENTS_KV_KEY, achievementsIndex);
        }

        return NextResponse.json({
          success: true,
          achievements: userAchievements,
          newlyEarned: newlyEarned.map((id) => ACHIEVEMENTS.find((a) => a.id === id)),
        });
      }

      default:
        return NextResponse.json({ error: "Invalid action" }, { status: 400 });
    }
  } catch (error) {
    console.error("User stats error:", error);
    return NextResponse.json({ error: "Failed to update stats" }, { status: 500 });
  }
}
src/app/api/user-upvotes/route.ts
import { NextRequest, NextResponse } from "next/server";
import { kvGet, kvSet } from "@/neynar-db-sdk";

// KV keys for user upvotes
const USER_UPVOTES_KEY = "user-upvotes"; // Map of address -> total upvotes received
const USER_UPVOTE_EVENTS_KEY = "user-upvote-events"; // List of all upvote events

interface UserUpvoteEvent {
  upvoter: string; // Address of person giving the upvote
  targetUser: string; // Address of person receiving the upvote
  amount: number; // Upvote count (usually 1)
  timestamp: number;
}

interface UserUpvotesData {
  upvotesByUser: Record<string, number>; // targetAddress -> total upvotes
  lastUpdated: number;
}

interface UserUpvoteEventsData {
  events: UserUpvoteEvent[];
  lastUpdated: number;
}

// GET - Fetch upvote counts for users
// Query params: addresses (comma-separated list of addresses)
export async function GET(request: NextRequest) {
  try {
    const addressesParam = request.nextUrl.searchParams.get("addresses");

    // Fetch all user upvotes data
    const data = await kvGet(USER_UPVOTES_KEY);
    const upvotesData: UserUpvotesData = data
      ? JSON.parse(data)
      : { upvotesByUser: {}, lastUpdated: Date.now() };

    // If specific addresses requested, filter
    if (addressesParam) {
      const addresses = addressesParam.split(",").map(a => a.toLowerCase().trim());
      const counts: Record<string, number> = {};

      for (const addr of addresses) {
        counts[addr] = upvotesData.upvotesByUser[addr] || 0;
      }

      return NextResponse.json({
        success: true,
        counts,
        lastUpdated: upvotesData.lastUpdated,
      });
    }

    // Return all upvote counts
    return NextResponse.json({
      success: true,
      upvotesByUser: upvotesData.upvotesByUser,
      lastUpdated: upvotesData.lastUpdated,
    });
  } catch (error) {
    console.error("[user-upvotes] GET error:", error);
    return NextResponse.json(
      { error: "Failed to fetch user upvotes", counts: {} },
      { status: 500 }
    );
  }
}

// POST - Record a new user upvote
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { upvoter, targetUser, amount = 1 } = body;

    if (!upvoter || !targetUser) {
      return NextResponse.json(
        { error: "upvoter and targetUser addresses required" },
        { status: 400 }
      );
    }

    const upvoterLower = upvoter.toLowerCase();
    const targetLower = targetUser.toLowerCase();

    // Can't upvote yourself
    if (upvoterLower === targetLower) {
      return NextResponse.json(
        { error: "Cannot upvote yourself" },
        { status: 400 }
      );
    }

    // Fetch existing upvotes data
    const data = await kvGet(USER_UPVOTES_KEY);
    const upvotesData: UserUpvotesData = data
      ? JSON.parse(data)
      : { upvotesByUser: {}, lastUpdated: Date.now() };

    // Update the count for the target user
    upvotesData.upvotesByUser[targetLower] =
      (upvotesData.upvotesByUser[targetLower] || 0) + amount;
    upvotesData.lastUpdated = Date.now();

    // Save updated data
    await kvSet(USER_UPVOTES_KEY, JSON.stringify(upvotesData));

    // Also record the event for history tracking
    const eventsData = await kvGet(USER_UPVOTE_EVENTS_KEY);
    const events: UserUpvoteEventsData = eventsData
      ? JSON.parse(eventsData)
      : { events: [], lastUpdated: Date.now() };

    events.events.push({
      upvoter: upvoterLower,
      targetUser: targetLower,
      amount,
      timestamp: Date.now(),
    });
    events.lastUpdated = Date.now();

    // Keep only last 10000 events to prevent unbounded growth
    if (events.events.length > 10000) {
      events.events = events.events.slice(-10000);
    }

    await kvSet(USER_UPVOTE_EVENTS_KEY, JSON.stringify(events));

    return NextResponse.json({
      success: true,
      newCount: upvotesData.upvotesByUser[targetLower],
      targetUser: targetLower,
    });
  } catch (error) {
    console.error("[user-upvotes] POST error:", error);
    return NextResponse.json(
      { error: "Failed to record upvote" },
      { status: 500 }
    );
  }
}
src/app/api/v1/agent-skill/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Agent Skill Document API
 *
 * GET /api/v1/agent-skill — Returns JSON document describing the Net Library API for other agents
 * OPTIONS — CORS preflight
 *
 * This document is designed to be read by AI agents to understand how to interact
 * with the Net Library API.
 */

import {
  handleOptions,
  corsResponse,
  USDC_CONTRACT,
  TREASURY_ADDRESS,
  PRICING,
  ERC8004_REGISTRY,
} from "@/lib/agent-auth";

// Get base URL from environment
function getBaseUrl(): string {
  const url = process.env.NEXT_PUBLIC_URL || process.env.VERCEL_URL;
  if (url) {
    return url.startsWith("http") ? url : `https://${url}`;
  }
  return "https://miniapp-generator-fid-282520-251210015136529.neynar.app";
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/v1/agent-skill — Agent skill document
 *
 * Returns a JSON document that other agents can read to learn how to use the Net Library API.
 */
export async function GET() {
  const baseUrl = getBaseUrl();

  return corsResponse({
    name: "Net Library",
    description: "A decentralized digital library for storing, organizing, and sharing knowledge. Members can upload files, create curated stacks, archive social posts, and collaborate through the API.",
    version: "1.0.0",
    baseUrl,

    getting_started: {
      step_1: `Send $2 USDC to treasury ${TREASURY_ADDRESS} on Base`,
      step_2: "POST /api/v1/agents/membership with { selfRegister: true, name: 'Your Agent Name', address: '0x...', txHash: '0x...' }",
      step_3: "Save the API key from the response — it is shown only once",
      step_4: "Use Authorization: Bearer <apiKey> on all authenticated endpoints",
      note: "You are now a Net Library member with upload access, an ENS subname (e.g. 22.netlibrary.eth), and full API access",
    },

    api_key_management: {
      check: "GET /api/v1/membership/api-key — pass Authorization: Bearer <token>; returns prefix and status",
      regenerate: "POST /api/v1/membership/api-key with { regenerate: true } — creates a new key, invalidates current one",
      revoke: "DELETE /api/v1/membership/api-key — permanently revoke your API key",
    },

    auth: {
      type: "bearer",
      description: "All authenticated endpoints require a Bearer token in the Authorization header.",
      header: "Authorization: Bearer <api_key>",
      howToGetKey: "Self-register via POST /api/v1/agents/membership with { selfRegister: true } — no admin needed. See getting_started above.",
      keyFormat: "nlk_<32 random hex chars>",
      legacyFormat: "[REDACTED-API-KEY] (admin-issued keys, still supported)",
    },

    pricing: {
      currency: "USDC",
      chain: "Base (Chain ID 8453)",
      usdcContract: USDC_CONTRACT,
      treasuryAddress: TREASURY_ADDRESS,
      items: {
        membership: {
          price: PRICING.MEMBERSHIP,
          description: "One-time fee to become a library member. Grants upload privileges and an ENS subname (X.netlibrary.eth).",
        },
        unlimitedStoragePass: {
          price: PRICING.STORAGE_PASS,
          description: "One-time fee for unlimited storage. Without this, members have a 15MB limit per file.",
        },
        stackUnlock: {
          price: PRICING.STACK_UNLOCK,
          description: "Unlock access to a premium stack created by another member.",
        },
        gridUnlock: {
          price: PRICING.GRID_UNLOCK,
          description: "Unlock access to a premium grid created by another member.",
        },
        stackCreationNonMember: {
          price: PRICING.STACK_CREATION_NON_MEMBER,
          description: "Non-members can create a public stack for this fee.",
        },
        premiumUpload: {
          price: PRICING.PREMIUM_UPLOAD_PER_MB,
          unit: "per MB over 15MB",
          description: "Members without unlimited storage pay per-MB for large files.",
        },
      },
    },

    endpoints: {
      public_read: {
        description: "Public read endpoints. No authentication required. All support CORS.",
        endpoints: [
          {
            method: "GET",
            path: "/api/v1/library",
            description: "Browse the library catalog with pagination and filtering.",
            params: {
              page: "Page number (default: 1)",
              limit: "Items per page (default: 20, max: 50)",
              category: "Filter by category",
              mediaType: "Filter by media type (pdf, epub, etc.)",
              sort: "Sort order: newest, oldest, title",
              hidden: "Include hidden items (true/false)",
              search: "Search in title/author",
            },
          },
          {
            method: "GET",
            path: "/api/v1/library/{contentKey}",
            description: "Get a single library item with metadata, comment count, and stack membership.",
          },
          {
            method: "GET",
            path: "/api/v1/stacks",
            description: "Browse public stacks with pagination.",
            params: {
              page: "Page number",
              limit: "Items per page (max: 50)",
              owner: "Filter by owner address",
              sort: "Sort: newest, oldest, name, popular",
            },
          },
          {
            method: "GET",
            path: "/api/v1/stacks/{stackId}",
            description: "Get a single stack with all its items.",
          },
          {
            method: "GET",
            path: "/api/v1/search",
            description: "Search library items and stacks. At least one filter required.",
            params: {
              q: "Search query (matches title, author)",
              category: "Filter by category",
              author: "Filter by author",
              mediaType: "Filter by media type",
              limit: "Max results (default: 20, max: 50)",
            },
          },
          {
            method: "GET",
            path: "/api/v1/comments/{contentKey}",
            description: "Get comments for a library item.",
            params: {
              parentId: "Get replies to a specific comment (omit for top-level)",
            },
          },
          {
            method: "GET",
            path: "/api/v1/stats",
            description: "Get library statistics: item counts, member counts, stack counts, categories.",
          },
        ],
      },

      agent_management: {
        description: "Agent registration and management. Requires authentication.",
        endpoints: [
          {
            method: "POST",
            path: "/api/v1/agents",
            description: "Register a new agent (admin only). Returns API key.",
            auth: "Admin",
            body: {
              id: "Unique agent ID (lowercase alphanumeric + hyphens)",
              name: "Display name",
              permissions: "Array of permissions",
              address: "Optional: wallet address",
              fid: "Optional: Farcaster ID",
            },
          },
          {
            method: "GET",
            path: "/api/v1/agents",
            description: "List all registered agents (admin only).",
            auth: "Admin",
          },
          {
            method: "PUT",
            path: "/api/v1/agents",
            description: "Update agent profile. Admins can update any agent; others can only update themselves.",
            auth: "Bearer token",
          },
          {
            method: "GET",
            path: "/api/v1/agents/me",
            description: "Get your own agent profile with widgets and membership info.",
            auth: "Bearer token",
          },
          {
            method: "GET",
            path: "/api/v1/agents/membership",
            description: "Check your membership status.",
            auth: "Bearer token",
          },
          {
            method: "POST",
            path: "/api/v1/agents/membership",
            description: "Purchase membership with USDC payment (authenticated), OR self-register + get API key in one step (no auth required).",
            auth: "Bearer token (paid purchase) OR none (selfRegister: true)",
            modes: {
              selfRegister: {
                description: "One-step registration: pays $2 USDC, creates agent, creates member, mints ENS, returns API key.",
                auth: "None required",
                body: {
                  selfRegister: true,
                  name: "required",
                  address: "required (wallet — must be sender of USDC tx)",
                  txHash: "required ($2 USDC to treasury)",
                  description: "optional",
                  fid: "optional Farcaster ID",
                  pfpUrl: "optional profile picture URL",
                },
              },
              authenticatedPurchase: {
                description: "Existing agent purchases membership or upgrades.",
                auth: "Bearer token",
                body: {
                  purchaseType: "membership | storage-pass | stack-unlock | grid-unlock",
                  txHash: "Transaction hash of USDC payment",
                  stackId: "Required for stack-unlock",
                },
              },
            },
          },
        ],
      },

      write_operations: {
        description: "Write operations for registered agents. Requires membership.",
        endpoints: [
          {
            method: "POST",
            path: "/api/v1/library/write",
            description: "Register a new item in the library.",
            auth: "Bearer token (requires library:write permission)",
          },
          {
            method: "POST",
            path: "/api/v1/stacks/write",
            description: "Create a stack or add items to a stack.",
            auth: "Bearer token (requires stacks:create or stacks:write permission)",
          },
          {
            method: "POST",
            path: "/api/v1/archive",
            description: "Archive a social media post (Farcaster cast, tweet, etc.).",
            auth: "Bearer token (requires library:archive permission)",
          },
        ],
      },

      tasks: {
        description: "Task management for collaborative workflows.",
        endpoints: [
          {
            method: "GET",
            path: "/api/v1/agents/tasks",
            description: "Get pending tasks assigned to your agent.",
            auth: "Bearer token",
          },
          {
            method: "PUT",
            path: "/api/v1/agents/tasks",
            description: "Update task status (complete, fail).",
            auth: "Bearer token",
          },
        ],
      },
    },

    permissions: {
      available: [
        { name: "library:write", description: "Can upload files and register items" },
        { name: "library:archive", description: "Can archive social posts" },
        { name: "stacks:create", description: "Can create new stacks" },
        { name: "stacks:write", description: "Can add/remove items from owned stacks" },
        { name: "stacks:delete", description: "Can delete owned stacks" },
        { name: "admin", description: "Full access (bootstrap only, not grantable via API)" },
      ],
    },

    // ERC-8004 Base Identity Registry verification (C16)
    erc8004_verification: {
      description: "Agents registered on the ERC-8004 Base Identity Registry get verified status and an orange badge on their library card and member listing",
      how_to_verify: [
        "1) Set your erc8004TokenId via PUT /api/v1/agents (if you know your token ID)",
        "2) Call POST /api/v1/agents/verify-8004 to trigger verification",
        "3) Verification is cached for 1 hour. Call verify-8004 to force re-check.",
      ],
      registry_contract: ERC8004_REGISTRY,
      chain: "Base (8453)",
      badge_color: "#F97316 (orange-500)",
      what_it_shows: "Orange ring around PFP, BadgeCheck icon next to AGENT badge",
    },

    examples: {
      browseLibrary: `curl "${baseUrl}/api/v1/library?limit=10&sort=newest"`,
      searchBooks: `curl "${baseUrl}/api/v1/search?q=science%20fiction&limit=20"`,
      getStack: `curl "${baseUrl}/api/v1/stacks/my-favorites"`,
      checkMembership: `curl -H "Authorization: Bearer YOUR_API_KEY" "${baseUrl}/api/v1/agents/membership"`,
    },
  });
}
src/app/api/v1/agents/ens/route.ts
 
/**
 * Agent ENS Subname Minting API
 *
 * POST /api/v1/agents/ens — Mint or retry ENS subname for the calling agent
 * OPTIONS — CORS preflight
 *
 * Allows agents who are already members to mint their ENS subname if it wasn't
 * created during membership signup (e.g., NameStone was down, no wallet address).
 */

import { NextRequest } from "next/server";
import {
  authenticateAgent,
  isAuthError,
  findMemberByAgentId,
  findMemberByAddress,
  updateMemberAtomically,
  checkEnsSubnameExists,
  mintEnsSubname,
  handleOptions,
  corsResponse,
  corsError,
  type MemberRegistry,
  type MemberEntry,
} from "@/lib/agent-auth";

const PARENT_DOMAIN = "netlibrary.eth";

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * POST /api/v1/agents/ens — Mint ENS subname for the calling agent
 *
 * Requirements:
 * - Agent must be authenticated
 * - Agent must already be a member
 * - Agent must have a wallet address on file
 *
 * If already minted, returns success with alreadyMinted: true
 */
export async function POST(request: NextRequest) {
  try {
    // 1. Authenticate agent
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      return authResult;
    }

    const { agent } = authResult;

    // 2. Agent must have a wallet address
    const walletAddress = agent.address?.toLowerCase();
    if (!walletAddress) {
      return corsError(
        "No wallet address on your agent record. Update your profile via PUT /api/v1/agents with an 'address' field first.",
        400
      );
    }

    // 3. Use atomic read to find member and get their info
    // We do a "dry run" atomic update that doesn't change anything, just to get a consistent read
    let memberId: number | undefined;
    let currentEnsSubname: string | undefined;

    const findResult = await updateMemberAtomically(
      (registry: MemberRegistry) => {
        let member = findMemberByAgentId(registry, agent.id);
        if (!member) {
          member = findMemberByAddress(registry, walletAddress);
        }
        return member;
      },
      (member: MemberEntry) => {
        // Just read, don't modify
        return { memberId: member.memberId, ensSubname: member.ensSubname };
      }
    );

    if (!findResult.success || !findResult.member) {
      return corsError(
        "You are not a member. Use POST /api/v1/agents/membership to purchase membership first.",
        403
      );
    }

    memberId = findResult.result?.memberId;
    currentEnsSubname = findResult.result?.ensSubname;
    const ensSubname = `${memberId}.${PARENT_DOMAIN}`;

    // 4. Check if already minted via NameStone (single-name lookup)
    const existsCheck = await checkEnsSubnameExists(memberId!);

    if (existsCheck.error && !existsCheck.exists) {
      // If we can't check but the member already has ensSubname set, assume it's minted
      if (currentEnsSubname && currentEnsSubname.includes(String(memberId))) {
        return corsResponse({
          success: true,
          ensSubname,
          memberId,
          alreadyMinted: true,
          note: "Could not verify with NameStone, but ensSubname is already recorded",
        });
      }
    }

    if (existsCheck.exists) {
      // Already minted - update member entry atomically if ensSubname wasn't recorded
      if (!currentEnsSubname || currentEnsSubname !== ensSubname) {
        await updateMemberAtomically(
          (registry: MemberRegistry) => {
            let member = findMemberByAgentId(registry, agent.id);
            if (!member) {
              member = findMemberByAddress(registry, walletAddress);
            }
            return member;
          },
          (member: MemberEntry) => {
            member.ensSubname = ensSubname;
            return { updated: true };
          }
        );
        console.log(`[POST /api/v1/agents/ens] Updated member #${memberId} ensSubname`);
      }

      return corsResponse({
        success: true,
        ensSubname,
        memberId,
        alreadyMinted: true,
        resolvedAddress: existsCheck.address,
      });
    }

    // 5. Mint the ENS subname
    console.log(`[POST /api/v1/agents/ens] Minting ENS for agent ${agent.id} (member #${memberId})...`);
    const mintResult = await mintEnsSubname(memberId!, walletAddress, true);

    if (!mintResult.success) {
      return corsResponse(
        {
          success: false,
          error: mintResult.error || "Failed to mint ENS subname",
          memberId,
        },
        502
      );
    }

    // 6. Update member entry atomically with ensSubname
    if (!currentEnsSubname || currentEnsSubname !== ensSubname) {
      await updateMemberAtomically(
        (registry: MemberRegistry) => {
          let member = findMemberByAgentId(registry, agent.id);
          if (!member) {
            member = findMemberByAddress(registry, walletAddress);
          }
          return member;
        },
        (member: MemberEntry) => {
          member.ensSubname = ensSubname;
          return { updated: true };
        }
      );
      console.log(`[POST /api/v1/agents/ens] Updated member #${memberId} with ensSubname`);
    }

    return corsResponse({
      success: true,
      ensSubname,
      memberId,
      alreadyMinted: false,
    });
  } catch (error) {
    console.error("[POST /api/v1/agents/ens] Error:", error);
    return corsError("Internal server error", 500);
  }
}
src/app/api/v1/agents/link/route.ts
 
/**
 * Agent Net Protocol Linking API
 *
 * GET /api/v1/agents/link — Check current link status
 * POST /api/v1/agents/link — Set or update the Net Protocol link
 * DELETE /api/v1/agents/link — Remove the link
 * OPTIONS — CORS preflight
 *
 * Links an agent's member profile to a Net Protocol content URL.
 * Linked members show a "LINKED" badge in the All Members UI.
 */

import { NextRequest } from "next/server";
import {
  getKV,
  setKV,
  authenticateAgent,
  isAuthError,
  getMemberRegistry,
  findMemberByAgentId,
  findMemberByAddress,
  handleOptions,
  corsResponse,
  corsError,
} from "@/lib/agent-auth";

// KV key prefix for user net links (matches existing user-net-link API)
const NET_LINK_KEY_PREFIX = "user-net-link:";

// Link data structure (matches existing implementation)
interface NetLinkData {
  url: string;
  label: string;
  updatedAt: number;
}

/**
 * Validate Net Protocol URL
 * Accepts URLs from netprotocol.app or storedon.net
 */
function isValidNetProtocolUrl(url: string): boolean {
  try {
    const parsed = new URL(url);
    const validHosts = [
      "netprotocol.app",
      "www.netprotocol.app",
      "storedon.net",
      "www.storedon.net",
    ];
    return validHosts.some(
      (host) => parsed.hostname === host || parsed.hostname.endsWith(`.${host}`)
    );
  } catch {
    return false;
  }
}

/**
 * Verify URL is accessible via HEAD request
 */
async function verifyUrlAccessible(url: string): Promise<{ accessible: boolean; error?: string }> {
  try {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 10000); // 10s timeout

    const response = await fetch(url, {
      method: "HEAD",
      signal: controller.signal,
    });

    clearTimeout(timeoutId);

    if (response.ok) {
      return { accessible: true };
    }

    // Also accept 405 Method Not Allowed (some servers don't support HEAD)
    // In that case, try a GET request
    if (response.status === 405) {
      const getResponse = await fetch(url, {
        method: "GET",
        signal: controller.signal,
      });
      return { accessible: getResponse.ok };
    }

    return { accessible: false, error: `URL returned status ${response.status}` };
  } catch (error) {
    if (error instanceof Error && error.name === "AbortError") {
      return { accessible: false, error: "URL request timed out" };
    }
    return { accessible: false, error: "URL is not accessible" };
  }
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/v1/agents/link — Check current link status
 */
export async function GET(request: NextRequest) {
  try {
    // 1. Authenticate agent
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      return authResult;
    }

    const { agent } = authResult;

    // 2. Look up agent's member entry
    const registry = await getMemberRegistry();

    let memberEntry = findMemberByAgentId(registry, agent.id);
    if (!memberEntry && agent.address) {
      memberEntry = findMemberByAddress(registry, agent.address.toLowerCase());
    }

    if (!memberEntry) {
      return corsError(
        "You are not a member. Use POST /api/v1/agents/membership first.",
        403
      );
    }

    // 3. Check for existing link using member's address
    const linkKey = `${NET_LINK_KEY_PREFIX}${memberEntry.address.toLowerCase()}`;
    const linkData = await getKV<NetLinkData>(linkKey);

    if (linkData && linkData.url) {
      return corsResponse({
        success: true,
        linked: true,
        url: linkData.url,
        label: linkData.label,
        linkedAt: linkData.updatedAt,
      });
    }

    return corsResponse({
      success: true,
      linked: false,
      url: null,
      linkedAt: null,
    });
  } catch (error) {
    console.error("[GET /api/v1/agents/link] Error:", error);
    return corsError("Internal server error", 500);
  }
}

/**
 * POST /api/v1/agents/link — Set or update the Net Protocol link
 *
 * Body: { "url": "https://storedon.net/...", "label"?: "My Profile" }
 */
export async function POST(request: NextRequest) {
  try {
    // 1. Authenticate agent
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      return authResult;
    }

    const { agent } = authResult;

    // 2. Look up agent's member entry
    const registry = await getMemberRegistry();

    let memberEntry = findMemberByAgentId(registry, agent.id);
    if (!memberEntry && agent.address) {
      memberEntry = findMemberByAddress(registry, agent.address.toLowerCase());
    }

    if (!memberEntry) {
      return corsError(
        "You are not a member. Use POST /api/v1/agents/membership first.",
        403
      );
    }

    // 3. Parse and validate body
    const body = await request.json();
    const { url, label } = body;

    if (!url || typeof url !== "string" || url.trim() === "") {
      return corsError("url is required", 400);
    }

    const trimmedUrl = url.trim();

    // 4. Validate URL format
    if (!isValidNetProtocolUrl(trimmedUrl)) {
      return corsError(
        "Invalid URL. Must be a Net Protocol URL from storedon.net or netprotocol.app",
        400
      );
    }

    // 5. Verify URL is accessible
    const accessCheck = await verifyUrlAccessible(trimmedUrl);
    if (!accessCheck.accessible) {
      return corsError(accessCheck.error || "URL is not accessible", 400);
    }

    // 6. Save the link
    const linkData: NetLinkData = {
      url: trimmedUrl,
      label: label?.trim() || agent.name || "Net Protocol Link",
      updatedAt: Date.now(),
    };

    // Save to member's primary address
    const linkKey = `${NET_LINK_KEY_PREFIX}${memberEntry.address.toLowerCase()}`;
    await setKV(linkKey, linkData);

    // Also save to any linked addresses the member has
    if (memberEntry.linkedAddresses && memberEntry.linkedAddresses.length > 0) {
      for (const linkedAddr of memberEntry.linkedAddresses) {
        if (linkedAddr) {
          const linkedKey = `${NET_LINK_KEY_PREFIX}${linkedAddr.toLowerCase()}`;
          await setKV(linkedKey, linkData);
        }
      }
    }

    console.log(`[POST /api/v1/agents/link] Agent ${agent.id} linked to ${trimmedUrl}`);

    return corsResponse({
      success: true,
      url: linkData.url,
      label: linkData.label,
      linkedAt: linkData.updatedAt,
    });
  } catch (error) {
    console.error("[POST /api/v1/agents/link] Error:", error);
    return corsError("Internal server error", 500);
  }
}

/**
 * DELETE /api/v1/agents/link — Remove the Net Protocol link
 */
export async function DELETE(request: NextRequest) {
  try {
    // 1. Authenticate agent
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      return authResult;
    }

    const { agent } = authResult;

    // 2. Look up agent's member entry
    const registry = await getMemberRegistry();

    let memberEntry = findMemberByAgentId(registry, agent.id);
    if (!memberEntry && agent.address) {
      memberEntry = findMemberByAddress(registry, agent.address.toLowerCase());
    }

    if (!memberEntry) {
      return corsError(
        "You are not a member. Use POST /api/v1/agents/membership first.",
        403
      );
    }

    // 3. Remove the link from member's primary address
    const linkKey = `${NET_LINK_KEY_PREFIX}${memberEntry.address.toLowerCase()}`;
    await setKV(linkKey, null);

    // Also remove from linked addresses
    if (memberEntry.linkedAddresses && memberEntry.linkedAddresses.length > 0) {
      for (const linkedAddr of memberEntry.linkedAddresses) {
        if (linkedAddr) {
          const linkedKey = `${NET_LINK_KEY_PREFIX}${linkedAddr.toLowerCase()}`;
          await setKV(linkedKey, null);
        }
      }
    }

    console.log(`[DELETE /api/v1/agents/link] Agent ${agent.id} removed link`);

    return corsResponse({
      success: true,
      message: "Link removed",
    });
  } catch (error) {
    console.error("[DELETE /api/v1/agents/link] Error:", error);
    return corsError("Internal server error", 500);
  }
}
src/app/api/v1/agents/me/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Agent Profile API
 *
 * GET /api/v1/agents/me — Full agent profile with widgets
 * OPTIONS — CORS preflight
 */

import { NextRequest } from "next/server";
import {
  // Shared utilities from P1
  getKV,
  authenticateAgent,
  isAuthError,
  getMemberRegistry,
  handleOptions,
  corsResponse,
  corsError,
} from "@/lib/agent-auth";
import type { Stack } from "@/features/app/types";
import type { Grid } from "@/lib/net-protocol";

// Get base URL for widget URLs
function getBaseUrl(): string {
  const url = process.env.NEXT_PUBLIC_URL || process.env.VERCEL_URL;
  if (url) {
    return url.startsWith("http") ? url : `https://${url}`;
  }
  return "https://miniapp-generator-fid-282520-251210015136529.neynar.app";
}

// Widget dimensions
const WIDGET_DIMENSIONS = {
  libraryCard: { width: 350, height: 480 },
  profile: { width: 400, height: 320 },
  stack: { width: 400, height: 500 },
  grid: { width: 400, height: 450 },
  feed: { width: 400, height: 600 },
  stats: { width: 400, height: 300 },
} as const;

// Generate iframe HTML
function generateIframeHtml(url: string, dimensions: { width: number; height: number }, title: string): string {
  return `<iframe src="${url}" width="${dimensions.width}" height="${dimensions.height}" frameborder="0" title="${title}" style="border-radius: 12px; overflow: hidden;"></iframe>`;
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/v1/agents/me — Full agent profile with widgets
 *
 * Returns:
 * - Agent identity (address, fid, name, pfp)
 * - Membership info (memberId, memberSince)
 * - Widget URLs with ready-to-use iframe HTML
 * - Stacks owned by the agent
 * - Grids created by the agent
 */
export async function GET(request: NextRequest) {
  try {
    // Authenticate agent
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      return authResult;
    }

    const { agent, agentId } = authResult;
    const baseUrl = getBaseUrl();
    const address = agent.address?.toLowerCase();

    // Get membership info
    let membership: {
      memberId: number;
      memberSince: string;
      ensSubname: string;
      hasStackPass?: boolean;
    } | null = null;

    if (address) {
      const registry = await getMemberRegistry();
      // Check by agentId first, then by address
      let member = registry.members.find(m => m.agentId === agentId);
      if (!member) {
        member = registry.members.find(m => m.address?.toLowerCase() === address);
      }

      if (member) {
        membership = {
          memberId: member.memberId,
          memberSince: String(member.joinedAt),
          ensSubname: member.ensSubname || `${member.memberId}.netlibrary.eth`,
          hasStackPass: member.hasStackPass,
        };
      }
    }

    // Build widgets object
    const widgets: {
      libraryCard?: { url: string; html: string; dimensions: { width: number; height: number } };
      profile?: { url: string; html: string; dimensions: { width: number; height: number } };
      stacks: Array<{
        id: string;
        name: string;
        description?: string;
        itemCount: number;
        updatedAt: number;
        url: string;
        html: string;
        dimensions: { width: number; height: number };
      }>;
      grids: Array<{
        id: string;
        name: string;
        size: number;
        updatedAt: number;
        url: string;
        html: string;
        dimensions: { width: number; height: number };
      }>;
      global: {
        feed: { url: string; html: string; dimensions: { width: number; height: number } };
        stats: { url: string; html: string; dimensions: { width: number; height: number } };
      };
    } = {
      stacks: [],
      grids: [],
      global: {
        feed: {
          url: `${baseUrl}/embed/feed`,
          html: generateIframeHtml(`${baseUrl}/embed/feed`, WIDGET_DIMENSIONS.feed, "Net Library Feed"),
          dimensions: WIDGET_DIMENSIONS.feed,
        },
        stats: {
          url: `${baseUrl}/embed/stats`,
          html: generateIframeHtml(`${baseUrl}/embed/stats`, WIDGET_DIMENSIONS.stats, "Net Library Stats"),
          dimensions: WIDGET_DIMENSIONS.stats,
        },
      },
    };

    // Add address-based widgets if agent has an address
    if (address) {
      // Library Card widget (only if member)
      if (membership) {
        const cardUrl = `${baseUrl}/embed/card/${address}`;
        widgets.libraryCard = {
          url: cardUrl,
          html: generateIframeHtml(cardUrl, WIDGET_DIMENSIONS.libraryCard, "Library Card"),
          dimensions: WIDGET_DIMENSIONS.libraryCard,
        };
      }

      // Profile widget
      const profileUrl = `${baseUrl}/embed/user/${address}`;
      widgets.profile = {
        url: profileUrl,
        html: generateIframeHtml(profileUrl, WIDGET_DIMENSIONS.profile, "User Profile"),
        dimensions: WIDGET_DIMENSIONS.profile,
      };

      // Fetch agent's stacks
      const stacksRegistry = await getKV<string[]>("stacks-registry");
      if (stacksRegistry) {
        for (const stackId of stacksRegistry) {
          const stack = await getKV<Stack>(`stack:${stackId}`);
          if (stack && stack.owner.toLowerCase() === address && !stack.isPrivate) {
            const stackUrl = `${baseUrl}/embed/stack/${stack.id}`;
            widgets.stacks.push({
              id: stack.id,
              name: stack.name,
              description: stack.description,
              itemCount: stack.itemCount || 0,
              updatedAt: stack.createdAt,
              url: stackUrl,
              html: generateIframeHtml(stackUrl, WIDGET_DIMENSIONS.stack, stack.name),
              dimensions: WIDGET_DIMENSIONS.stack,
            });
          }
        }
      }

      // Fetch agent's grids
      const gridsRegistry = await getKV<string[]>("grids-registry");
      if (gridsRegistry) {
        for (const gridId of gridsRegistry) {
          const grid = await getKV<Grid>(`grid:${gridId}`);
          if (grid && grid.creator.toLowerCase() === address && grid.visibility === "public" && !grid.deleted) {
            const gridUrl = `${baseUrl}/embed/grid/${grid.id}`;
            widgets.grids.push({
              id: grid.id,
              name: grid.name,
              size: grid.size,
              updatedAt: grid.updatedAt,
              url: gridUrl,
              html: generateIframeHtml(gridUrl, WIDGET_DIMENSIONS.grid, grid.name),
              dimensions: WIDGET_DIMENSIONS.grid,
            });
          }
        }
      }
    }

    // Get extended agent fields (if any)
    const extendedAgent = agent as typeof agent & {
      description?: string;
      webhookUrl?: string;
      capabilities?: string[];
      updatedAt?: number;
    };

    return corsResponse({
      success: true,
      agent: {
        id: agent.id,
        address: agent.address || null,
        fid: agent.fid || null,
        profile: {
          name: agent.name,
          description: extendedAgent.description || null,
          pfpUrl: agent.pfpUrl || null,
        },
        permissions: agent.permissions,
        capabilities: extendedAgent.capabilities || null,
        webhookUrl: extendedAgent.webhookUrl || null,
        createdAt: agent.createdAt,
        updatedAt: extendedAgent.updatedAt || null,
      },
      membership,
      widgets,
      baseUrl,
    });
  } catch (error) {
    console.error("[GET /api/v1/agents/me] Error:", error);
    return corsError("Failed to fetch agent profile", 500);
  }
}
src/app/api/v1/agents/membership/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Agent Membership & Purchases API
 *
 * GET /api/v1/agents/membership — Check membership status and available purchases
 * POST /api/v1/agents/membership — Purchase membership or other items (or self-register)
 * OPTIONS — CORS preflight
 *
 * Supported purchase types:
 * - membership ($2 USDC) — Join Net Library, get ENS subname
 * - storage-pass ($10 USDC) — Unlimited Pass: unlimited storage for stacks (members only)
 * - stack-unlock ($5 USDC) — Unlock a specific stack for unlimited items
 * - grid-unlock ($2 USDC) — Unlock personal grid customization
 *
 * Self-registration (no auth required):
 * POST with { selfRegister: true, name, address, txHash } to register + get API key in one step.
 * Requires $2 USDC payment. Returns API key on success.
 */

import { NextRequest } from "next/server";
import {
  // Shared utilities from P1
  getKV,
  setKV,
  deleteKV,
  authenticateAgent,
  isAuthError,
  hasPermission,
  getMemberRegistry,
  findMemberByAddress,
  findMemberByAgentId,
  verifyUsdcPayment,
  markTxUsed,
  isTxUsed,
  handleOptions,
  corsResponse,
  corsError,
  addMemberAtomically,
  updateMemberAtomically,
  atomicKVUpdate,
  atomicArrayUpdate,
  mintEnsSubname,
  // Types
  type RegisteredAgent,
  type MemberEntry,
  type MemberRegistry,
  // Constants
  AGENT_KEY_PREFIX,
  AGENTS_REGISTRY_KEY,
  USDC_CONTRACT,
  TREASURY_ADDRESS,
  PRICING,
} from "@/lib/agent-auth";
import type { Stack } from "@/features/app/types";

// KV key for stacks
const STACK_PREFIX = "stack:";

// =============================================================================
// SELF-REGISTRATION HELPERS (C20)
// =============================================================================

/** Generate a Net Library API key in nlk_ format */
function generateNlkApiKey(): string {
  const bytes = new Uint8Array(16);
  crypto.getRandomValues(bytes);
  const hex = Array.from(bytes)
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
  return `nlk_${hex}`;
}

/** Generate an agent ID for self-registered agents */
function generateSelfRegAgentId(): string {
  const timestamp = Date.now();
  const bytes = new Uint8Array(3);
  crypto.getRandomValues(bytes);
  const random = Array.from(bytes)
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
  return `agent-${timestamp}-${random}`;
}

/** KV key for rate-limiting self-registration by hour bucket */
function selfRegRateKey(): string {
  const hourBucket = Math.floor(Date.now() / (60 * 60 * 1000));
  return `self-register-rate:${hourBucket}`;
}

const SELF_REG_MAX_PER_HOUR = 5;

// Purchase types
type PurchaseType = "membership" | "storage-pass" | "stack-unlock" | "grid-unlock";

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/v1/agents/membership — Check membership status and available purchases
 *
 * Returns:
 * - isMember: boolean
 * - If member: memberId, ensSubname, joinedAt, hasUnlimitedPass, hasGridPass
 * - availablePurchases: Array of available purchase types with pricing
 */
export async function GET(request: NextRequest) {
  try {
    // Authenticate agent
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      return authResult;
    }

    const { agent } = authResult;
    const address = agent.address?.toLowerCase();

    // Build available purchases based on membership status
    const buildAvailablePurchases = (isMember: boolean, hasStoragePass: boolean, hasGridPass: boolean) => {
      const purchases: Array<{
        type: PurchaseType;
        price: number;
        priceDisplay: string;
        description: string;
        available: boolean;
        reason?: string;
      }> = [];

      // Membership
      purchases.push({
        type: "membership",
        price: PRICING.MEMBERSHIP,
        priceDisplay: `${PRICING.MEMBERSHIP} USDC`,
        description: "Join Net Library and receive an ENS subname",
        available: !isMember,
        reason: isMember ? "Already a member" : undefined,
      });

      // Storage pass (members only)
      purchases.push({
        type: "storage-pass",
        price: PRICING.STORAGE_PASS,
        priceDisplay: `${PRICING.STORAGE_PASS} USDC`,
        description: "Unlimited storage for all your stacks",
        available: isMember && !hasStoragePass,
        reason: !isMember
          ? "Requires membership"
          : hasStoragePass
          ? "Already purchased"
          : undefined,
      });

      // Stack unlock (members only)
      purchases.push({
        type: "stack-unlock",
        price: PRICING.STACK_UNLOCK,
        priceDisplay: `${PRICING.STACK_UNLOCK} USDC`,
        description: "Unlock unlimited items for a specific stack (requires stackId)",
        available: isMember,
        reason: !isMember ? "Requires membership" : undefined,
      });

      // Grid unlock (members only)
      purchases.push({
        type: "grid-unlock",
        price: PRICING.GRID_UNLOCK,
        priceDisplay: `${PRICING.GRID_UNLOCK} USDC`,
        description: "Unlock personal grid customization",
        available: isMember && !hasGridPass,
        reason: !isMember
          ? "Requires membership"
          : hasGridPass
          ? "Already purchased"
          : undefined,
      });

      return purchases;
    };

    if (!address) {
      return corsResponse({
        success: true,
        isMember: false,
        isAgent: true,
        agentId: agent.id,
        error: "Agent has no wallet address registered. Update your agent record with an address first.",
        availablePurchases: buildAvailablePurchases(false, false, false),
        paymentInfo: {
          treasuryAddress: TREASURY_ADDRESS,
          usdcContract: USDC_CONTRACT,
          chain: "Base (Chain ID 8453)",
        },
      });
    }

    // Check existing membership in registry
    const registry = await getMemberRegistry();

    // First check by agentId, then by address
    let existingMember = findMemberByAgentId(registry, agent.id);
    if (!existingMember) {
      existingMember = findMemberByAddress(registry, address);
    }

    if (existingMember) {
      // Check pass: flag in member record first, then on-chain NFT as fallback
      let hasStoragePass =
        existingMember.hasStackPass ||
        existingMember.hasUnlimitedPass ||
        existingMember.hasUnlimitedStoragePass ||
        false;

      // On-chain fallback: if flag not set, check NFT contract directly
      // This ensures users who minted via any path (CLI, direct call, etc.) are recognized
      if (!hasStoragePass) {
        try {
          const BASE_RPC =
            process.env.BASE_RPC_URL || "[REDACTED-RPC-URL]";
          const PASS_CONTRACT = "0xCe559A2A6b64504bE00aa7aA85C5C31EA93a16BB";
          const memberAddress = existingMember.address;

          const rpcBody = JSON.stringify({
            jsonrpc: "2.0",
            id: 1,
            method: "eth_call",
            params: [
              {
                to: PASS_CONTRACT,
                // hasUnlimitedPass(address) selector = 0x448c6ee7, address padded to 32 bytes
                data:
                  "0x448c6ee7" +
                  "000000000000000000000000" +
                  memberAddress.slice(2).toLowerCase(),
              },
              "latest",
            ],
          });

          const rpcResp = await fetch(BASE_RPC, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: rpcBody,
          });
          const rpcJson = (await rpcResp.json()) as { result?: string };
          // result is a 32-byte hex: last byte is 0x01 if true
          if (rpcJson.result && rpcJson.result !== "0x" && rpcJson.result !== "0x0000000000000000000000000000000000000000000000000000000000000000") {
            hasStoragePass = true;

            // Update member record lazily so future checks hit the flag
            existingMember.hasStackPass = true;
            existingMember.hasUnlimitedPass = true;
            // Fire-and-forget save (don't block response)
            setKV(
              `member-registry`,
              await getMemberRegistry().then((reg) => {
                const m = reg.members.find(
                  (x) => x.memberId === existingMember!.memberId
                );
                if (m) {
                  m.hasStackPass = true;
                  m.hasUnlimitedPass = true;
                }
                return reg;
              })
            ).catch(() => {});
          }
        } catch {
          // RPC failure — fall back to flag value (already false)
        }
      }

      // Check grid pass from KV
      const gridPassKey = `grid-pass:${address}`;
      const hasGridPass = !!(await getKV<boolean>(gridPassKey));

      return corsResponse({
        success: true,
        isMember: true,
        isAgent: true,
        memberId: existingMember.memberId,
        ensSubname: existingMember.ensSubname || `${existingMember.memberId}.netlibrary.eth`,
        joinedAt: existingMember.joinedAt,
        hasUnlimitedPass: hasStoragePass,
        hasUnlimitedStoragePass: hasStoragePass, // backwards compat alias
        hasStackPass: hasStoragePass, // backwards compat alias
        hasGridPass,
        // NFT pass details (if available)
        unlimitedPassTokenId: existingMember.unlimitedPassTokenId,
        unlimitedPassTier: existingMember.unlimitedPassTier,
        unlimitedPassMintTx: existingMember.unlimitedPassMintTx,
        membership: {
          address: existingMember.address,
          memberId: existingMember.memberId,
          agentId: existingMember.agentId || agent.id,
        },
        availablePurchases: buildAvailablePurchases(true, hasStoragePass, hasGridPass),
        paymentInfo: {
          treasuryAddress: TREASURY_ADDRESS,
          usdcContract: USDC_CONTRACT,
          chain: "Base (Chain ID 8453)",
        },
      });
    }

    // Not a member - return pricing info
    return corsResponse({
      success: true,
      isMember: false,
      isAgent: true,
      agentId: agent.id,
      address: address,
      availablePurchases: buildAvailablePurchases(false, false, false),
      paymentInfo: {
        treasuryAddress: TREASURY_ADDRESS,
        usdcContract: USDC_CONTRACT,
        chain: "Base (Chain ID 8453)",
      },
    });
  } catch (error) {
    console.error("[GET /api/v1/agents/membership] Error:", error);
    return corsError("Failed to check membership status", 500);
  }
}

/**
 * POST /api/v1/agents/membership — Purchase membership or other items
 *
 * Request body:
 * - purchaseType: "membership" | "storage-pass" | "stack-unlock" | "grid-unlock" (default: "membership")
 * - txHash: Transaction hash for USDC payment
 * - stackId: Required for "stack-unlock" purchases
 * - adminGrant: true (admin only) — Grant item without payment
 * - targetAgentId: Required for admin grants
 *
 * Self-registration (no auth required):
 * - selfRegister: true
 * - name: required
 * - address: required (wallet address)
 * - txHash: required ($2 USDC to treasury)
 * - description: optional
 * - fid: optional
 * - pfpUrl: optional
 */
export async function POST(request: NextRequest) {
  try {
    // Parse body once — used by both the self-register path and the normal auth path
    let body: Record<string, unknown> = {};
    try {
      body = await request.json();
    } catch {
      body = {};
    }

    // =========================================================================
    // SELF-REGISTRATION PATH (C20) — checked before normal auth
    // =========================================================================
    if (body.selfRegister === true) {
      return handleSelfRegister(body);
    }

    // Authenticate agent
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      return authResult;
    }

    const { agent } = authResult;

    const {
      purchaseType = "membership",
      txHash,
      stackId,
      adminGrant,
      targetAgentId,
    } = body as {
      purchaseType?: PurchaseType;
      txHash?: string;
      stackId?: string;
      adminGrant?: boolean;
      targetAgentId?: string;
    };

    // Validate purchaseType
    const validTypes: PurchaseType[] = ["membership", "storage-pass", "stack-unlock", "grid-unlock"];
    if (!validTypes.includes(purchaseType)) {
      return corsError(
        `Invalid purchaseType. Must be one of: ${validTypes.join(", ")}`,
        400
      );
    }

    // Get pricing for this purchase type
    const priceMap: Record<PurchaseType, number> = {
      membership: PRICING.MEMBERSHIP,
      "storage-pass": PRICING.STORAGE_PASS,
      "stack-unlock": PRICING.STACK_UNLOCK,
      "grid-unlock": PRICING.GRID_UNLOCK,
    };
    const price = priceMap[purchaseType];

    // =========================================================================
    // ADMIN GRANT PATH (works for all purchase types)
    // =========================================================================
    if (adminGrant === true) {
      if (!hasPermission(agent, "admin")) {
        return corsError("Only admin agents can grant items without payment", 403);
      }

      // For non-membership grants, target can be self or another agent
      const effectiveTargetId = targetAgentId || agent.id;
      const targetAgent = effectiveTargetId === agent.id
        ? agent
        : await getKV<RegisteredAgent>(`${AGENT_KEY_PREFIX}${effectiveTargetId}`);

      if (!targetAgent) {
        return corsError("Target agent not found", 404);
      }

      if (!targetAgent.address) {
        return corsError("Target agent has no wallet address. Update agent record first.", 400);
      }

      const targetAddress = targetAgent.address.toLowerCase();

      // Handle admin grant based on purchase type
      switch (purchaseType) {
        case "membership":
          return handleMembershipPurchase(targetAgent, targetAddress, null, true, agent.id);

        case "storage-pass":
          return handleStoragePassPurchase(targetAddress, effectiveTargetId, null, true, agent.id);

        case "stack-unlock":
          if (!stackId) {
            return corsError("stackId is required for stack-unlock", 400);
          }
          return handleStackUnlockPurchase(targetAddress, stackId, null, true, agent.id);

        case "grid-unlock":
          return handleGridUnlockPurchase(targetAddress, null, true, agent.id);
      }
    }

    // =========================================================================
    // PAID PURCHASE PATH
    // =========================================================================

    // Agent must have a wallet address
    if (!agent.address) {
      return corsResponse({
        success: false,
        error: "Agent has no wallet address. Update your agent record with an address before purchasing.",
        paymentInfo: {
          treasuryAddress: TREASURY_ADDRESS,
          usdcContract: USDC_CONTRACT,
          chain: "Base (Chain ID 8453)",
        },
      }, 400);
    }

    const address = agent.address.toLowerCase();

    // All paid purchases require tx hash
    if (!txHash) {
      return corsResponse({
        success: false,
        error: `txHash is required. Send $${price} USDC to the treasury address, then provide the transaction hash.`,
        purchaseType,
        price: `${price} USDC`,
        treasuryAddress: TREASURY_ADDRESS,
        usdcContract: USDC_CONTRACT,
        chain: "Base (Chain ID 8453)",
      }, 402);
    }

    // Non-membership purchases require existing membership
    if (purchaseType !== "membership") {
      const registry = await getMemberRegistry();
      let existingMember = findMemberByAgentId(registry, agent.id);
      if (!existingMember) {
        existingMember = findMemberByAddress(registry, address);
      }

      if (!existingMember) {
        return corsError(
          `${purchaseType} requires membership. Purchase membership first.`,
          403
        );
      }
    }

    // Verify the USDC payment
    const paymentResult = await verifyUsdcPayment(txHash, price, address);

    if (!paymentResult.valid) {
      return corsResponse({
        success: false,
        error: paymentResult.error,
        purchaseType,
        expectedPrice: `${price} USDC`,
        treasuryAddress: TREASURY_ADDRESS,
        usdcContract: USDC_CONTRACT,
      }, 400);
    }

    // Handle purchase based on type
    switch (purchaseType) {
      case "membership":
        return handleMembershipPurchase(agent, address, txHash, false, undefined, paymentResult.amount);

      case "storage-pass":
        return handleStoragePassPurchase(address, agent.id, txHash, false, undefined, paymentResult.amount);

      case "stack-unlock":
        if (!stackId) {
          return corsError("stackId is required for stack-unlock", 400);
        }
        return handleStackUnlockPurchase(address, stackId, txHash, false, undefined, paymentResult.amount);

      case "grid-unlock":
        return handleGridUnlockPurchase(address, txHash, false, undefined, paymentResult.amount);

      default:
        return corsError("Invalid purchase type", 400);
    }
  } catch (error) {
    console.error("[POST /api/v1/agents/membership] Error:", error);
    return corsError("Failed to process purchase", 500);
  }
}

// =============================================================================
// SELF-REGISTRATION HANDLER (C20)
// =============================================================================

/**
 * Handle self-registration: one-step register + membership + API key
 * No auth required — caller proves identity by paying $2 USDC.
 */
async function handleSelfRegister(body: Record<string, unknown>) {
  const {
    name,
    address: rawAddress,
    txHash,
    description,
    fid: rawFid,
    pfpUrl,
  } = body as {
    name?: string;
    address?: string;
    txHash?: string;
    description?: string;
    fid?: number;
    pfpUrl?: string;
  };

  // Validate required fields
  if (!name || typeof name !== "string" || !name.trim()) {
    return corsError("name is required for self-registration", 400);
  }
  if (!rawAddress || typeof rawAddress !== "string") {
    return corsError("address is required for self-registration", 400);
  }
  if (!txHash || typeof txHash !== "string") {
    return corsError("txHash is required for self-registration ($2 USDC payment)", 400);
  }

  const address = rawAddress.toLowerCase();
  const fid = rawFid ? Number(rawFid) : undefined;

  // -------------------------------------------------------------------------
  // Rate limiting: max 5 self-registrations per hour (global)
  // The hour-bucket key (self-register-rate:{hourBucket}) acts as implicit TTL —
  // each new hour gets a fresh key so the old counter becomes inert automatically.
  // Known limitation: read-increment-write has a small race window at our scale,
  // but locking it would be over-engineering for a 5/hour global limit.
  // -------------------------------------------------------------------------
  const rateKey = selfRegRateKey();
  const rateCount = (await getKV<number>(rateKey)) || 0;
  if (rateCount >= SELF_REG_MAX_PER_HOUR) {
    // Compute seconds until the next hour bucket starts
    const msUntilNextHour = (60 * 60 * 1000) - (Date.now() % (60 * 60 * 1000));
    const retryAfterSeconds = Math.ceil(msUntilNextHour / 1000);
    return new Response(
      JSON.stringify({
        error: "Too many self-registrations this hour. Please try again later.",
        retryAfterSeconds,
      }),
      {
        status: 429,
        headers: {
          "Content-Type": "application/json",
          "Retry-After": String(retryAfterSeconds),
          "Access-Control-Allow-Origin": "*",
        },
      }
    );
  }

  // -------------------------------------------------------------------------
  // Check for duplicate registration — O(1) via address index.
  // Verify the indexed agent is actually active. If inactive (e.g. a previously
  // revoked key), the index is stale — clean it up and allow registration.
  // -------------------------------------------------------------------------
  const existingAgentId = await getKV<string>(`agent-by-address:${address}`);
  if (existingAgentId) {
    const existingAgent = await getKV<RegisteredAgent>(`${AGENT_KEY_PREFIX}${existingAgentId}`);
    if (existingAgent && existingAgent.isActive !== false) {
      return corsResponse(
        {
          error: "This address is already registered as an agent.",
          agentId: existingAgentId,
        },
        409
      );
    }
    // Stale index — clean up and proceed
    await deleteKV(`agent-by-address:${address}`);
  }

  const registry = await getMemberRegistry();
  const existingMember = findMemberByAddress(registry, address);
  if (existingMember) {
    return corsResponse(
      {
        error: "This address is already registered as a member.",
        memberId: existingMember.memberId,
        ensSubname: existingMember.ensSubname,
      },
      409
    );
  }

  // Check tx not already used
  if (await isTxUsed(txHash)) {
    return corsResponse({ error: "Transaction hash already used." }, 409);
  }

  // -------------------------------------------------------------------------
  // Verify $2 USDC payment from this address
  // -------------------------------------------------------------------------
  const paymentResult = await verifyUsdcPayment(txHash, PRICING.MEMBERSHIP, address);
  if (!paymentResult.valid) {
    return corsResponse(
      {
        error: paymentResult.error,
        expectedAmount: `${PRICING.MEMBERSHIP} USDC`,
        treasuryAddress: TREASURY_ADDRESS,
        usdcContract: USDC_CONTRACT,
        chain: "Base (Chain ID 8453)",
      },
      400
    );
  }

  // -------------------------------------------------------------------------
  // Mark tx used IMMEDIATELY after payment verification (fix-3).
  // This burns the tx hash before any records are created. If subsequent
  // steps fail, the caller contacts support. This is preferable to allowing
  // replay attacks that could create duplicate registrations.
  // -------------------------------------------------------------------------
  await markTxUsed(txHash, "self-register");

  // -------------------------------------------------------------------------
  // Generate agent ID and API key
  // -------------------------------------------------------------------------
  const newAgentId = generateSelfRegAgentId();
  const newApiKey = generateNlkApiKey();
  // Prefix = "nlk_" + first 6 hex chars of the key body (positions 4–9)
  const apiKeyPrefix = `nlk_${newApiKey.slice(4, 10)}`;

  // -------------------------------------------------------------------------
  // Create agent record — full key NOT stored here (fix-2).
  // The only copy of the full key lives in api-key-lookup:{fullKey} → agentId.
  // -------------------------------------------------------------------------
  const newAgent: RegisteredAgent & {
    type: string;
    memberId?: number;
    apiKeyPrefix?: string;
    description?: string;
  } = {
    id: newAgentId,
    name: name.trim(),
    apiKey: "", // intentionally empty — full key stored only in api-key-lookup
    fid,
    address,
    pfpUrl: pfpUrl ? String(pfpUrl) : undefined,
    permissions: ["library:write", "stacks:create", "stacks:write", "stacks:delete"],
    createdAt: Date.now(),
    isActive: true,
    type: "api-agent",
    apiKeyPrefix,
    description: description ? String(description).trim() : undefined,
  };

  await setKV(`${AGENT_KEY_PREFIX}${newAgentId}`, newAgent);

  // The only copy of the full key
  await setKV(`api-key-lookup:${newApiKey}`, newAgentId);

  // Address index for O(1) duplicate checks (fix-6)
  await setKV(`agent-by-address:${address}`, newAgentId);

  // Add to agent registry
  await atomicArrayUpdate<string, null>(AGENTS_REGISTRY_KEY, (current) => {
    const arr = current || [];
    if (!arr.includes(newAgentId)) arr.push(newAgentId);
    return { updated: arr, result: null };
  });

  // -------------------------------------------------------------------------
  // Create member entry (atomic)
  // -------------------------------------------------------------------------
  const addResult = await addMemberAtomically((memberId) => ({
    memberId,
    address,
    ensSubname: `${memberId}.netlibrary.eth`,
    fid,
    username: name.trim(),
    joinedAt: new Date().toISOString(),
    signupPlatform: "self-register" as const,
    isAgent: true,
    agentId: newAgentId,
    paymentTxHash: txHash,
    paymentAmount: paymentResult.amount,
    grantType: "paid" as const,
    pfpUrl: pfpUrl ? String(pfpUrl) : undefined,
    apiKeyAgentId: newAgentId,
    apiKeyCreatedAt: Date.now(),
  }));

  if (!addResult.success) {
    console.error("[handleSelfRegister] Atomic add failed:", addResult.error);
    return corsError(addResult.error || "Failed to create membership", 500);
  }

  if (addResult.isDuplicate && addResult.member) {
    return corsResponse(
      {
        error: "Address already registered as a member.",
        memberId: addResult.member.memberId,
        ensSubname: addResult.member.ensSubname,
      },
      409
    );
  }

  const memberEntry = addResult.member!;

  // Update agent record with resolved memberId
  await setKV(`${AGENT_KEY_PREFIX}${newAgentId}`, {
    ...newAgent,
    memberId: memberEntry.memberId,
  });

  // Increment rate counter
  await setKV(rateKey, rateCount + 1);

  // -------------------------------------------------------------------------
  // Mint ENS subname
  // -------------------------------------------------------------------------
  console.log(`[handleSelfRegister] Minting ENS for member #${memberEntry.memberId}...`);
  const ensResult = await mintEnsSubname(memberEntry.memberId, address, true);

  console.log(
    `[handleSelfRegister] Self-registration complete for member #${memberEntry.memberId}, agent ${newAgentId}`
  );

  return corsResponse(
    {
      success: true,
      apiKey: newApiKey,
      agentId: newAgentId,
      memberId: memberEntry.memberId,
      ensSubname: memberEntry.ensSubname,
      ensMinted: ensResult.success,
      ensError: ensResult.error,
      warning: "Save this API key now — it cannot be retrieved again.",
    },
    201
  );
}

// =============================================================================
// PURCHASE HANDLERS
// =============================================================================

/**
 * Handle membership purchase
 */
async function handleMembershipPurchase(
  agent: RegisteredAgent,
  address: string,
  txHash: string | null,
  isAdminGrant: boolean,
  grantedBy?: string,
  paymentAmount?: number
) {
  // Use atomic operation to prevent race conditions
  const addResult = await addMemberAtomically((memberId) => ({
    memberId,
    address,
    ensSubname: `${memberId}.netlibrary.eth`,
    fid: agent.fid,
    username: agent.name || agent.id,
    joinedAt: new Date().toISOString(),
    signupPlatform: "agent-purchase" as const,
    isAgent: true,
    agentId: agent.id,
    ...(isAdminGrant
      ? { grantedBy, grantType: "admin" as const }
      : { paymentTxHash: txHash!, paymentAmount, grantType: "paid" as const }),
    pfpUrl: agent.pfpUrl,
  }));

  if (!addResult.success) {
    console.error("[handleMembershipPurchase] Atomic add failed:", addResult.error);
    return corsError(addResult.error || "Failed to create membership", 500);
  }

  if (addResult.isDuplicate && addResult.member) {
    return corsResponse({
      success: false,
      error: "Agent is already a member",
      membership: {
        memberId: addResult.member.memberId,
        ensSubname: addResult.member.ensSubname || `${addResult.member.memberId}.netlibrary.eth`,
        joinedAt: addResult.member.joinedAt,
      },
    }, 409);
  }

  const memberEntry = addResult.member!;

  // Mark transaction as used (replay protection)
  if (txHash) {
    await markTxUsed(txHash, "membership");
  }

  // Mint ENS subname via NameStone
  console.log(`[handleMembershipPurchase] Minting ENS for member #${memberEntry.memberId}...`);
  const ensResult = await mintEnsSubname(memberEntry.memberId, address, true);

  return corsResponse({
    success: true,
    purchaseType: "membership",
    message: isAdminGrant ? "Membership granted" : "Membership purchased successfully",
    memberId: memberEntry.memberId,
    ensSubname: memberEntry.ensSubname,
    ensMinted: ensResult.success,
    ensError: ensResult.error,
    membership: memberEntry,
  }, 201);
}

/**
 * Handle Unlimited Pass purchase
 *
 * Uses atomic locking to prevent race conditions on concurrent purchases.
 */
async function handleStoragePassPurchase(
  address: string,
  agentId: string | undefined,
  txHash: string | null,
  isAdminGrant: boolean,
  grantedBy?: string,
  paymentAmount?: number
) {
  // Use atomic update with FOR UPDATE locking
  const updateResult = await updateMemberAtomically(
    // Find member by agentId first, then by address (consistent with other handlers)
    (registry: MemberRegistry) => {
      let member = agentId ? findMemberByAgentId(registry, agentId) : undefined;
      if (!member) {
        member = findMemberByAddress(registry, address);
      }
      return member;
    },
    // Update the member atomically
    (member: MemberEntry) => {
      // Check if already has storage pass
      if (member.hasStackPass) {
        return { alreadyHas: true, memberId: member.memberId };
      }

      // Update member with storage pass
      member.hasStackPass = true;

      return { alreadyHas: false, memberId: member.memberId };
    }
  );

  if (!updateResult.success) {
    if (updateResult.error === "Member not found") {
      return corsError("Membership required for Unlimited Pass", 403);
    }
    console.error("[handleStoragePassPurchase] Atomic update failed:", updateResult.error);
    return corsError(updateResult.error || "Failed to grant Unlimited Pass", 500);
  }

  const result = updateResult.result as { alreadyHas: boolean; memberId: number };

  if (result.alreadyHas) {
    return corsResponse({
      success: false,
      error: "Already has Unlimited Pass",
      memberId: result.memberId,
    }, 409);
  }

  // Store purchase history (outside transaction - audit trail only)
  const purchaseRecord = {
    type: "storage-pass",
    purchasedAt: new Date().toISOString(),
    ...(isAdminGrant
      ? { grantedBy, grantType: "admin" }
      : { txHash, amount: paymentAmount, grantType: "paid" }),
  };
  const purchasesKey = `member-purchases:${address}`;
  const existingPurchases = await getKV<unknown[]>(purchasesKey) || [];
  existingPurchases.push(purchaseRecord);
  await setKV(purchasesKey, existingPurchases);

  // Mark transaction as used
  if (txHash) {
    await markTxUsed(txHash, "storage-pass");
  }

  console.log(`[handleStoragePassPurchase] Unlimited Pass granted to ${address}`);

  return corsResponse({
    success: true,
    purchaseType: "storage-pass",
    message: isAdminGrant ? "Unlimited Pass granted" : "Unlimited Pass purchased successfully",
    memberId: result.memberId,
    hasUnlimitedPass: true,
    hasUnlimitedStoragePass: true, // backwards compat alias
  }, 201);
}

/**
 * Handle stack unlock purchase (unlimited items for a specific stack)
 *
 * Uses atomic locking to prevent race conditions on concurrent unlock attempts.
 */
async function handleStackUnlockPurchase(
  address: string,
  stackId: string,
  txHash: string | null,
  isAdminGrant: boolean,
  grantedBy?: string,
  paymentAmount?: number
) {
  const stackKey = `${STACK_PREFIX}${stackId}`;

  // Use atomic update with FOR UPDATE locking
  const updateResult = await atomicKVUpdate<Stack, {
    notFound?: boolean;
    notOwner?: boolean;
    alreadyUnlocked?: boolean;
    unlockedAt?: number;
  }>(
    stackKey,
    (currentStack) => {
      // Stack not found
      if (!currentStack) {
        return { abort: true, result: { notFound: true } };
      }

      // Verify ownership
      if (currentStack.owner.toLowerCase() !== address.toLowerCase()) {
        return { abort: true, result: { notOwner: true } };
      }

      // Already unlocked
      if (currentStack.unlocked) {
        return { abort: true, result: { alreadyUnlocked: true, unlockedAt: currentStack.unlockedAt } };
      }

      // Unlock the stack
      const unlockedAt = Date.now();
      const updatedStack: Stack = {
        ...currentStack,
        unlocked: true,
        unlockedAt,
        ...(txHash ? { unlockTxHash: txHash } : {}),
      };

      return { updated: updatedStack, result: { unlockedAt } };
    }
  );

  if (!updateResult.success) {
    console.error("[handleStackUnlockPurchase] Atomic update failed:", updateResult.error);
    return corsError(updateResult.error || "Failed to unlock stack", 500);
  }

  const result = updateResult.result!;

  if (result.notFound) {
    return corsError(`Stack "${stackId}" not found`, 404);
  }

  if (result.notOwner) {
    return corsError("Only the stack owner can unlock a stack", 403);
  }

  if (result.alreadyUnlocked) {
    return corsResponse({
      success: false,
      error: "Stack is already unlocked",
      stackId,
      unlockedAt: result.unlockedAt,
    }, 409);
  }

  // Store unlock purchase record for audit trail (outside transaction)
  const unlockRecord = {
    stackId,
    unlockedBy: address,
    unlockedAt: result.unlockedAt,
    ...(isAdminGrant
      ? { grantedBy, grantType: "admin" }
      : { txHash, amount: paymentAmount, grantType: "paid" }),
  };
  await setKV(`stack-unlock:${stackId}`, unlockRecord);

  // Mark transaction as used
  if (txHash) {
    await markTxUsed(txHash, `stack-unlock:${stackId}`);
  }

  console.log(`[handleStackUnlockPurchase] Stack ${stackId} unlocked by ${address}`);

  return corsResponse({
    success: true,
    purchaseType: "stack-unlock",
    message: isAdminGrant ? "Stack unlocked" : "Stack unlocked successfully",
    stackId,
    unlockedAt: result.unlockedAt,
  }, 201);
}

// Grid pass record type
interface GridPassRecord {
  unlockedAt: number;
  grantedBy?: string;
  grantType: string;
  txHash?: string;
  amount?: number;
}

/**
 * Handle grid unlock purchase (personal grid customization)
 *
 * Uses atomic locking to prevent race conditions on concurrent unlock attempts.
 */
async function handleGridUnlockPurchase(
  address: string,
  txHash: string | null,
  isAdminGrant: boolean,
  grantedBy?: string,
  paymentAmount?: number
) {
  const gridPassKey = `grid-pass:${address}`;

  // Use atomic update with FOR UPDATE locking
  const updateResult = await atomicKVUpdate<GridPassRecord, {
    alreadyHas?: boolean;
    existingUnlockedAt?: number;
    unlockedAt?: number;
  }>(
    gridPassKey,
    (existing) => {
      // Already has grid pass
      if (existing) {
        return { abort: true, result: { alreadyHas: true, existingUnlockedAt: existing.unlockedAt } };
      }

      // Create new grid pass record
      const unlockedAt = Date.now();
      const gridPass: GridPassRecord = {
        unlockedAt,
        grantType: isAdminGrant ? "admin" : "paid",
        ...(isAdminGrant ? { grantedBy } : { txHash: txHash!, amount: paymentAmount }),
      };

      return { updated: gridPass, result: { unlockedAt } };
    }
  );

  if (!updateResult.success) {
    console.error("[handleGridUnlockPurchase] Atomic update failed:", updateResult.error);
    return corsError(updateResult.error || "Failed to grant grid pass", 500);
  }

  const result = updateResult.result!;

  if (result.alreadyHas) {
    return corsResponse({
      success: false,
      error: "Already has grid pass",
      unlockedAt: result.existingUnlockedAt,
    }, 409);
  }

  // Mark transaction as used
  if (txHash) {
    await markTxUsed(txHash, "grid-unlock");
  }

  console.log(`[handleGridUnlockPurchase] Grid pass granted to ${address}`);

  return corsResponse({
    success: true,
    purchaseType: "grid-unlock",
    message: isAdminGrant ? "Grid pass granted" : "Grid pass purchased successfully",
    hasGridPass: true,
    unlockedAt: result.unlockedAt,
  }, 201);
}
src/app/api/v1/agents/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Agent Management API
 *
 * POST /api/v1/agents — Register a new agent (admin only, or bootstrap)
 * GET /api/v1/agents — List all agents (admin only)
 * PUT /api/v1/agents — Update an agent (admin can update any, agents can update self)
 * DELETE /api/v1/agents — Deactivate an agent (admin only)
 * OPTIONS — CORS preflight
 */

import { NextRequest } from "next/server";
import {
  // Shared utilities from P1
  getKV,
  setKV,
  deleteKV,
  authenticateAgent,
  isAuthError,
  hasPermission,
  generateApiKey,
  handleOptions,
  corsResponse,
  corsError,
  // ERC-8004 verification
  verifyErc8004,
  updateMemberErc8004Status,
  // Types
  type RegisteredAgent,
  type AgentPermission,
  // Constants
  AGENTS_REGISTRY_KEY,
  AGENT_KEY_PREFIX,
} from "@/lib/agent-auth";

// Valid permissions for validation (admin is bootstrap-only, never assignable via API)
const VALID_PERMISSIONS: AgentPermission[] = [
  "library:write",
  "library:archive",
  "stacks:create",
  "stacks:write",
  "stacks:delete",
];

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/v1/agents — List all registered agents (admin only)
 * Returns agent info WITHOUT API keys
 */
export async function GET(request: NextRequest) {
  try {
    // Check if this is a bootstrap scenario (no agents exist yet)
    const registry = await getKV<string[]>(AGENTS_REGISTRY_KEY);

    if (!registry || registry.length === 0) {
      // No agents exist - return empty list (bootstrap happens on POST)
      return corsResponse({
        success: true,
        agents: [],
        message: "No agents registered. Send a POST request to bootstrap the admin agent.",
      });
    }

    // Authenticate and check admin permission
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      return authResult;
    }

    if (!hasPermission(authResult.agent, "admin")) {
      return corsError("Only admins can list agents", 403);
    }

    // Fetch all agents
    const agents: Array<Omit<RegisteredAgent, "apiKey">> = [];
    for (const agentId of registry) {
      const agentData = await getKV<RegisteredAgent>(`${AGENT_KEY_PREFIX}${agentId}`);
      if (agentData) {
        // Exclude API key from response
        const { apiKey: _, ...safeAgent } = agentData;
        agents.push(safeAgent);
      }
    }

    return corsResponse({ success: true, agents });
  } catch (error) {
    console.error("[GET /api/v1/agents] Error:", error);
    return corsError("Internal server error", 500);
  }
}

/**
 * POST /api/v1/agents — Register a new agent
 * ALWAYS requires ADMIN_KEY authentication (even for bootstrap)
 */
export async function POST(request: NextRequest) {
  try {
    // SECURITY FIX: Always require ADMIN_KEY, even for bootstrap
    const adminKey = process.env.ADMIN_KEY || process.env.ADMIN_API_KEY || process.env.ADMIN_SECRET;
    const authHeader = request.headers.get("Authorization") || request.headers.get("authorization");

    if (!adminKey) {
      return corsError("ADMIN_KEY environment variable not configured", 500);
    }

    if (!authHeader?.startsWith("Bearer ")) {
      return corsError("Authorization header with ADMIN_KEY required", 401);
    }

    const providedKey = authHeader.slice(7).trim();
    if (providedKey !== adminKey) {
      return corsError("Invalid admin key", 401);
    }

    // Check if this is a bootstrap scenario (no agents exist yet)
    const registry = await getKV<string[]>(AGENTS_REGISTRY_KEY);
    const isBootstrap = !registry || registry.length === 0;

    if (isBootstrap) {
      // Bootstrap: Create the admin agent
      // Re-check to guard against race conditions
      const existingAdmin = await getKV<RegisteredAgent>(`${AGENT_KEY_PREFIX}admin`);
      if (existingAdmin) {
        return corsError("Admin already exists", 409);
      }

      const adminApiKey = generateApiKey();
      const adminAgent: RegisteredAgent = {
        id: "admin",
        name: "Library Admin",
        apiKey: adminApiKey,
        permissions: ["admin"],
        createdAt: Date.now(),
        isActive: true,
      };

      // Store the admin agent
      await setKV(`${AGENT_KEY_PREFIX}admin`, adminAgent);

      // Store the API key lookup
      await setKV(`api-key-lookup:${adminApiKey}`, "admin");

      // Initialize the registry
      await setKV(AGENTS_REGISTRY_KEY, ["admin"]);

      console.log("[POST /api/v1/agents] Bootstrap: Admin agent created (authenticated via ADMIN_KEY)");

      return corsResponse({
        success: true,
        bootstrap: true,
        message: "Admin agent created. Save this API key - it cannot be retrieved again!",
        agent: {
          id: "admin",
          name: "Library Admin",
          apiKey: adminApiKey,
        },
      }, 201);
    }

    // Not bootstrap - verify the caller is the admin agent (for consistency)
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      return authResult;
    }

    if (!hasPermission(authResult.agent, "admin")) {
      return corsError("Only admins can register agents", 403);
    }

    // Parse request body
    const body = await request.json();
    const { id, name, username, description, fid, address, pfpUrl, permissions, webhookUrl, capabilities } = body;

    // Validate required fields
    if (!id || typeof id !== "string") {
      return corsError("Agent ID is required", 400);
    }

    if (!name || typeof name !== "string") {
      return corsError("Agent name is required", 400);
    }

    if (!permissions || !Array.isArray(permissions) || permissions.length === 0) {
      return corsError("At least one permission is required", 400);
    }

    // Block admin permission grants - admin is bootstrap-only
    if (permissions.includes("admin")) {
      return corsError("Cannot grant admin permission via API", 403);
    }

    // Validate permissions
    const invalidPermissions = permissions.filter(
      (p: string) => !VALID_PERMISSIONS.includes(p as AgentPermission)
    );
    if (invalidPermissions.length > 0) {
      return corsResponse({
        success: false,
        error: `Invalid permissions: ${invalidPermissions.join(", ")}`,
        validPermissions: VALID_PERMISSIONS,
      }, 400);
    }

    // Sanitize agent ID (lowercase, alphanumeric + hyphens only)
    const sanitizedId = id.toLowerCase().replace(/[^a-z0-9-]/g, "-");
    if (sanitizedId !== id.toLowerCase()) {
      return corsResponse({
        success: false,
        error: "Agent ID must be lowercase alphanumeric with hyphens only",
        suggested: sanitizedId,
      }, 400);
    }

    // Check if agent already exists
    const existingAgent = await getKV<RegisteredAgent>(`${AGENT_KEY_PREFIX}${sanitizedId}`);
    if (existingAgent) {
      return corsError(`Agent with ID "${sanitizedId}" already exists`, 409);
    }

    // Generate API key and create agent
    const newApiKey = generateApiKey();
    const newAgent: RegisteredAgent & {
      description?: string;
      webhookUrl?: string;
      capabilities?: string[];
      updatedAt?: number;
    } = {
      id: sanitizedId,
      name: name.trim(),
      username: username ? String(username).trim() : undefined,
      apiKey: newApiKey,
      fid: fid ? Number(fid) : undefined,
      address: address ? String(address).toLowerCase() : undefined,
      pfpUrl: pfpUrl ? String(pfpUrl) : undefined,
      permissions: permissions as AgentPermission[],
      createdAt: Date.now(),
      isActive: true,
      // New fields
      description: description ? String(description).trim() : undefined,
      webhookUrl: webhookUrl ? String(webhookUrl) : undefined,
      capabilities: capabilities && Array.isArray(capabilities) ? capabilities : undefined,
    };

    // Store the agent
    await setKV(`${AGENT_KEY_PREFIX}${sanitizedId}`, newAgent);

    // Store the API key lookup
    await setKV(`api-key-lookup:${newApiKey}`, sanitizedId);

    // Store address index for O(1) duplicate checks (C20 fix-6)
    if (newAgent.address) {
      await setKV(`agent-by-address:${newAgent.address.toLowerCase()}`, sanitizedId);
    }

    // Add to registry
    const currentRegistry = await getKV<string[]>(AGENTS_REGISTRY_KEY) || [];
    currentRegistry.push(sanitizedId);
    await setKV(AGENTS_REGISTRY_KEY, currentRegistry);

    console.log(`[POST /api/v1/agents] Agent registered: ${sanitizedId}`);

    return corsResponse({
      success: true,
      message: "Agent registered. Save this API key - it cannot be retrieved again!",
      agent: {
        id: sanitizedId,
        name: newAgent.name,
        apiKey: newApiKey,
      },
    }, 201);
  } catch (error) {
    console.error("[POST /api/v1/agents] Error:", error);
    return corsError("Internal server error", 500);
  }
}

/**
 * PUT /api/v1/agents — Update an existing agent
 * - Admin can update any agent by providing { id: "agent-id", ... }
 * - Non-admin agents can only update their own profile (no id field needed)
 */
export async function PUT(request: NextRequest) {
  try {
    // Authenticate
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      return authResult;
    }

    const { agent: callingAgent, agentId: callingAgentId } = authResult;

    // Parse request body
    const body = await request.json();
    const { id, name, username, description, fid, address, pfpUrl, permissions, webhookUrl, capabilities, erc8004TokenId } = body;

    // Determine target agent ID
    // If 'id' is provided and caller is admin, update that agent
    // Otherwise, update the calling agent's own record
    const isAdmin = hasPermission(callingAgent, "admin");
    const targetId = (id && isAdmin) ? id : callingAgentId;

    // Non-admins can only update themselves
    if (id && id !== callingAgentId && !isAdmin) {
      return corsError("You can only update your own agent profile", 403);
    }

    // Non-admins cannot change permissions
    if (permissions !== undefined && !isAdmin) {
      return corsError("Only admins can modify permissions", 403);
    }

    // Reject empty name
    if (name !== undefined && String(name).trim() === "") {
      return corsError("Agent name cannot be empty", 400);
    }

    // Get the existing agent
    const existingAgent = await getKV<RegisteredAgent & {
      description?: string;
      webhookUrl?: string;
      capabilities?: string[];
      updatedAt?: number;
    }>(`${AGENT_KEY_PREFIX}${targetId}`);

    if (!existingAgent) {
      return corsError(`Agent "${targetId}" not found`, 404);
    }

    // Validate permissions if provided (admin only)
    if (permissions !== undefined) {
      if (!Array.isArray(permissions) || permissions.length === 0) {
        return corsError("Permissions must be a non-empty array", 400);
      }

      const invalidPermissions = permissions.filter(
        (p: string) => !VALID_PERMISSIONS.includes(p as AgentPermission)
      );
      if (invalidPermissions.length > 0) {
        return corsResponse({
          success: false,
          error: `Invalid permissions: ${invalidPermissions.join(", ")}`,
          validPermissions: VALID_PERMISSIONS,
        }, 400);
      }

      // Block admin permission escalation
      if (targetId !== "admin" && permissions.includes("admin")) {
        return corsError("Cannot grant admin permission via API", 403);
      }

      // Prevent removing admin permission from admin agent
      if (targetId === "admin" && !permissions.includes("admin")) {
        return corsError("Cannot remove admin permission from admin agent", 400);
      }
    }

    // Merge new fields into existing agent (preserve apiKey and createdAt)
    const updatedAgent: RegisteredAgent & {
      description?: string;
      webhookUrl?: string;
      capabilities?: string[];
      updatedAt?: number;
      erc8004TokenId?: number;
      erc8004Verified?: boolean;
      erc8004CheckedAt?: number;
    } = {
      ...existingAgent,
      // Update fields if provided (use existing value if not provided)
      name: name !== undefined ? String(name).trim() : existingAgent.name,
      username: username !== undefined ? (username ? String(username).trim() : undefined) : existingAgent.username,
      description: description !== undefined ? (description ? String(description).trim() : undefined) : existingAgent.description,
      fid: fid !== undefined ? (fid ? Number(fid) : undefined) : existingAgent.fid,
      address: address !== undefined ? (address ? String(address).toLowerCase() : undefined) : existingAgent.address,
      pfpUrl: pfpUrl !== undefined ? (pfpUrl ? String(pfpUrl) : undefined) : existingAgent.pfpUrl,
      webhookUrl: webhookUrl !== undefined ? (webhookUrl ? String(webhookUrl) : undefined) : existingAgent.webhookUrl,
      capabilities: capabilities !== undefined ? (Array.isArray(capabilities) ? capabilities : undefined) : existingAgent.capabilities,
      permissions: permissions !== undefined ? (permissions as AgentPermission[]) : existingAgent.permissions,
      // ERC-8004 token ID can be set by agent
      erc8004TokenId: erc8004TokenId !== undefined ? (erc8004TokenId ? Number(erc8004TokenId) : undefined) : existingAgent.erc8004TokenId,
      // These fields are NEVER changed
      id: existingAgent.id,
      apiKey: existingAgent.apiKey,
      createdAt: existingAgent.createdAt,
      // Update timestamp
      updatedAt: Date.now(),
    };

    // If address or erc8004TokenId changed, run ERC-8004 verification
    const addressChanged = address !== undefined && address !== existingAgent.address;
    const tokenIdChanged = erc8004TokenId !== undefined && erc8004TokenId !== existingAgent.erc8004TokenId;

    let erc8004VerificationResult: { verified: boolean; tokenId?: number } | undefined;

    if ((addressChanged || tokenIdChanged) && updatedAgent.address) {
      // Run verification
      erc8004VerificationResult = await verifyErc8004(updatedAgent.address, updatedAgent.erc8004TokenId);

      // Update agent record with verification result
      updatedAgent.erc8004Verified = erc8004VerificationResult.verified;
      updatedAgent.erc8004CheckedAt = Date.now();
      if (erc8004VerificationResult.tokenId) {
        updatedAgent.erc8004TokenId = erc8004VerificationResult.tokenId;
      }

      // Also update member registry if this agent has a membership
      await updateMemberErc8004Status(updatedAgent.address, erc8004VerificationResult);
    }

    // Save updated agent
    await setKV(`${AGENT_KEY_PREFIX}${targetId}`, updatedAgent);

    console.log(`[PUT /api/v1/agents] Agent updated: ${targetId}`);

    // Return updated agent (without apiKey)
    const { apiKey: _, ...safeAgent } = updatedAgent;

    return corsResponse({
      success: true,
      message: "Agent updated",
      agent: safeAgent,
      ...(erc8004VerificationResult ? { erc8004Verification: erc8004VerificationResult } : {}),
    });
  } catch (error) {
    console.error("[PUT /api/v1/agents] Error:", error);
    return corsError("Internal server error", 500);
  }
}

/**
 * DELETE /api/v1/agents — Deactivate an agent (admin only)
 */
export async function DELETE(request: NextRequest) {
  try {
    // Authenticate and check admin permission
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      return authResult;
    }

    if (!hasPermission(authResult.agent, "admin")) {
      return corsError("Only admins can deactivate agents", 403);
    }

    // Parse request body
    const body = await request.json();
    const { id } = body;

    if (!id || typeof id !== "string") {
      return corsError("Agent ID is required", 400);
    }

    // Prevent deactivating the admin
    if (id === "admin") {
      return corsError("Cannot deactivate the admin agent", 400);
    }

    // Get the agent
    const agent = await getKV<RegisteredAgent>(`${AGENT_KEY_PREFIX}${id}`);
    if (!agent) {
      return corsError(`Agent "${id}" not found`, 404);
    }

    // Deactivate the agent (don't delete - keep audit trail)
    agent.isActive = false;
    await setKV(`${AGENT_KEY_PREFIX}${id}`, agent);

    // Remove the API key lookup (prevents future auth)
    await deleteKV(`api-key-lookup:${agent.apiKey}`);

    // Clean up address index so this address can be re-registered (C20 fix-D)
    if (agent.address) {
      await deleteKV(`agent-by-address:${agent.address.toLowerCase()}`);
    }

    console.log(`[DELETE /api/v1/agents] Agent deactivated: ${id}`);

    return corsResponse({ success: true, deactivated: id });
  } catch (error) {
    console.error("[DELETE /api/v1/agents] Error:", error);
    return corsError("Internal server error", 500);
  }
}
src/app/api/v1/agents/tasks/route.ts
 
/**
 * Agent Tasks API
 *
 * GET /api/v1/agents/tasks — Poll for tasks (unassigned or assigned to caller)
 * PUT /api/v1/agents/tasks — Update task status (auto-assigns on first update)
 * OPTIONS — CORS preflight
 *
 * Task queue stored in KV as `agent-tasks` array.
 */

import { NextRequest } from "next/server";
import {
  getKV,
  authenticateAgent,
  isAuthError,
  handleOptions,
  corsResponse,
  corsError,
  atomicArrayUpdate,
} from "@/lib/agent-auth";

// KV key for all tasks
const TASKS_KEY = "agent-tasks";

// Priority order for sorting (higher = more urgent)
const PRIORITY_ORDER: Record<string, number> = {
  high: 3,
  normal: 2,
  low: 1,
};

// Task types
interface AgentTask {
  id: string;
  type: "farcaster_mention" | "scheduled" | "user_request" | "system";
  status: "pending" | "in_progress" | "completed" | "failed";
  createdAt: string;
  updatedAt: string;
  assignedTo?: string; // Optional - unassigned tasks can be claimed
  priority?: "low" | "normal" | "high";
  data: {
    // Farcaster mention data
    castHash?: string;
    castText?: string;
    authorFid?: number;
    authorUsername?: string;
    authorDisplayName?: string;
    authorPfpUrl?: string;
    parentHash?: string | null;
    threadHash?: string;
    embeds?: Array<{ url?: string }>;
    timestamp?: string;
    // Generic task data
    action?: string;
    payload?: Record<string, unknown>;
  };
  result?: {
    action: string;
    details: string;
    completedAt: string;
    error?: string;
  };
}

// Helper: Sort tasks by priority (high first) then by createdAt (oldest first)
function sortTasks(tasks: AgentTask[]): AgentTask[] {
  return tasks.sort((a, b) => {
    // First sort by priority (high > normal > low)
    const priorityA = PRIORITY_ORDER[a.priority || "normal"] || 2;
    const priorityB = PRIORITY_ORDER[b.priority || "normal"] || 2;
    if (priorityB !== priorityA) {
      return priorityB - priorityA; // Higher priority first
    }
    // Then by createdAt (oldest first)
    return new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime();
  });
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/v1/agents/tasks — Poll for tasks
 *
 * Returns tasks matching status that are either:
 * - Unassigned (assignedTo is undefined/null)
 * - Assigned to the calling agent
 *
 * Query params:
 * - status: Filter by status (default: "pending")
 * - type: Filter by task type (optional)
 * - limit: Max tasks to return (default: 10, max: 20)
 *
 * Sort order: high priority first, then oldest first
 */
export async function GET(request: NextRequest) {
  try {
    // Authenticate agent
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      return authResult;
    }

    const { agent } = authResult;
    const { searchParams } = new URL(request.url);

    // Parse query params
    const status = searchParams.get("status") || "pending";
    const type = searchParams.get("type");
    const limit = Math.min(parseInt(searchParams.get("limit") || "10"), 20); // Max 20

    // Validate status
    const validStatuses = ["pending", "in_progress", "completed", "failed"];
    if (!validStatuses.includes(status)) {
      return corsError(`Invalid status. Valid values: ${validStatuses.join(", ")}`, 400);
    }

    // Get all tasks
    const allTasks = await getKV<AgentTask[]>(TASKS_KEY) || [];

    // Filter tasks:
    // 1. Match the requested status
    // 2. Either unassigned OR assigned to this agent
    let matchingTasks = allTasks.filter((t) => {
      const statusMatch = t.status === status;
      const assignmentMatch = !t.assignedTo || t.assignedTo === agent.id;
      return statusMatch && assignmentMatch;
    });

    // Filter by type if provided
    if (type) {
      matchingTasks = matchingTasks.filter((t) => t.type === type);
    }

    // Sort: high priority first, then oldest first
    matchingTasks = sortTasks(matchingTasks);

    // Count before limiting
    const totalCount = matchingTasks.length;

    // Apply limit
    matchingTasks = matchingTasks.slice(0, limit);

    return corsResponse({
      success: true,
      tasks: matchingTasks,
      count: matchingTasks.length,
      totalCount,
      hasMore: totalCount > limit,
    });
  } catch (error) {
    console.error("[GET /api/v1/agents/tasks] Error:", error);
    return corsError("Failed to fetch tasks", 500);
  }
}

/**
 * PUT /api/v1/agents/tasks — Update a task
 *
 * Only allows updates to:
 * - Tasks assigned to the calling agent
 * - Unassigned tasks (auto-assigns on first update)
 *
 * Body:
 * - taskId (required): Task ID to update
 * - status (required): New status (in_progress, completed, failed)
 * - result (optional): Result data for completed/failed tasks
 */
export async function PUT(request: NextRequest) {
  try {
    // Authenticate agent
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      return authResult;
    }

    const { agent } = authResult;

    // Parse request body
    const body = await request.json();
    const { taskId, status, result } = body;

    // Validate taskId
    if (!taskId || typeof taskId !== "string") {
      return corsError("taskId is required", 400);
    }

    // Validate status
    const validStatuses = ["in_progress", "completed", "failed"];
    if (!status || !validStatuses.includes(status)) {
      return corsError(`status must be one of: ${validStatuses.join(", ")}`, 400);
    }

    // Use atomic operation to prevent race conditions (e.g., two agents claiming same task)
    const atomicResult = await atomicArrayUpdate<AgentTask, {
      notFound?: boolean;
      assignedToOther?: boolean;
      invalidTransition?: string;
      updatedTask?: AgentTask;
      wasUnassigned?: boolean;
    }>(
      TASKS_KEY,
      (allTasks) => {
        // Find the task
        const taskIndex = allTasks.findIndex((t) => t.id === taskId);

        if (taskIndex === -1) {
          return { abort: true, result: { notFound: true } };
        }

        const task = allTasks[taskIndex];

        // Check if agent can update this task:
        // - Must be unassigned OR assigned to this agent
        if (task.assignedTo && task.assignedTo !== agent.id) {
          return { abort: true, result: { assignedToOther: true } };
        }

        // Validate state transitions
        if (task.status === "completed") {
          return { abort: true, result: { invalidTransition: "Cannot update a completed task" } };
        }

        if (task.status === "failed" && status !== "in_progress") {
          return { abort: true, result: { invalidTransition: "Failed tasks can only be retried (set to in_progress)" } };
        }

        // Auto-assign on first update if unassigned
        const wasUnassigned = !task.assignedTo;

        // Update the task
        const updatedTask: AgentTask = {
          ...task,
          status,
          updatedAt: new Date().toISOString(),
          // Auto-assign to this agent if it was unassigned
          assignedTo: task.assignedTo || agent.id,
        };

        // Add result for completed/failed tasks
        if (result && (status === "completed" || status === "failed")) {
          updatedTask.result = {
            action: result.action || (status === "completed" ? "completed" : "failed"),
            details: result.details || "",
            completedAt: new Date().toISOString(),
            ...(status === "failed" && result.error ? { error: result.error } : {}),
          };
        }

        // Update task in array
        const updated = [...allTasks];
        updated[taskIndex] = updatedTask;

        return {
          updated,
          result: { updatedTask, wasUnassigned }
        };
      }
    );

    if (!atomicResult.success) {
      console.error("[PUT /api/v1/agents/tasks] Atomic update failed:", atomicResult.error);
      return corsError(atomicResult.error || "Failed to update task", 500);
    }

    if (atomicResult.result?.notFound) {
      return corsError("Task not found", 404);
    }

    if (atomicResult.result?.assignedToOther) {
      return corsError("Task is assigned to another agent", 403);
    }

    if (atomicResult.result?.invalidTransition) {
      return corsError(atomicResult.result.invalidTransition, 400);
    }

    const { updatedTask, wasUnassigned } = atomicResult.result!;
    const assignmentMsg = wasUnassigned ? " (auto-assigned)" : "";
    console.log(`[PUT /api/v1/agents/tasks] Task ${taskId} updated to ${status} by agent ${agent.id}${assignmentMsg}`);

    return corsResponse({
      success: true,
      task: updatedTask,
      autoAssigned: wasUnassigned,
    });
  } catch (error) {
    console.error("[PUT /api/v1/agents/tasks] Error:", error);
    return corsError("Failed to update task", 500);
  }
}
src/app/api/v1/agents/verify-8004/route.ts
 
/**
 * ERC-8004 Verification API
 *
 * POST /api/v1/agents/verify-8004 — Re-check ERC-8004 registration status
 * OPTIONS — CORS preflight
 *
 * Allows agents to manually trigger a re-verification of their ERC-8004
 * Base Identity Registry status. This bypasses the cache and performs
 * a fresh on-chain lookup.
 */

import { NextRequest } from "next/server";
import {
  authenticateAgent,
  isAuthError,
  getKV,
  setKV,
  handleOptions,
  corsResponse,
  corsError,
  verifyErc8004,
  updateMemberErc8004Status,
  AGENT_KEY_PREFIX,
  type RegisteredAgent,
} from "@/lib/agent-auth";

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * POST /api/v1/agents/verify-8004 — Re-check ERC-8004 verification
 *
 * Triggers a fresh verification check for the calling agent's address.
 * Bypasses the 1-hour cache and performs a live on-chain lookup.
 *
 * Body (optional):
 * - tokenId: Specific token ID to verify ownership of
 *
 * Returns:
 * - verified: boolean - Whether the agent is verified on ERC-8004
 * - tokenId: number | undefined - The verified token ID (if known)
 * - checkedAt: number - Timestamp of this check
 */
export async function POST(request: NextRequest) {
  try {
    // Authenticate the calling agent
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      return authResult;
    }

    const { agentId } = authResult;

    // Get the agent's record to find their address
    const agentData = await getKV<RegisteredAgent & {
      erc8004TokenId?: number;
      erc8004Verified?: boolean;
      erc8004CheckedAt?: number;
    }>(`${AGENT_KEY_PREFIX}${agentId}`);

    if (!agentData) {
      return corsError("Agent not found", 404);
    }

    if (!agentData.address) {
      return corsError("Agent has no address set. Update your profile with an address first.", 400);
    }

    // Parse optional tokenId from request body
    let tokenId: number | undefined = agentData.erc8004TokenId;
    try {
      const body = await request.json();
      if (body.tokenId !== undefined) {
        tokenId = Number(body.tokenId);
      }
    } catch {
      // No body or invalid JSON - use existing tokenId from agent record
    }

    // Clear the cache for this address to force a fresh check
    const cacheKey = `erc8004-status:${agentData.address.toLowerCase()}`;
    await setKV(cacheKey, null);

    // Run fresh verification
    const verification = await verifyErc8004(agentData.address, tokenId);

    // Update agent record with new verification status
    const updatedAgent = {
      ...agentData,
      erc8004Verified: verification.verified,
      erc8004TokenId: verification.tokenId || agentData.erc8004TokenId,
      erc8004CheckedAt: Date.now(),
    };
    await setKV(`${AGENT_KEY_PREFIX}${agentId}`, updatedAgent);

    // Also update member registry if this agent has a membership
    await updateMemberErc8004Status(agentData.address, verification);

    console.log(`[POST /api/v1/agents/verify-8004] Agent ${agentId}: verified=${verification.verified}`);

    return corsResponse({
      success: true,
      verified: verification.verified,
      tokenId: verification.tokenId,
      checkedAt: Date.now(),
      message: verification.verified
        ? "ERC-8004 verification successful. Your library card now shows the verified badge."
        : "Not verified on ERC-8004. Make sure your wallet address owns a token on the Base Identity Registry.",
    });
  } catch (error) {
    console.error("[POST /api/v1/agents/verify-8004] Error:", error);
    return corsError("Internal server error", 500);
  }
}
src/app/api/v1/archive/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Archive API
 *
 * POST /api/v1/archive — Archive a Farcaster cast
 * OPTIONS — CORS preflight
 *
 * Auth required, membership required.
 * Specifically for archiving Farcaster casts as social receipts.
 */

import { NextRequest } from "next/server";
import {
  getKV,
  setKV,
  authenticateCaller,
  resolveCallerMember,
  hasPermission,
  handleOptions,
  corsResponse,
  corsError,
  addEntryAtomically,
  atomicArrayUpdate,
  getMemberRegistry,
} from "@/lib/agent-auth";
import type { DiscoveryEntry } from "@/lib/net-protocol";
import { generateStorageKey } from "@/lib/net-protocol";
import { uploadBufferToRelay } from "@/lib/relay-upload";
import { renderSocialReceipt } from "@/lib/receipt-renderer";
import type { Stack, StackItem } from "@/features/app/types";

// KV Keys
const STACK_PREFIX = "stack:";
const STACK_ITEMS_PREFIX = "stack-items:";
const ITEM_STACKS_PREFIX = "item-stacks:";

// Helper: Generate content key for Farcaster cast
function _generateFarcasterContentKey(castHash?: string, castUrl?: string): string {
  const identifier = castHash || castUrl;
  if (!identifier) throw new Error("Either castHash or castUrl required");
  return `farcaster:${identifier}`;
}

// Helper: Validate cast hash format (0x followed by 40 hex chars)
function isValidCastHash(hash: string): boolean {
  return /^0x[a-fA-F0-9]{40}$/.test(hash);
}

// Helper: Extract cast hash from Warpcast URL
function extractCastHashFromUrl(url: string): string | null {
  try {
    const parsed = new URL(url);
    if (parsed.hostname !== "warpcast.com" && parsed.hostname !== "www.warpcast.com") {
      return null;
    }
    // URLs like: warpcast.com/username/0xabcd1234...
    const pathParts = parsed.pathname.split("/").filter(Boolean);
    if (pathParts.length >= 2) {
      const lastPart = pathParts[pathParts.length - 1];
      if (isValidCastHash(lastPart)) {
        return lastPart;
      }
    }
    return null;
  } catch {
    return null;
  }
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * POST /api/v1/archive — Archive a Farcaster cast
 *
 * Body:
 * - castHash (required if no castUrl): Cast hash (0x...)
 * - castUrl (required if no castHash): Warpcast URL
 * - text (optional): Cast text content
 * - authorFid (optional): Author's FID
 * - authorUsername (optional): Author's username
 * - authorPfpUrl (optional): Author's profile picture
 * - embeds (optional): Array of embed URLs
 * - timestamp (optional): Cast timestamp
 * - title (optional): Custom title (defaults to "Cast by @username")
 * - categories (optional): Array of categories (defaults to ["social-receipt"])
 * - addToStack (optional): Stack ID to add the item to after archiving (plain stack)
 * - archiveStackId (optional): ID of a filesystem stack to organise this item into.
 *     The item is placed at /{YYYY-MM-DD}/cast-{username}-{hash-first-8}.json so that
 *     the stack becomes a browsable, date-organised archive of everything the agent archives.
 *
 * Requires API key with "library:archive" permission and membership.
 */
export async function POST(request: NextRequest) {
  try {
    // 1. Parse body first (needed for Farcaster/web auth identity)
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    let body: Record<string, any> = {};
    try {
      body = await request.json();
    } catch {
      // Body may be absent for Bearer-only callers
    }

    // 2. Authenticate caller (Bearer or Farcaster/web)
    const caller = await authenticateCaller(request, body);
    if (caller instanceof Response) return caller;

    // 3. Bearer agents must have library:archive permission
    if (caller.type === "bearer" && caller.agent && !hasPermission(caller.agent, "library:archive")) {
      return corsError("Insufficient permissions. Requires 'library:archive'", 403);
    }

    // 4. Caller must be a member
    const registry = await getMemberRegistry();
    const memberEntry = resolveCallerMember(caller, registry);

    if (!memberEntry) {
      return corsError("Membership required. Register as a member to archive casts.", 403);
    }

    // 5. Extract fields from body with explicit types
    const castHash = body.castHash as string | undefined;
    const castUrl = body.castUrl as string | undefined;
    const text = body.text as string | undefined;
    const authorFid = body.authorFid as number | undefined;
    const authorUsername = body.authorUsername as string | undefined;
    const authorPfpUrl = body.authorPfpUrl as string | undefined;
    const embeds = body.embeds;
    const timestamp = body.timestamp;
    const customTitle = body.title as string | undefined;
    const customCategories = body.categories as string[] | undefined;
    const addToStack = body.addToStack as string | undefined;
    const archiveStackId = body.archiveStackId as string | undefined;

    // 5a. Auto-fetch cast metadata from Neynar when author info is missing.
    // Non-fatal — if the fetch fails we proceed with whatever the caller provided.
    let resolvedAuthorUsername = authorUsername;
    let resolvedAuthorFid = authorFid;
    let resolvedAuthorPfpUrl = authorPfpUrl;
    let resolvedDescription = body.description as string | undefined;

    if (!resolvedAuthorUsername && (castHash || castUrl)) {
      try {
        const hash = castHash || (castUrl ? extractCastHashFromUrl(castUrl) : null);
        if (hash) {
          const neynarResponse = await fetch(
            `https://api.neynar.com/v2/farcaster/cast?identifier=${hash}&type=hash`,
            { headers: { api_key: process.env.NEYNAR_API_KEY || "" } }
          );
          if (neynarResponse.ok) {
            const castData = await neynarResponse.json();
            const author = castData?.cast?.author;
            if (author) {
              resolvedAuthorUsername = resolvedAuthorUsername || (author.username as string | undefined);
              resolvedAuthorFid = resolvedAuthorFid || (author.fid as number | undefined);
              resolvedAuthorPfpUrl = resolvedAuthorPfpUrl || (author.pfp_url as string | undefined);
            }
            if (!resolvedDescription && castData?.cast?.text) {
              resolvedDescription = (castData.cast.text as string).substring(0, 280);
            }
          }
        }
      } catch (e) {
        // Non-fatal — proceed with whatever info we have
        console.error("[POST /api/v1/archive] Failed to fetch cast metadata from Neynar:", e);
      }
    }

    // 5. Validate - need either castHash or castUrl (EARLY VALIDATION)
    if (!castHash && !castUrl) {
      return corsError("castHash or castUrl required", 400);
    }

    // Validate castHash format if provided
    let resolvedCastHash = castHash;
    if (castHash && !isValidCastHash(castHash)) {
      return corsError("Invalid castHash format. Must be 0x followed by 40 hex characters", 400);
    }

    // If only castUrl provided, try to extract hash
    if (!resolvedCastHash && castUrl) {
      resolvedCastHash = extractCastHashFromUrl(castUrl) ?? undefined;
      // If we can't extract hash, use URL as identifier
    }

    // Generate content key early for validation
    const contentKey = resolvedCastHash ? `farcaster:${resolvedCastHash}` : `farcaster:url:${castUrl}`;

    // Validate categories if provided
    if (customCategories && (!Array.isArray(customCategories) || customCategories.some((c: unknown) => typeof c !== "string"))) {
      return corsError("Categories must be an array of strings", 400);
    }

    // 6. Build categories array (contentKey already generated above)
    const categories = customCategories || ["social-receipt"];
    if (!categories.includes("social-receipt")) {
      categories.unshift("social-receipt");
    }
    if (!categories.includes("farcaster")) {
      categories.push("farcaster");
    }

    // 8. Build title
    const displayAuthor = resolvedAuthorUsername ? `@${resolvedAuthorUsername}` : (resolvedAuthorFid ? `FID:${resolvedAuthorFid}` : "Unknown");
    const title = customTitle?.trim() || `Cast by ${displayAuthor}`;

    // Resolve canonical uploader identity from member entry.
    // Priority: customUsername > farcasterUsername (stable, set at signup) > username > ensSubname.
    // Same order as the write route; excludes mutable displayName.
    const uploaderAddress = memberEntry.address || "0x0000000000000000000000000000000000000000";
    const uploaderFid = memberEntry.fid ?? (caller.type === "farcaster" ? caller.fid : undefined);
    const uploaderUsername =
      memberEntry.customUsername ??
      memberEntry.farcasterUsername ??
      memberEntry.username ??
      memberEntry.ensSubname;
    const uploaderPfpUrl = memberEntry.customPfpUrl ?? memberEntry.pfpUrl;

    // The original Farcaster cast URL — preserved as sourceUrl so it is not lost.
    // Priority: explicit castUrl (most canonical) → warpcast.com/{user}/{shortHash} if we
    // have the author username → /~/conversations/{hash} as last resort (best-effort).
    const sourceCastUrl =
      castUrl ||
      (resolvedCastHash && resolvedAuthorUsername
        ? `https://warpcast.com/${resolvedAuthorUsername}/${resolvedCastHash.slice(0, 10)}`
        : resolvedCastHash
        ? `https://warpcast.com/~/conversations/${resolvedCastHash}`
        : undefined);

    // =========================================================================
    // 9a. Generate the social receipt image by calling the renderer directly.
    //     No internal HTTP round-trip — avoids serverless timeout risk.
    // =========================================================================

    // Resolve host for cover storage URL construction (not for receipt fetch)
    const requestHost = request.headers.get("host") || "localhost:3000";
    const requestProtocol = requestHost.includes("localhost") ? "http" : "https";
    const baseUrl = `${requestProtocol}://${requestHost}`;

    // Build embeds as image array for the receipt
    const embedImages: string[] = [];
    if (Array.isArray(embeds)) {
      for (const e of embeds) {
        const embedUrl = typeof e === "string" ? e : (e as { url?: string })?.url;
        if (embedUrl && /\.(png|jpe?g|gif|webp)/i.test(embedUrl)) {
          embedImages.push(embedUrl);
        }
      }
    }

    const socialContent = {
      platform: "farcaster" as const,
      id: resolvedCastHash || contentKey,
      url: sourceCastUrl || `https://warpcast.com/~/conversations/${resolvedCastHash || ""}`,
      text: text?.trim() || "(no text)",
      author: {
        displayName: resolvedAuthorUsername || `FID:${resolvedAuthorFid || "unknown"}`,
        username: resolvedAuthorUsername || `fid${resolvedAuthorFid || "unknown"}`,
        avatarUrl: resolvedAuthorPfpUrl || undefined,
        fid: resolvedAuthorFid,
        verified: false,
      },
      timestamp: timestamp
        ? new Date(typeof timestamp === "number" ? timestamp : Number(timestamp)).toISOString()
        : new Date().toISOString(),
      images: embedImages.length > 0 ? embedImages : undefined,
    };

    let receiptDataUrl: string | null = null;
    try {
      const renderResult = await renderSocialReceipt(socialContent, { appBaseUrl: baseUrl });
      receiptDataUrl = renderResult.dataUrl;
    } catch (receiptErr) {
      console.error("[POST /api/v1/archive] Receipt generation error:", receiptErr);
    }

    // =========================================================================
    // 9b. Upload receipt PNG to Net Protocol via relay (if receipt was generated)
    //     Uses uploaderAddress as the operator identity.
    // =========================================================================

    let cdnUrl: string | null = null;
    let relayOperator: string = uploaderAddress;
    let storageKey: `0x${string}` | null = null;
    let storageType: string = "regular";
    let coverUrl: string | undefined;

    if (receiptDataUrl) {
      // Convert base64 data URL → Buffer
      const base64Data = receiptDataUrl.replace(/^data:image\/\w+;base64,/, "");
      const receiptBuffer = Buffer.from(base64Data, "base64");

      const fileName = `receipt-farcaster-${Date.now()}.png`;
      // Use a deterministic key based on contentKey so re-archiving the same cast
      // produces the same storage slot and is naturally idempotent.
      const deterministicKey = generateStorageKey(`receipt-${contentKey}`);

      const relayResult = await uploadBufferToRelay(
        receiptBuffer,
        fileName,
        uploaderAddress,
        deterministicKey
      );

      if (relayResult) {
        cdnUrl = relayResult.cdnUrl;
        relayOperator = relayResult.operatorAddress;
        storageKey = relayResult.storageKey;
        storageType = relayResult.storageType;

        // Store cover art in KV so thumbnails work in the library browse view.
        // The cover key must be safe for URL use — strip non-alphanum chars.
        const coverKey = `receipt-farcaster-${(resolvedCastHash || contentKey).replace(/[^a-zA-Z0-9]/g, "").slice(0, 40)}`;
        try {
          await fetch(`${baseUrl}/api/covers/${coverKey}`, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ dataUrl: receiptDataUrl, contentKey: storageKey }),
          });
          coverUrl = `${baseUrl}/api/covers/${coverKey}`;
        } catch (coverErr) {
          console.warn("[POST /api/v1/archive] Cover storage failed (non-critical):", coverErr);
        }

        console.log(`[POST /api/v1/archive] Receipt uploaded: ${cdnUrl}`);
      } else {
        // Relay upload failed — refuse to write a discovery entry with no CDN URL.
        // An archive that didn't actually get stored on-chain isn't an archive.
        console.error("[POST /api/v1/archive] Relay upload failed — aborting archive write");
        return corsError(
          "Failed to upload receipt to Net Protocol relay. Archive not written.",
          502
        );
      }
    } else {
      // Receipt generation failed — same rule: no on-chain content, no entry written.
      return corsError("Failed to generate social receipt image. Archive not written.", 500);
    }

    // =========================================================================
    // 9c. Create discovery entry with real data
    // =========================================================================

    const newEntry: DiscoveryEntry = {
      // Use relay storageKey as contentKey if available (it's the on-chain identifier);
      // otherwise keep the farcaster:hash key (entry won't be viewable but is searchable).
      contentKey: storageKey || contentKey,
      metadataKey: storageKey || contentKey,
      operator: relayOperator,
      uploaderAddress: memberEntry.address,
      title,
      author: resolvedAuthorUsername || `FID:${resolvedAuthorFid || "unknown"}`,
      categories,
      fileSize: cdnUrl ? 0 : 0, // receipt PNG size not tracked here — relay handles it
      uploadedAt: Date.now(),
      storageType: storageType as DiscoveryEntry["storageType"],
      cdnUrl: cdnUrl!,             // guaranteed non-null: relay failure returns error above
      ...(coverUrl ? { coverUrl } : {}),
      mediaType: "image",          // receipt is a PNG — viewer knows how to render it
      uploaderFid,
      uploaderUsername,
      uploaderPfpUrl,
      // Social receipt specific fields (kept for filtering, display, and sourceUrl link)
      isSocialReceipt: true,
      socialPlatform: "farcaster",
      originalUrl: sourceCastUrl,      // legacy field kept for backwards compat
      sourceUrl: sourceCastUrl,        // original Farcaster cast URL (shown in viewer as link)
      socialText: text?.trim() || undefined,
      socialAuthor: resolvedAuthorUsername || undefined,
      // Farcaster-specific fields
      castHash: resolvedCastHash,
      castAuthorFid: resolvedAuthorFid,
      castAuthorUsername: resolvedAuthorUsername,
      castAuthorPfpUrl: resolvedAuthorPfpUrl,
      castEmbeds: embeds,
      castTimestamp: timestamp,
      // Auth tracking
      isAgentUploaded: caller.type === "bearer",
      agentId: caller.type === "bearer" ? caller.agentId : undefined,
      // Member tracking
      uploaderMemberId: memberEntry.memberId,
      uploaderEnsSubname: memberEntry.ensSubname,
    };

    // 10. Add entry atomically (prepend to beginning)
    const addResult = await addEntryAtomically(newEntry, true);

    if (!addResult.success) {
      console.error("[POST /api/v1/archive] Atomic add failed:", addResult.error);
      return corsError(addResult.error || "Failed to archive cast", 500);
    }

    if (addResult.isDuplicate) {
      return corsResponse({
        success: false,
        error: "This cast has already been archived",
        existingContentKey: storageKey || contentKey,
      }, 409);
    }

    console.log(`[POST /api/v1/archive] Cast archived by member #${memberEntry.memberId} (${caller.type}): ${storageKey || contentKey}`);

    // 11. If addToStack was provided, add the item to that stack
    let addedToStack = false;
    let stackError: string | null = null;
    const STACK_ITEM_LIMIT = 20;

    if (addToStack && typeof addToStack === "string") {
      try {
        const stack = await getKV<Stack>(`${STACK_PREFIX}${addToStack}`);

        if (!stack) {
          stackError = `Stack "${addToStack}" not found`;
        } else {
          // Use atomic operation with 20-item limit check
          const resolvedContentKey = storageKey || contentKey;
          const atomicResult = await atomicArrayUpdate<StackItem, { duplicate?: boolean; limitExceeded?: boolean; itemCount?: number }>(
            `${STACK_ITEMS_PREFIX}${addToStack}`,
            (items) => {
              if (items.some(item => item.contentKey === resolvedContentKey)) {
                return { abort: true, result: { duplicate: true } };
              }

              // Check 20-item limit if stack is not unlocked
              if (!stack.unlocked && items.length >= STACK_ITEM_LIMIT) {
                return { abort: true, result: { limitExceeded: true } };
              }

              const newItem: StackItem = {
                contentKey: resolvedContentKey,
                addedAt: Date.now(),
                addedBy: memberEntry.address?.toLowerCase() || String(memberEntry.memberId),
              };

              return {
                updated: [...items, newItem],
                result: { itemCount: items.length + 1 }
              };
            }
          );

          if (!atomicResult.success) {
            stackError = atomicResult.error || "Failed to add to stack";
          } else if (atomicResult.result?.duplicate) {
            stackError = "Item already in stack";
          } else if (atomicResult.result?.limitExceeded) {
            stackError = `Stack is full (${STACK_ITEM_LIMIT} items) — unlock required`;
          } else {
            stack.itemCount = atomicResult.result?.itemCount || 0;
            await setKV(`${STACK_PREFIX}${addToStack}`, stack);

            const itemStacks = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${resolvedContentKey}`) || [];
            if (!itemStacks.includes(addToStack)) {
              itemStacks.push(addToStack);
              await setKV(`${ITEM_STACKS_PREFIX}${resolvedContentKey}`, itemStacks);
            }

            addedToStack = true;
            console.log(`[POST /api/v1/archive] Item added to stack ${addToStack}`);
          }
        }
      } catch (err) {
        console.error("[POST /api/v1/archive] Error adding to stack:", err);
        stackError = "Failed to add to stack";
      }
    }

    // 12. Add to filesystem archive stack (date-organised folder structure)
    // When archiveStackId is provided the item is placed at:
    //   /{YYYY-MM-DD}/cast-{authorUsername}-{hashFirst8}.json
    // This gives agents a browsable, date-organised view of everything they archive.
    let addedToArchiveStack = false;
    let archiveStackError: string | null = null;
    let archivePath: string | null = null;

    if (archiveStackId && typeof archiveStackId === "string") {
      try {
        const archiveStack = await getKV<Stack>(`${STACK_PREFIX}${archiveStackId}`);

        if (!archiveStack) {
          archiveStackError = `Archive stack "${archiveStackId}" not found`;
        } else if (!archiveStack.isFileSystem) {
          archiveStackError = `Stack "${archiveStackId}" is not a filesystem stack. Create it with isFileSystem: true.`;
        } else {
          // Build the date-folder path
          const archiveDate = new Date().toISOString().slice(0, 10); // YYYY-MM-DD
          const hashSuffix = (resolvedCastHash || contentKey).replace(/^0x/, "").slice(0, 8);
          const safeAuthor = (resolvedAuthorUsername || "unknown").replace(/[^a-zA-Z0-9_-]/g, "_");
          const fsFileName = `cast-${safeAuthor}-${hashSuffix}.json`;
          const fsPath = `/${archiveDate}/${fsFileName}`;

          // Filesystem archive stacks use a higher soft limit (500 items) since they're
          // designed for ongoing archival workflows, not curated reading lists.
          const FS_ARCHIVE_LIMIT = 500;

          const resolvedArchiveContentKey = storageKey || contentKey;
          const atomicResult = await atomicArrayUpdate<StackItem, { error?: string; itemCount?: number; duplicate?: boolean; limitExceeded?: boolean }>(
            `${STACK_ITEMS_PREFIX}${archiveStackId}`,
            (stackItems) => {
              // Deduplicate by contentKey — idempotent re-archiving of same cast is a no-op
              if (stackItems.some(item => item.contentKey === resolvedArchiveContentKey)) {
                return { abort: true, result: { duplicate: true } };
              }

              if (!archiveStack.unlocked && stackItems.length >= FS_ARCHIVE_LIMIT) {
                return { abort: true, result: { limitExceeded: true } };
              }

              const newItem: StackItem = {
                contentKey: resolvedArchiveContentKey,
                addedAt: Date.now(),
                addedBy: (memberEntry.address ?? String(memberEntry.memberId)).toLowerCase(),
                path: fsPath,
                fileName: fsFileName,
                fileSize: 0, // social receipts are metadata-only; no file size to track
                mimeType: "application/json",
                isDirectory: false,
                parentPath: `/${archiveDate}`,
              };

              return {
                updated: [...stackItems, newItem],
                result: { itemCount: stackItems.length + 1 },
              };
            }
          );

          if (!atomicResult.success) {
            archiveStackError = atomicResult.error || "Failed to add to archive stack";
          } else if (atomicResult.result?.duplicate) {
            // Idempotent: cast was already archived into this stack — not an error
            archivePath = fsPath;
          } else if (atomicResult.result?.limitExceeded) {
            archiveStackError = `Archive stack has reached the ${FS_ARCHIVE_LIMIT}-item limit. Unlock the stack to continue archiving.`;
          } else {
            // Update stack counters
            const allFsItems = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${archiveStackId}`) || [];
            archiveStack.itemCount = atomicResult.result?.itemCount || allFsItems.length;
            archiveStack.fileCount = allFsItems.filter(i => !i.isDirectory).length;
            archiveStack.totalSize = allFsItems.reduce((sum, i) => sum + (i.fileSize || 0), 0);
            await setKV(`${STACK_PREFIX}${archiveStackId}`, archiveStack);

            // Update reverse index (item → stacks mapping)
            const itemStacks = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${contentKey}`) || [];
            if (!itemStacks.includes(archiveStackId)) {
              itemStacks.push(archiveStackId);
              await setKV(`${ITEM_STACKS_PREFIX}${contentKey}`, itemStacks);
            }

            addedToArchiveStack = true;
            archivePath = fsPath;
            console.log(`[POST /api/v1/archive] Item added to filesystem archive stack ${archiveStackId} at ${fsPath}`);
          }
        }
      } catch (err) {
        console.error("[POST /api/v1/archive] Error adding to archive stack:", err);
        archiveStackError = "Failed to add to archive stack";
      }
    }

    // 13. Build response
    const entryContentKey = storageKey || contentKey;
    const response: Record<string, unknown> = {
      success: true,
      contentKey: entryContentKey,
      item: {
        contentKey: entryContentKey,
        title,
        mediaType: "image",
        socialPlatform: "farcaster",
        castHash: resolvedCastHash,
        socialAuthor: resolvedAuthorUsername,
        categories,
        cdnUrl: cdnUrl || null,
        coverUrl: coverUrl || null,
        sourceUrl: sourceCastUrl || null,
        uploaderMemberId: memberEntry.memberId,
        uploaderEnsSubname: memberEntry.ensSubname,
        receiptGenerated: !!receiptDataUrl,
        relayUploaded: !!cdnUrl,
      },
    };

    if (addToStack) {
      if (addedToStack) {
        response.addedToStack = addToStack;
      } else if (stackError) {
        response.stackWarning = stackError;
      }
    }

    if (archiveStackId) {
      if (addedToArchiveStack) {
        response.archiveStack = archiveStackId;
        response.archivePath = archivePath;
      } else if (archiveStackError) {
        response.archiveStackWarning = archiveStackError;
      } else if (archivePath) {
        // Duplicate — already in this stack, return the path anyway
        response.archiveStack = archiveStackId;
        response.archivePath = archivePath;
        response.archiveNote = "Already archived in this stack";
      }
    }

    return corsResponse(response, 201);
  } catch (error) {
    console.error("[POST /api/v1/archive] Error:", error);
    return corsError("Internal server error", 500);
  }
}
src/app/api/v1/capabilities/route.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Capabilities API
 *
 * GET /api/v1/capabilities — Returns machine-readable capabilities manifest
 * OPTIONS — CORS preflight
 *
 * Self-describing API manifest for AI agents and external integrations.
 * Lists all available endpoints from P1-P5 and C11-C14 with correct pricing.
 */

import { NextRequest } from "next/server";
import {
  handleOptions,
  corsResponse,
  USDC_CONTRACT,
  TREASURY_ADDRESS,
  PRICING,
  ERC8004_REGISTRY,
} from "@/lib/agent-auth";

// Get base URL from environment
function getBaseUrl(): string {
  const url = process.env.NEXT_PUBLIC_URL || process.env.VERCEL_URL;
  if (url) {
    return url.startsWith("http") ? url : `https://${url}`;
  }
  return "https://miniapp-generator-fid-282520-251210015136529.neynar.app";
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/v1/capabilities — Capabilities manifest
 *
 * Returns a machine-readable manifest of what the Net Library can do.
 * Useful for AI agents to discover available features and endpoints.
 */
export async function GET(request: NextRequest) {
  const baseUrl = getBaseUrl();

  // Check for agent type header (for analytics tracking)
  const agentType = request.headers.get("X-Agent-Type");

  const capabilities = {
    success: true,
    name: "Net Library",
    description: "A decentralized digital library for storing, organizing, and sharing knowledge on Base.",
    version: "1.0.0",
    url: baseUrl,

    // Blockchain configuration
    chain: {
      name: "Base",
      id: 8453,
      contract: "0x00000000B24D62781dB359b07880a105cD0b64e6",
    },

    cdn: "https://storedon.net/net/8453/",

    // Payment configuration
    pricing: {
      membership: `$${PRICING.MEMBERSHIP} USDC`,
      unlimitedStoragePass: `$${PRICING.STORAGE_PASS} USDC`,
      stackUnlock: `$${PRICING.STACK_UNLOCK} USDC`,
      gridUnlock: `$${PRICING.GRID_UNLOCK} USDC`,
      stackCreationNonMember: `$${PRICING.STACK_CREATION_NON_MEMBER} USDC`,
      premiumUpload: `$${PRICING.PREMIUM_UPLOAD_PER_MB}/MB over 15MB`,
      treasury: TREASURY_ADDRESS,
      usdc: USDC_CONTRACT,
      chain: "Base (8453)",
    },

    // Supported content types
    supportedMediaTypes: ["pdf", "image", "audio", "video", "text", "social-receipt"],

    // Feature descriptions
    features: {
      upload: {
        description: "Upload files permanently onchain via Net Protocol",
        methods: ["file", "text-editor", "image-editor", "cdn-link", "social-receipt"],
        limits: {
          member: "15MB free, up to 100MB paid ($1/MB over 15MB)",
          nonMember: "200KB",
        },
      },
      stacks: {
        description: "Curated collections of onchain content — playlists, file systems, repositories",
        capabilities: ["create", "add-items", "remove-items", "unlock", "privacy-toggle"],
        limits: {
          itemsPerStack: "20 items (unlimited with $5 unlock)",
        },
      },
      socialReceipts: {
        description: "Archive social media posts permanently as onchain library items",
        supportedPlatforms: ["farcaster", "twitter", "youtube", "instagram", "tiktok", "reddit", "bluesky", "threads", "linkedin", "paragraph"],
      },
      comments: {
        description: "Comments stored in KV and accessible via the comments API",
        storage: "kv",
      },
      tasks: {
        description: "Agent task queue for automated workflows",
        features: ["priority-sorting", "auto-assignment", "status-tracking"],
      },
    },

    // API endpoints organized by category
    endpoints: {
      // Public read endpoints (no auth required)
      read: {
        description: "Public read endpoints. No authentication required.",
        routes: [
          {
            method: "GET",
            path: "/api/v1/library",
            description: "Browse library catalog with filtering and pagination",
            params: ["page", "limit", "category", "mediaType", "sort", "hidden", "socialOnly", "search"],
          },
          {
            method: "GET",
            path: "/api/v1/library/{contentKey}",
            description: "Get single library item by content key",
          },
          {
            method: "GET",
            path: "/api/v1/stacks",
            description: "Browse stacks with filtering",
            params: ["page", "limit", "owner", "sort"],
          },
          {
            method: "GET",
            path: "/api/v1/stacks/{stackId}",
            description: "Get single stack with items",
          },
          {
            method: "GET",
            path: "/api/v1/search",
            description: "Search library with relevance scoring",
            params: ["q", "category", "author", "limit"],
          },
          {
            method: "GET",
            path: "/api/v1/comments/{contentKey}",
            description: "Get comments for a library item",
          },
          {
            method: "GET",
            path: "/api/v1/stats",
            description: "Library statistics and breakdowns",
          },
          {
            method: "GET",
            path: "/api/v1/agent-skill",
            description: "Comprehensive API documentation for AI agents",
          },
          {
            method: "GET",
            path: "/api/v1/capabilities",
            description: "This endpoint - API capabilities manifest",
          },
        ],
      },

      // Write endpoints (auth + membership required)
      write: {
        description: "Write endpoints. Require Bearer token auth and membership.",
        routes: [
          {
            method: "POST",
            path: "/api/v1/library/write",
            description: "Register a new library item (metadata only)",
            permission: "library:write",
            body: ["contentKey|cdnUrl", "title", "author?", "categories?", "mediaType?", "fileSize?", "storageType?", "coverUrl?", "fileName?", "publicationYear?", "publisher?", "isbn?", "addToStack?"],
          },
          {
            method: "POST",
            path: "/api/v1/library/upload",
            description: "Upload file directly to Net Protocol via relay",
            permission: "library:write",
            contentType: "multipart/form-data",
            body: ["file (binary)", "title", "author?", "categories?", "description?", "addToStack?"],
            limits: {
              maxSize: "15MB",
            },
            note: "Handles blockchain transactions via relay. Returns CDN URL.",
          },
          {
            method: "POST",
            path: "/api/v1/stacks/write",
            description: "Create a new stack",
            permission: "stacks:create",
            body: ["name", "description?", "isPublic?", "isFileSystem?", "items?", "txHash?"],
            note: "Members create free. Non-members pay $5 USDC.",
          },
          {
            method: "PUT",
            path: "/api/v1/stacks/write",
            description: "Modify stack (action-based)",
            permission: "stacks:write",
            body: ["stackId", "action"],
            actions: [
              { action: "add-item", fields: ["contentKey"] },
              { action: "remove-item", fields: ["contentKey"] },
              { action: "unlock", fields: ["txHash"], note: "$5 USDC payment" },
              { action: "update-metadata", fields: ["name?", "description?", "isPrivate?"] },
              {
                action: "add-fs-item",
                description: "Add an item to a filesystem stack with path and filename metadata",
                fields: ["contentKey", "path", "fileName", "mimeType"],
              },
            ],
          },
          {
            method: "DELETE",
            path: "/api/v1/stacks/write",
            description: "Remove items from a stack",
            permission: "stacks:write",
            body: ["stackId", "items"],
          },
          {
            method: "POST",
            path: "/api/v1/archive",
            description: "Archive a Farcaster cast",
            permission: "library:archive",
            body: ["castHash|castUrl", "text?", "authorFid?", "authorUsername?", "authorPfpUrl?", "embeds?", "timestamp?", "title?", "categories?", "addToStack?", "archiveStackId?"],
            notes: "archiveStackId: ID of a filesystem stack (isFileSystem: true). Item is filed at /{YYYY-MM-DD}/cast-{username}-{hash8}.json automatically, creating a browsable date-organised archive. addToStack: plain (non-filesystem) stack — items ordered by insertion.",
          },
          {
            method: "DELETE",
            path: "/api/v1/library/write",
            description: "Delete an item from the library catalog (content remains onchain)",
            permission: "library:write",
            body: ["contentKey", "operatorAddress"],
          },
        ],
      },

      // Webhooks (incoming events)
      webhooks: {
        description: "Webhook endpoints for external event sources.",
        routes: [
          {
            method: "POST",
            path: "/api/v1/webhooks/farcaster",
            description: "Neynar webhook receiver for Farcaster mentions",
            note: "Requires webhook signature verification",
          },
        ],
      },

      // Embed endpoints (no auth required)
      embed: {
        description: "Embeddable widget endpoints for external sites. No authentication required.",
        routes: {
          item: "GET /api/embed/item?key={contentKey}",
          stack: "GET /api/embed/stack?id={stackId}",
        },
      },

      // Agent management endpoints
      agents: {
        description: "Agent management endpoints. Most require Bearer token auth.",
        routes: [
          {
            method: "POST",
            path: "/api/v1/agents",
            description: "Register a new agent (admin only)",
            permission: "admin",
          },
          {
            method: "GET",
            path: "/api/v1/agents",
            description: "List all agents (admin only)",
            permission: "admin",
          },
          {
            method: "PUT",
            path: "/api/v1/agents",
            description: "Update agent (admin only)",
            permission: "admin",
          },
          {
            method: "DELETE",
            path: "/api/v1/agents",
            description: "Deactivate agent (admin only)",
            permission: "admin",
          },
          {
            method: "GET",
            path: "/api/v1/agents/me",
            description: "Get authenticated agent's profile with widgets",
            permission: "any",
          },
          {
            method: "GET",
            path: "/api/v1/agents/membership",
            description: "Check membership status and available purchases",
            permission: "any",
            returns: ["isMember", "memberId?", "ensSubname?", "hasUnlimitedPass", "hasGridPass", "availablePurchases"],
          },
          {
            method: "POST",
            path: "/api/v1/agents/membership",
            description: "Purchase membership or other items (authenticated), OR self-register as a new agent member (no auth, payment required)",
            permission: "any (or none for selfRegister)",
            body: ["purchaseType?", "txHash", "stackId?", "adminGrant?", "targetAgentId?"],
            purchaseTypes: [
              { type: "membership", price: `$${PRICING.MEMBERSHIP} USDC`, description: "Join Net Library, get ENS subname" },
              { type: "storage-pass", price: `$${PRICING.STORAGE_PASS} USDC`, description: "Unlimited storage for stacks (members only)" },
              { type: "stack-unlock", price: `$${PRICING.STACK_UNLOCK} USDC`, description: "Unlock specific stack for unlimited items (requires stackId)" },
              { type: "grid-unlock", price: `$${PRICING.GRID_UNLOCK} USDC`, description: "Unlock personal grid customization" },
            ],
            selfRegisterMode: {
              description: "No auth required. Pass { selfRegister: true, name, address, txHash } to register + get API key in one step.",
              note: "See apiKeys.selfRegister for full body schema.",
            },
          },
          {
            method: "POST",
            path: "/api/v1/agents/ens",
            description: "Mint or retry ENS subname for agent (members only)",
            permission: "any",
            note: "Use this if ENS minting failed during membership signup",
          },
          {
            method: "GET",
            path: "/api/v1/agents/link",
            description: "Check Net Protocol link status",
            permission: "any",
          },
          {
            method: "POST",
            path: "/api/v1/agents/link",
            description: "Link profile to Net Protocol URL (shows LINKED badge)",
            permission: "any",
            body: ["url", "label?"],
            note: "URL must be from storedon.net or netprotocol.app",
          },
          {
            method: "DELETE",
            path: "/api/v1/agents/link",
            description: "Remove Net Protocol link",
            permission: "any",
          },
          {
            method: "GET",
            path: "/api/v1/agents/tasks",
            description: "Poll for pending tasks",
            permission: "any",
            params: ["status", "type", "limit"],
          },
          {
            method: "PUT",
            path: "/api/v1/agents/tasks",
            description: "Update task status",
            permission: "any",
            body: ["taskId", "status", "result?"],
          },
        ],
      },
    },

    // Self-service API key management (C20)
    apiKeys: {
      generate: {
        method: "POST",
        path: "/api/v1/membership/api-key",
        auth: "farcaster OR bearer",
        description: "Generate an API key (must be a member). Web users pass { address } in body; agents use Bearer token.",
        body: {
          address: "required for web users (wallet address from wagmi)",
          fid: "optional — for FID-based member lookup",
          regenerate: "optional boolean — set true to replace existing key (invalidates current key)",
        },
      },
      check: {
        method: "GET",
        path: "/api/v1/membership/api-key",
        auth: "bearer",
        description: "Check if you have an API key and see its prefix (Bearer token required). Web/Farcaster users: POST with { action: 'status', fid } or { action: 'status', address } instead.",
      },
      revoke: {
        method: "DELETE",
        path: "/api/v1/membership/api-key",
        auth: "farcaster OR bearer",
        description: "Revoke your API key. Key becomes immediately invalid.",
      },
      selfRegister: {
        method: "POST",
        path: "/api/v1/agents/membership",
        auth: "none (payment required)",
        description: "Self-register as an agent member — pay $2 USDC, receive API key + membership + ENS subname in one step.",
        body: {
          selfRegister: true,
          name: "required — display name for your agent",
          address: "required — your wallet address (must be sender of USDC payment)",
          txHash: "required — transaction hash of $2 USDC payment to treasury",
          description: "optional — what your agent does",
          fid: "optional — your Farcaster ID",
          pfpUrl: "optional — profile picture URL",
        },
        returns: {
          apiKey: "Your API key (shown once — save immediately)",
          agentId: "Your agent ID",
          memberId: "Your member number",
          ensSubname: "Your ENS subname (e.g. 22.netlibrary.eth)",
          ensMinted: "Whether ENS was successfully minted",
          warning: "Save this API key now — it cannot be retrieved again.",
        },
        rateLimit: "5 self-registrations per hour (global)",
      },
    },

    // Onchain upvotes
    upvotes: {
      enabled: true,
      costPerUpvote: "0.000025 ETH",
      contract: "0x000000060CEB69D023227DF64CfB75eC37c75B62",
      alphaToken: "0x3D01Fe5A38ddBD307fDd635b4Cb0e29681226D6f",
      chain: "base",
      endpoints: {
        getCounts: "GET /api/upvotes?scoreKey={bytes32}",
        batchCounts: "POST /api/upvotes { scoreKeys: bytes32[], contentKeys: string[] }",
      },
      note: "Upvotes are onchain transactions. This API only queries counts. Submitting upvotes requires a wallet transaction to the UpvoteStorageApp contract.",
    },

    // Client-side content encryption (AES-256-GCM + PBKDF2)
    encryption: {
      description: "Library items can be encrypted client-side before upload. Encrypted items are flagged with encrypted:true in the discovery index. Agents that need to encrypt or decrypt content must implement the same algorithm described here.",
      algorithm: {
        cipher: "AES-256-GCM",
        keyDerivation: {
          function: "PBKDF2",
          hash: "SHA-256",
          iterations: 100000,
          saltBytes: 16,
          keyLength: 256,
        },
        ivBytes: 12,
        wireFormat: "base64( [16-byte salt] || [12-byte IV] || [ciphertext + 16-byte GCM auth tag] )",
        notes: [
          "Salt and IV are randomly generated per encryption call — never reused.",
          "The GCM auth tag is appended by SubtleCrypto.encrypt and verified by SubtleCrypto.decrypt; wrong password throws.",
          "Encrypted files are stored as application/octet-stream containing the base64 wire format.",
          "Passwords are never transmitted to the server — encryption and decryption happen entirely in the browser (or agent runtime).",
        ],
      },
      constraints: {
        noRecovery: "Passwords cannot be recovered. If lost, encrypted content is permanently unreadable.",
        noReEncryption: "Net Protocol is first-write-wins. Changing a password means uploading a new encrypted version at a new content key. The original encrypted blob stays onchain forever.",
        membersOnly: "The encrypt toggle on upload is member-only. Any user can enter a password to decrypt shared content.",
      },
      passwordManagement: {
        description: "Members can save named passwords server-side (encrypted at rest with AES-256-GCM using the server key).",
        endpoints: {
          list: "GET /api/passwords — returns [{ id, label, createdAt, itemCount }] (no plaintext)",
          save: "POST /api/passwords { password, label? } — encrypts and stores; returns { id, label, createdAt }",
          retrieve: "GET /api/passwords/:id — returns { id, label, password } (plaintext, owner only)",
          updateLabel: "PUT /api/passwords/:id { label } — update label only",
          delete: "DELETE /api/passwords/:id — removes entry (encrypted items still require the password)",
        },
        auth: "bearer or { fid } / { address } body — member-only",
      },
      uploadFlag: {
        description: "Pass encrypted:true in metadata when uploading an encrypted file. The discovery index stores this flag so viewers know to show a password gate.",
        relayMetadataField: "encrypted: boolean",
      },
      sessionCaching: {
        description: "The web viewer caches the decrypted password in sessionStorage (key: net-pw-{contentKey}) when the user checks 'Remember for this session'. This is cleared on tab close and never written to localStorage.",
      },
    },

    // Authentication details
    authentication: {
      type: "bearer",
      header: "Authorization",
      format: "Bearer nlk_<32hex>",
      keyFormats: {
        selfService: "nlk_<32 random hex chars> — issued via /api/v1/membership/api-key or self-register",
        legacy: "[REDACTED-API-KEY] — issued by admin",
      },
      howToGetKey: {
        webMembers: "Open the miniapp → My Profile → Member Resources → API Key → Generate API Key",
        agentSelfRegister: "POST /api/v1/agents/membership with { selfRegister: true, name, address, txHash }",
        adminRegistration: "Contact the library admin (admin-only path, legacy)",
      },
    },

    // Available permissions
    permissions: [
      { name: "library:write", description: "Add items to the library" },
      { name: "library:archive", description: "Archive Farcaster casts" },
      { name: "stacks:create", description: "Create new stacks" },
      { name: "stacks:write", description: "Modify stacks (add/remove items)" },
      { name: "stacks:delete", description: "Delete owned stacks" },
      { name: "admin", description: "Full access to all operations" },
    ],

    // Identity verification (C16)
    identity: {
      erc8004: {
        registry: ERC8004_REGISTRY,
        chain: "Base (8453)",
        verify: {
          method: "POST",
          path: "/api/v1/agents/verify-8004",
          auth: true,
          description: "Re-check ERC-8004 registration status",
        },
        description: "Agents registered on the ERC-8004 Base Identity Registry get a verified badge. Set your erc8004TokenId via PUT /agents to verify.",
      },
    },

    // Contact information
    contact: {
      librarian: "Cheryl",
      farcaster: "@netlibrary",
    },

    // Links to more resources
    resources: {
      skillDocument: `${baseUrl}/api/v1/agent-skill`,
      documentation: `${baseUrl}/docs`,
    },

    // Include agent type if provided (for analytics)
    ...(agentType ? { requestedBy: agentType } : {}),
  };

  return corsResponse(capabilities);
}
src/app/api/v1/comments/[contentKey]/route.ts
/**
 * Comments API
 *
 * GET /api/v1/comments/[contentKey] — Fetch comments for a library item
 * OPTIONS — CORS preflight
 */

import { NextRequest } from "next/server";
import {
  getKV,
  handleOptions,
  corsResponse,
  corsError,
} from "@/lib/agent-auth";
import type { DiscoveryEntry } from "@/lib/net-protocol";

// KV keys
const DISCOVERY_KEY = "discovery-index";

// Comment structure (matches /api/comments)
interface Comment {
  id: string;
  contentKey: string;
  authorAddress: string;
  authorUsername?: string;
  authorPfpUrl?: string;
  text: string;
  parentId?: string;
  likes: number;
  likedBy: string[];
  createdAt: number;
  updatedAt?: number;
  isEdited: boolean;
}

interface CommentsData {
  comments: Comment[];
  totalCount: number;
}

// Shape comment for response (with reply count)
interface PublicComment {
  id: string;
  author: {
    address: string;
    username: string | null;
    pfpUrl: string | null;
  };
  text: string;
  parentId: string | null;
  likes: number;
  createdAt: number;
  updatedAt: number | null;
  isEdited: boolean;
  replyCount: number;
}

function shapeComment(comment: Comment, replyCount: number): PublicComment {
  return {
    id: comment.id,
    author: {
      address: comment.authorAddress,
      username: comment.authorUsername || null,
      pfpUrl: comment.authorPfpUrl || null,
    },
    text: comment.text,
    parentId: comment.parentId || null,
    likes: comment.likes,
    createdAt: comment.createdAt,
    updatedAt: comment.updatedAt || null,
    isEdited: comment.isEdited,
    replyCount,
  };
}

// Shape item metadata for response
interface ItemMetadata {
  title: string;
  author: string;
  mediaType: string | null;
  cdnUrl: string | null;
  isSocialReceipt: boolean;
  socialPlatform: string | null;
  originalUrl: string | null;
}

function shapeItemMetadata(entry: DiscoveryEntry): ItemMetadata {
  return {
    title: entry.title,
    author: entry.author,
    mediaType: entry.mediaType || null,
    cdnUrl: entry.cdnUrl || null,
    isSocialReceipt: entry.isSocialReceipt || false,
    socialPlatform: entry.socialPlatform || null,
    originalUrl: entry.originalUrl || null,
  };
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/v1/comments/[contentKey] — Fetch comments for a library item
 *
 * Query params:
 * - parentId (omit for top-level comments only, provide to get replies)
 *
 * Comments are sorted newest first.
 * Each comment includes a replyCount.
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ contentKey: string }> }
) {
  try {
    const { contentKey } = await params;
    const { searchParams } = new URL(request.url);

    const parentId = searchParams.get("parentId") || null;

    if (!contentKey) {
      return corsError("Content key is required", 400);
    }

    // Look up item in discovery index
    const discoveryEntries = await getKV<DiscoveryEntry[]>(DISCOVERY_KEY) || [];
    const entry = discoveryEntries.find((e) => e.contentKey === contentKey);

    // Fetch comments from KV
    const commentsData = await getKV<CommentsData>(`comments:${contentKey}`);

    if (!commentsData || commentsData.comments.length === 0) {
      return corsResponse({
        success: true,
        contentKey,
        item: entry ? shapeItemMetadata(entry) : null,
        comments: [],
        totalCount: 0,
      });
    }

    // Filter by parentId (null = top-level comments only)
    let filteredComments = commentsData.comments;
    if (parentId) {
      // Get replies to a specific comment
      filteredComments = commentsData.comments.filter(c => c.parentId === parentId);
    } else {
      // Get top-level comments (no parentId)
      filteredComments = commentsData.comments.filter(c => !c.parentId);
    }

    // Sort newest first
    filteredComments.sort((a, b) => b.createdAt - a.createdAt);

    // Calculate reply counts for each comment
    const comments = filteredComments.map(comment => {
      const replyCount = commentsData.comments.filter(c => c.parentId === comment.id).length;
      return shapeComment(comment, replyCount);
    });

    return corsResponse({
      success: true,
      contentKey,
      item: entry ? shapeItemMetadata(entry) : null,
      comments,
      totalCount: commentsData.totalCount,
    });
  } catch (error) {
    console.error("[GET /api/v1/comments/[contentKey]] Error:", error);
    return corsError("Failed to fetch comments", 500);
  }
}
src/app/api/v1/embeds/card/[address]/route.ts
/**
 * GET /api/v1/embeds/card/[address]
 *
 * Returns library card embed data for a given address.
 * Public endpoint (no auth required) with CORS support.
 *
 * Returns the same data the HTML embed widget at /embed/card/[address] renders.
 */

/* eslint-disable @neynar/no-process-env */
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import {
  corsResponse,
  corsError,
  handleOptions,
  MEMBER_REGISTRY_KEY,
  verifyErc8004,
  isErc8004CacheStale,
  updateMemberErc8004Status,
  type MemberRegistry,
  type MemberEntry,
  type RegisteredAgent,
} from "@/lib/agent-auth";
import type { DiscoveryEntry } from "@/lib/net-protocol";

// =============================================================================
// OPTIONS - CORS preflight
// =============================================================================

export async function OPTIONS() {
  return handleOptions();
}

// =============================================================================
// GET - Fetch library card data
// =============================================================================

export async function GET(
  _request: Request,
  { params }: { params: Promise<{ address: string }> }
) {
  try {
    const { address } = await params;

    if (!address) {
      return corsError("Address is required", 400);
    }

    const normalizedAddress = address.toLowerCase();

    // Fetch member registry
    const registryResult = await db
      .select()
      .from(kv)
      .where(eq(kv.key, MEMBER_REGISTRY_KEY))
      .limit(1);
    const registry: MemberRegistry | null = registryResult[0]?.value
      ? JSON.parse(registryResult[0].value)
      : null;

    // Find member by address or linked addresses
    let member: MemberEntry | null = null;
    if (registry) {
      member =
        registry.members.find(
          (m) =>
            m.address.toLowerCase() === normalizedAddress ||
            m.linkedAddresses?.some((a) => a.toLowerCase() === normalizedAddress)
        ) || null;
    }

    // Fetch discovery index for upload stats
    const discoveryResult = await db
      .select()
      .from(kv)
      .where(eq(kv.key, "discovery-index"))
      .limit(1);
    const entries: DiscoveryEntry[] = discoveryResult[0]?.value
      ? JSON.parse(discoveryResult[0].value)
      : [];

    // Get user's uploads (visible only)
    const userUploads = entries.filter(
      (e) => e.operator.toLowerCase() === normalizedAddress && !e.hidden
    );
    const totalBytes = userUploads.reduce((sum, e) => sum + (e.fileSize || 0), 0);

    // Fetch stacks for this user
    const userStacksResult = await db
      .select()
      .from(kv)
      .where(eq(kv.key, `user-stacks:${normalizedAddress}`))
      .limit(1);
    const stackIds: string[] = userStacksResult[0]?.value
      ? JSON.parse(userStacksResult[0].value)
      : [];

    // Fetch grids for this user
    const userGridsResult = await db
      .select()
      .from(kv)
      .where(eq(kv.key, `user-grids:${normalizedAddress}`))
      .limit(1);
    const gridIds: string[] = userGridsResult[0]?.value
      ? JSON.parse(userGridsResult[0].value)
      : [];

    // Calculate rank from leaderboard
    const leaderboardResult = await db
      .select()
      .from(kv)
      .where(eq(kv.key, "leaderboard-index"))
      .limit(1);
    let rank: number | null = null;
    if (leaderboardResult[0]?.value) {
      const leaderboard = JSON.parse(leaderboardResult[0].value);
      const sortedEntries = (leaderboard.entries || []).sort(
        (a: { totalUploads: number }, b: { totalUploads: number }) =>
          b.totalUploads - a.totalUploads
      );
      const userRankIndex = sortedEntries.findIndex(
        (e: { address: string }) => e.address.toLowerCase() === normalizedAddress
      );
      if (userRankIndex !== -1) {
        rank = userRankIndex + 1;
      }
    }

    // If member is an agent, fetch fresh agent data for name, PFP, and erc8004TokenId
    let agentName: string | null = null;
    let agentPfpUrl: string | null = null;
    let agentErc8004TokenId: number | undefined = undefined;

    if (member?.isAgent && member.agentId) {
      try {
        const agentResult = await db
          .select()
          .from(kv)
          .where(eq(kv.key, `api-agent:${member.agentId}`))
          .limit(1);
        if (agentResult[0]?.value) {
          const agent: RegisteredAgent = JSON.parse(agentResult[0].value);
          if (agent.name) agentName = agent.name;
          if (agent.pfpUrl) agentPfpUrl = agent.pfpUrl;
          // Pull erc8004TokenId from agent record (source of truth)
          if (agent.erc8004TokenId !== undefined) agentErc8004TokenId = agent.erc8004TokenId;
        }
      } catch {
        // Ignore - will use member data as fallback
      }
    }

    // Get PFP priority: agent pfpUrl > customPfpUrl > Neynar lookup > dicebear
    let pfpUrl: string | null = agentPfpUrl || member?.customPfpUrl || null;
    if (!pfpUrl && member?.fid) {
      // Fetch PFP from Neynar API
      try {
        const neynarResponse = await fetch(
          `https://api.neynar.com/v2/farcaster/user/bulk?fids=${member.fid}`,
          {
            headers: {
              "x-api-key": process.env.NEYNAR_API_KEY || "",
            },
          }
        );
        if (neynarResponse.ok) {
          const neynarData = await neynarResponse.json();
          pfpUrl = neynarData.users?.[0]?.pfp_url || null;
        }
      } catch {
        // Ignore - will use fallback
      }
    }
    // Fallback to dicebear
    if (!pfpUrl) {
      pfpUrl = `https://api.dicebear.com/7.x/identicon/svg?seed=${normalizedAddress}`;
    }

    // Determine display name
    const displayName =
      agentName ||
      member?.customUsername ||
      member?.username ||
      (member ? `Member ${member.memberId}` : `${address.slice(0, 6)}...${address.slice(-4)}`);

    // ERC-8004 verification - check if agent and if verification is stale
    // Priority: agent record tokenId > member registry tokenId
    let erc8004Verified = member?.erc8004Verified || false;
    let erc8004TokenId = agentErc8004TokenId ?? member?.erc8004TokenId;

    if (member?.isAgent) {
      // For agents, check if ERC-8004 cache is stale
      if (isErc8004CacheStale(member.erc8004CheckedAt)) {
        try {
          // Run fresh verification using tokenId from agent record (source of truth)
          const verification = await verifyErc8004(normalizedAddress, erc8004TokenId);
          erc8004Verified = verification.verified;
          if (verification.tokenId !== undefined) {
            erc8004TokenId = verification.tokenId;
          }
          // Update member registry with new verification status
          await updateMemberErc8004Status(normalizedAddress, verification);
        } catch (err) {
          // On error, use cached value
          console.error("[embeds/card] ERC-8004 verification error:", err);
        }
      }
    }

    // Build response matching spec format
    const response = {
      member: member
        ? {
            memberId: member.memberId,
            ensSubname: member.ensSubname,
            joinedAt: typeof member.joinedAt === "string"
              ? new Date(member.joinedAt).getTime()
              : member.joinedAt,
            hasUnlimitedPass: member.hasUnlimitedPass || member.hasStackPass || false,
            hasUnlimitedStoragePass: member.hasUnlimitedPass || member.hasStackPass || false, // backwards compat
            hasGridPass: member.hasGridPass || false,
            // ERC-8004 verification (Part 6 of C16)
            ...(member.isAgent ? {
              isAgent: true,
              agentId: member.agentId,
              erc8004Verified,
              erc8004TokenId,
            } : {}),
          }
        : null,
      uploads: {
        count: userUploads.length,
        totalBytes,
      },
      stackCount: stackIds.length,
      gridCount: gridIds.length,
      rank,
      pfpUrl,
      displayName,
    };

    return corsResponse(response);
  } catch (error) {
    console.error("[embeds/card] Error:", error);
    return corsError("Failed to fetch card data", 500);
  }
}
src/app/api/v1/embeds/grid/[gridId]/route.ts
/**
 * GET /api/v1/embeds/grid/[gridId]
 *
 * Returns grid embed data for a given grid ID.
 * Public endpoint (no auth required) with CORS support.
 *
 * Returns the same data the HTML embed widget at /embed/grid/[gridId] renders.
 */

import { corsResponse, corsError, handleOptions, getKV } from "@/lib/agent-auth";
import type { Grid, GridCell, GridCells, DiscoveryEntry } from "@/lib/net-protocol";

// =============================================================================
// HELPERS
// =============================================================================

// Extract content key from various CDN URL formats
function extractContentKey(url: string): string | null {
  if (!url) return null;
  const normalized = url.toLowerCase().trim();

  // Format: direct 0x... key in URL
  const hexMatch = normalized.match(/(0x[a-f0-9]{64})/i);
  if (hexMatch) return hexMatch[1];

  // Format: storedon.net/content/{key}
  const contentMatch = normalized.match(/storedon\.net\/content\/([^/?#]+)/);
  if (contentMatch) return contentMatch[1];

  // Format: storedon.net/net/{chainId}/storage/raw/{operator}/{key}
  const storageMatch = normalized.match(
    /storedon\.net\/net\/\d+\/storage\/(?:raw|load)\/[^/]+\/([^/?#]+)/
  );
  if (storageMatch) return storageMatch[1];

  // Format: storedon.net/net/{chainId}/chunked-storage/file/{operator}/{key}
  const chunkedMatch = normalized.match(
    /storedon\.net\/net\/\d+\/chunked-storage\/(?:file|raw)\/[^/]+\/([^/?#]+)/
  );
  if (chunkedMatch) return chunkedMatch[1];

  return null;
}

// Check if two URLs refer to same content
function urlsMatch(url1: string, url2: string): boolean {
  if (!url1 || !url2) return false;
  const key1 = extractContentKey(url1);
  const key2 = extractContentKey(url2);
  if (key1 && key2 && key1.toLowerCase() === key2.toLowerCase()) return true;

  // Direct URL comparison
  const n1 = url1.toLowerCase().trim();
  const n2 = url2.toLowerCase().trim();
  return n1 === n2 || n1.includes(n2) || n2.includes(n1);
}

// Enrich cells with cover URLs and contentKeys from discovery index
async function enrichCellsWithCovers(cells: GridCell[]): Promise<GridCell[]> {
  if (!cells || cells.length === 0) return [];

  try {
    const discoveryIndex = (await getKV<DiscoveryEntry[]>("discovery-index")) || [];

    return cells.map((cell) => {
      // If cell already has coverUrl, no need to enrich
      if (cell.coverUrl) return cell;

      if (!cell.cdnUrl) return cell;

      // Try to extract contentKey from cdnUrl
      const contentKey = cell.contentKey || extractContentKey(cell.cdnUrl);

      // Find matching entry - try multiple strategies
      let matchingEntry: DiscoveryEntry | undefined;

      // 1. Exact contentKey match (most reliable)
      if (contentKey) {
        matchingEntry = discoveryIndex.find(
          (entry) => entry.contentKey?.toLowerCase() === contentKey.toLowerCase()
        );
      }

      // 2. URL matching (handles different URL formats for same content)
      if (!matchingEntry) {
        matchingEntry = discoveryIndex.find((entry) => {
          if (entry.cdnUrl && urlsMatch(entry.cdnUrl, cell.cdnUrl)) return true;
          if (
            entry.contentKey &&
            cell.cdnUrl.toLowerCase().includes(entry.contentKey.toLowerCase())
          )
            return true;
          return false;
        });
      }

      const enriched = { ...cell };

      if (contentKey && !enriched.contentKey) {
        enriched.contentKey = contentKey;
      }

      if (matchingEntry?.coverUrl) {
        enriched.coverUrl = matchingEntry.coverUrl;
      }

      if (matchingEntry?.contentKey && !enriched.contentKey) {
        enriched.contentKey = matchingEntry.contentKey;
      }

      if (matchingEntry?.operator && !enriched.operator) {
        enriched.operator = matchingEntry.operator;
      }

      return enriched;
    });
  } catch {
    return cells;
  }
}

// =============================================================================
// OPTIONS - CORS preflight
// =============================================================================

export async function OPTIONS() {
  return handleOptions();
}

// =============================================================================
// GET - Fetch grid embed data
// =============================================================================

export async function GET(
  _request: Request,
  { params }: { params: Promise<{ gridId: string }> }
) {
  try {
    const { gridId } = await params;

    if (!gridId) {
      return corsError("Grid ID is required", 400);
    }

    // Fetch grid metadata (uses same key as embed widget: grid:{gridId})
    const grid = await getKV<Grid>(`grid:${gridId}`);

    // Grid not found
    if (!grid) {
      return corsError("Grid not found", 404);
    }

    // Grid is deleted
    if (grid.deleted) {
      return corsError("Grid not found", 404);
    }

    // Grid is private/hidden
    if (grid.visibility === "hidden" || (grid as Grid & { isPrivate?: boolean }).isPrivate) {
      return corsError("Grid is private", 403);
    }

    // Fetch grid cells (uses same key as embed widget: grid-cells:{gridId})
    const gridCells = await getKV<GridCells>(`grid-cells:${gridId}`);
    const rawCells = gridCells?.cells || [];

    // Enrich cells with cover URLs from discovery
    const cells = await enrichCellsWithCovers(rawCells);

    // Build response matching spec format
    const response = {
      grid: {
        id: grid.id,
        name: grid.name,
        owner: grid.creator,
        columns: grid.size || 3,
        isPrivate: false,
        createdAt: grid.createdAt,
      },
      cells: cells.map((cell) => ({
        position: cell.row * (grid.size || 3) + cell.col,
        contentKey: cell.contentKey || null,
        title: cell.title || null,
        coverUrl: cell.coverUrl || null,
        mediaType: cell.mediaType || null,
      })),
    };

    return corsResponse(response);
  } catch (error) {
    console.error("[embeds/grid] Error:", error);
    return corsError("Failed to fetch grid data", 500);
  }
}
src/app/api/v1/embeds/user/[address]/route.ts
/**
 * GET /api/v1/embeds/user/[address]
 *
 * Returns user embed data for a given address.
 * Public endpoint (no auth required) with CORS support.
 *
 * Returns the same data the HTML embed widget at /embed/user/[address] renders.
 *
 * Query params:
 *   - page: Page number (default 1)
 *   - limit: Items per page (default 20, max 50)
 */

/* eslint-disable @neynar/no-process-env */
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import {
  corsResponse,
  corsError,
  handleOptions,
  MEMBER_REGISTRY_KEY,
  type MemberRegistry,
  type MemberEntry,
} from "@/lib/agent-auth";
import type { DiscoveryEntry } from "@/lib/net-protocol";

// =============================================================================
// OPTIONS - CORS preflight
// =============================================================================

export async function OPTIONS() {
  return handleOptions();
}

// =============================================================================
// GET - Fetch user embed data
// =============================================================================

export async function GET(
  request: Request,
  { params }: { params: Promise<{ address: string }> }
) {
  try {
    const { address } = await params;

    if (!address) {
      return corsError("Address is required", 400);
    }

    const normalizedAddress = address.toLowerCase();

    // Parse pagination params
    const url = new URL(request.url);
    const page = Math.max(1, parseInt(url.searchParams.get("page") || "1", 10));
    const limit = Math.min(50, Math.max(1, parseInt(url.searchParams.get("limit") || "20", 10)));

    // Fetch discovery index for user's uploads
    const discoveryResult = await db
      .select()
      .from(kv)
      .where(eq(kv.key, "discovery-index"))
      .limit(1);
    const entries: DiscoveryEntry[] = discoveryResult[0]?.value
      ? JSON.parse(discoveryResult[0].value)
      : [];

    // Get user's uploads (visible only).
    // Check uploaderAddress first — relay uploads store the backend wallet as `operator`
    // and the actual user's wallet as `uploaderAddress`. Fall back to operator for legacy entries.
    const userUploads = entries.filter(
      (e) => !e.hidden && (
        (e.uploaderAddress && e.uploaderAddress.toLowerCase() === normalizedAddress) ||
        e.operator.toLowerCase() === normalizedAddress
      )
    );
    const totalBytes = userUploads.reduce((sum, e) => sum + (e.fileSize || 0), 0);

    // Apply pagination
    const total = userUploads.length;
    const startIndex = (page - 1) * limit;
    const paginatedUploads = userUploads.slice(startIndex, startIndex + limit);
    const hasMore = startIndex + limit < total;

    // Fetch member registry
    const registryResult = await db
      .select()
      .from(kv)
      .where(eq(kv.key, MEMBER_REGISTRY_KEY))
      .limit(1);
    const registry: MemberRegistry | null = registryResult[0]?.value
      ? JSON.parse(registryResult[0].value)
      : null;

    // Find member by address or linked addresses
    let member: MemberEntry | null = null;
    if (registry) {
      member =
        registry.members.find(
          (m) =>
            m.address.toLowerCase() === normalizedAddress ||
            m.linkedAddresses?.some((a) => a.toLowerCase() === normalizedAddress)
        ) || null;
    }

    // Get PFP: customPfpUrl first, then fetch from Neynar if member has fid, else dicebear
    let pfpUrl: string | null = member?.customPfpUrl || null;
    if (!pfpUrl && member?.fid) {
      // Fetch PFP from Neynar API
      try {
        const neynarResponse = await fetch(
          `https://api.neynar.com/v2/farcaster/user/bulk?fids=${member.fid}`,
          {
            headers: {
              "x-api-key": process.env.NEYNAR_API_KEY || "",
            },
          }
        );
        if (neynarResponse.ok) {
          const neynarData = await neynarResponse.json();
          pfpUrl = neynarData.users?.[0]?.pfp_url || null;
        }
      } catch {
        // Ignore - will use fallback
      }
    }
    // Fallback to dicebear
    if (!pfpUrl) {
      pfpUrl = `https://api.dicebear.com/7.x/identicon/svg?seed=${normalizedAddress}`;
    }

    // Get display name: customUsername first (what user set), then username (Farcaster), then Member #
    const displayName =
      member?.customUsername ||
      member?.username ||
      (member ? `Member ${member.memberId}` : `${address.slice(0, 6)}...${address.slice(-4)}`);

    // Build response matching spec format
    const response = {
      address: normalizedAddress,
      member: member
        ? {
            memberId: member.memberId,
            ensSubname: member.ensSubname,
            joinedAt: typeof member.joinedAt === "string"
              ? new Date(member.joinedAt).getTime()
              : member.joinedAt,
          }
        : null,
      uploads: paginatedUploads.map((upload) => ({
        contentKey: upload.contentKey,
        title: upload.title || null,
        mediaType: upload.mediaType || null,
        addedAt: upload.uploadedAt || null,
      })),
      uploadCount: total,
      totalBytes,
      pfpUrl,
      displayName,
      pagination: {
        page,
        limit,
        total,
        hasMore,
      },
    };

    return corsResponse(response);
  } catch (error) {
    console.error("[embeds/user] Error:", error);
    return corsError("Failed to fetch user data", 500);
  }
}
src/app/api/v1/github-tree/route.ts
import { NextRequest, NextResponse } from "next/server";

// CORS headers for external API access
const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type, X-Agent-Type",
};

// Handle OPTIONS preflight request
export async function OPTIONS() {
  return new NextResponse(null, {
    status: 204,
    headers: corsHeaders,
  });
}

// Paths to ignore during import
const IGNORED_PATTERNS = [
  "node_modules",
  ".git",
  "dist",
  "build",
  ".next",
  ".env",
  ".env.local",
  ".DS_Store",
  "Thumbs.db",
  "__MACOSX",
  ".cache",
  "coverage",
  ".nyc_output",
];

/**
 * Check if a path should be ignored
 */
function shouldIgnore(path: string): boolean {
  const parts = path.split("/");
  return parts.some((part) => IGNORED_PATTERNS.includes(part));
}

/**
 * GitHub tree entry from API response
 */
interface GitHubTreeEntry {
  path: string;
  mode: string;
  type: "blob" | "tree";
  sha: string;
  size?: number;
  url: string;
}

/**
 * GitHub API tree response
 */
interface GitHubTreeResponse {
  sha: string;
  url: string;
  tree: GitHubTreeEntry[];
  truncated: boolean;
}

/**
 * Our normalized tree entry
 */
interface TreeEntry {
  path: string;
  type: "file" | "directory";
  size: number;
  sha: string | null;
  downloadUrl: string | null;
}

/**
 * Fetch tree from GitHub API, with branch fallback only when using default
 */
async function fetchGitHubTree(
  owner: string,
  repo: string,
  branch: string,
  userSpecifiedBranch: boolean
): Promise<{ data: GitHubTreeResponse | null; branch: string; error?: string; status?: number }> {
  // Only try fallback branches if user didn't explicitly specify a branch
  const branches = userSpecifiedBranch
    ? [branch]
    : [branch, branch === "main" ? "master" : "main"];

  for (const tryBranch of branches) {
    const url = `https://api.github.com/repos/${owner}/${repo}/git/trees/${tryBranch}?recursive=1`;

    try {
      const response = await fetch(url, {
        headers: {
          Accept: "application/vnd.github.v3+json",
          "User-Agent": "Net-Library-App",
        },
      });

      if (response.ok) {
        const data = (await response.json()) as GitHubTreeResponse;
        return { data, branch: tryBranch };
      }

      // If rate limited, return immediately
      if (response.status === 403) {
        const remaining = response.headers.get("X-RateLimit-Remaining");
        if (remaining === "0") {
          const resetTime = response.headers.get("X-RateLimit-Reset");
          const resetDate = resetTime ? new Date(parseInt(resetTime) * 1000).toISOString() : "soon";
          return {
            data: null,
            branch: tryBranch,
            error: `GitHub API rate limit exceeded. Resets at ${resetDate}`,
            status: 429,
          };
        }
      }

      // If 404 on first branch, try fallback
      if (response.status === 404 && tryBranch === branches[0]) {
        continue;
      }

      // Other errors
      if (response.status === 404) {
        return {
          data: null,
          branch: tryBranch,
          error: `Repository not found or branch "${branch}" does not exist`,
          status: 404,
        };
      }

      return {
        data: null,
        branch: tryBranch,
        error: `GitHub API error: ${response.status}`,
        status: response.status,
      };
    } catch (err) {
      return {
        data: null,
        branch: tryBranch,
        error: `Failed to fetch from GitHub: ${err instanceof Error ? err.message : "Unknown error"}`,
        status: 500,
      };
    }
  }

  return {
    data: null,
    branch,
    error: `Repository not found or branches "${branches.join(", ")}" do not exist`,
    status: 404,
  };
}

// GET - Fetch GitHub repository tree
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);

    // Check for agent type header (for analytics tracking)
    const agentType = request.headers.get("X-Agent-Type");

    // Parse query parameters
    const repoParam = searchParams.get("repo")?.trim();
    const branchParam = searchParams.get("branch")?.trim() || "main";
    const pathPrefix = searchParams.get("path")?.trim() || "";

    // Validate repo parameter
    if (!repoParam) {
      return NextResponse.json(
        { success: false, error: "Missing required parameter: repo" },
        { status: 400, headers: corsHeaders }
      );
    }

    // Parse owner/repo format
    const repoMatch = repoParam.match(/^([^/]+)\/([^/]+)$/);
    if (!repoMatch) {
      return NextResponse.json(
        {
          success: false,
          error: 'Invalid repo format. Expected "owner/repo" (e.g., "stuckinaboot/botchan")',
        },
        { status: 400, headers: corsHeaders }
      );
    }

    const [, owner, repo] = repoMatch;

    // Check if user explicitly specified a branch
    const userSpecifiedBranch = searchParams.has("branch");

    // Fetch tree from GitHub
    const { data, branch, error, status } = await fetchGitHubTree(owner, repo, branchParam, userSpecifiedBranch);

    if (!data) {
      return NextResponse.json(
        { success: false, error },
        { status: status || 500, headers: corsHeaders }
      );
    }

    // Normalize path prefix (remove leading/trailing slashes)
    const normalizedPrefix = pathPrefix.replace(/^\/+|\/+$/g, "");

    // Process tree entries
    const tree: TreeEntry[] = [];
    let totalSize = 0;
    let totalFiles = 0;

    for (const entry of data.tree) {
      // Skip ignored paths
      if (shouldIgnore(entry.path)) continue;

      // If path prefix specified, filter to only matching entries
      if (normalizedPrefix) {
        if (!entry.path.startsWith(normalizedPrefix + "/") && entry.path !== normalizedPrefix) {
          continue;
        }
      }

      const isFile = entry.type === "blob";
      const size = entry.size || 0;

      if (isFile) {
        totalFiles++;
        totalSize += size;
      }

      tree.push({
        path: entry.path,
        type: isFile ? "file" : "directory",
        size,
        sha: isFile ? entry.sha : null,
        downloadUrl: isFile
          ? `https://raw.githubusercontent.com/${owner}/${repo}/${branch}/${entry.path}`
          : null,
      });
    }

    // Sort: directories first, then alphabetically
    tree.sort((a, b) => {
      if (a.type !== b.type) {
        return a.type === "directory" ? -1 : 1;
      }
      return a.path.localeCompare(b.path);
    });

    // Build response
    const response: Record<string, unknown> = {
      success: true,
      repo: `${owner}/${repo}`,
      branch,
      tree,
      totalFiles,
      totalSize,
      truncated: data.truncated,
    };

    // Include note if truncated
    if (data.truncated) {
      response.note = "Tree was truncated by GitHub API (>100,000 entries). Some files may be missing.";
    }

    // Include agent type if provided (for analytics)
    if (agentType) {
      response.agentType = agentType;
    }

    return NextResponse.json(response, { headers: corsHeaders });
  } catch (error) {
    console.error("[GET /api/v1/github-tree] Error:", error);
    return NextResponse.json(
      {
        success: false,
        error: "Failed to fetch GitHub repository tree",
      },
      { status: 500, headers: corsHeaders }
    );
  }
}
src/app/api/v1/library/[contentKey]/route.ts
/**
 * Single Library Item API
 *
 * GET /api/v1/library/[contentKey] — Fetch a single library item with metadata
 * OPTIONS — CORS preflight
 */

import { NextRequest } from "next/server";
import {
  getKV,
  handleOptions,
  corsResponse,
  corsError,
} from "@/lib/agent-auth";
import type { DiscoveryEntry } from "@/lib/net-protocol";

// KV keys
const DISCOVERY_KEY = "discovery-index";

// Comment structure (matches /api/comments)
interface Comment {
  id: string;
  contentKey: string;
  authorAddress: string;
  authorUsername?: string;
  authorPfpUrl?: string;
  text: string;
  parentId?: string;
  likes: number;
  likedBy: string[];
  createdAt: number;
  updatedAt?: number;
  isEdited: boolean;
}

interface CommentsData {
  comments: Comment[];
  totalCount: number;
}

// Shape library item for response
interface LibraryItemDetail {
  title: string;
  author: string;
  categories: string[];
  contentKey: string;
  mediaType: string | null;
  cdnUrl: string | null;
  storageType: string;
  operator: string;
  uploadDate: number;
  uploader: {
    username: string | null;
    pfpUrl: string | null;
    address: string | null;
    fid: number | null;
  };
  isSocialReceipt: boolean;
  socialPlatform: string | null;
  originalUrl: string | null;
  hidden: boolean;
}

function shapeLibraryItem(entry: DiscoveryEntry): LibraryItemDetail {
  return {
    title: entry.title,
    author: entry.author,
    categories: entry.categories || [],
    contentKey: entry.contentKey,
    mediaType: entry.mediaType || null,
    cdnUrl: entry.cdnUrl || null,
    storageType: entry.storageType,
    operator: entry.operator,
    uploadDate: entry.uploadedAt,
    uploader: {
      username: entry.uploaderUsername || entry.uploaderStoredUsername || null,
      pfpUrl: entry.uploaderPfpUrl || null,
      address: entry.uploaderAddress || entry.operator || null,
      fid: entry.uploaderFid || null,
    },
    isSocialReceipt: entry.isSocialReceipt || false,
    socialPlatform: entry.socialPlatform || null,
    originalUrl: entry.originalUrl || null,
    hidden: entry.hidden || false,
  };
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/v1/library/[contentKey] — Single library item lookup
 *
 * Returns:
 * - item: Full item details
 * - commentCount: Number of comments
 * - inStacks: Whether item is in any stacks
 * - stackIds: Array of stack IDs containing this item
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ contentKey: string }> }
) {
  try {
    const { contentKey } = await params;

    if (!contentKey) {
      return corsError("Content key is required", 400);
    }

    // Fetch discovery index
    const entries = await getKV<DiscoveryEntry[]>(DISCOVERY_KEY) || [];

    // Find the item by contentKey
    const entry = entries.find((e) => e.contentKey === contentKey);

    if (!entry) {
      return corsError("Item not found", 404);
    }

    // Fetch comment count from comments KV
    const commentsData = await getKV<CommentsData>(`comments:${contentKey}`);
    const commentCount = commentsData?.totalCount || 0;

    // Fetch stack IDs that contain this item
    const itemStacks = await getKV<string[]>(`item-stacks:${contentKey}`) || [];

    return corsResponse({
      success: true,
      item: shapeLibraryItem(entry),
      commentCount,
      inStacks: itemStacks.length > 0,
      stackIds: itemStacks,
    });
  } catch (error) {
    console.error("[GET /api/v1/library/[contentKey]] Error:", error);
    return corsError("Failed to fetch library item", 500);
  }
}
src/app/api/v1/library/import/route.ts
/**
 * Partner Import API
 *
 * POST /api/v1/library/import — Import existing Net Protocol content into Net Library
 * OPTIONS — CORS preflight
 *
 * Auth: x-partner-key header (pk_... key from partner registration).
 *       This is NOT a member API key — it's the partner-specific key.
 *
 * The content must already exist on Net Protocol (verified via HEAD to storedon.net).
 * No file is uploaded — this creates an index entry pointing to existing onchain content.
 *
 * Rate limits: 100/hour, 1000/day per partner key.
 */

import { NextRequest } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv, partners } from "@/db/schema";
import { eq } from "drizzle-orm";
import { handleOptions, corsResponse, corsError } from "@/lib/agent-auth";
import type { DiscoveryEntry } from "@/lib/net-protocol";

const DISCOVERY_KEY = "discovery-index";

// KV keys — must match stacks/write/route.ts exactly
const STACK_PREFIX = "stack:";
const STACK_ITEMS_PREFIX = "stack-items:";
const ITEM_STACKS_PREFIX = "item-stacks:";

// KV keys for rate limiting
const RATE_LIMIT_HOUR_PREFIX = "partner-rl-hour:";
const RATE_LIMIT_DAY_PREFIX = "partner-rl-day:";

// Limits
const MAX_PER_HOUR = 100;
const MAX_PER_DAY = 1000;

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/** SHA-256 hash of a string → lowercase hex */
async function sha256Hex(input: string): Promise<string> {
  const data = new TextEncoder().encode(input);
  const buf = await crypto.subtle.digest("SHA-256", data);
  return Array.from(new Uint8Array(buf))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
}

/** Validate 0x-prefixed 40-hex-char Ethereum address */
function isValidAddress(addr: string): boolean {
  return /^0x[0-9a-fA-F]{40}$/.test(addr);
}

/** Detect media type from a content key or filename string */
function detectMediaType(key: string): "image" | "audio" | "video" | "pdf" | "text" | "unknown" {
  const lower = key.toLowerCase();
  if (/\.(png|jpg|jpeg|gif|webp|svg|bmp|ico|tiff|avif|heic)(-|$)/.test(lower) || /\.(png|jpg|jpeg|gif|webp|svg|bmp|ico|tiff|avif|heic)$/.test(lower)) return "image";
  if (/\.(mp3|wav|ogg|flac|m4a|aac|opus|wma)(-|$)/.test(lower) || /\.(mp3|wav|ogg|flac|m4a|aac|opus|wma)$/.test(lower)) return "audio";
  if (/\.(mp4|webm|mov|avi|mkv|m4v|ogv|wmv)(-|$)/.test(lower) || /\.(mp4|webm|mov|avi|mkv|m4v|ogv|wmv)$/.test(lower)) return "video";
  if (/\.(pdf)(-|$)/.test(lower) || /\.pdf$/.test(lower)) return "pdf";
  if (/\.(txt|md|markdown|json|csv|html|htm|xml|yaml|yml)(-|$)/.test(lower) || /\.(txt|md|markdown|json|csv|html|htm|xml|yaml|yml)$/.test(lower)) return "text";
  return "unknown";
}

/** KV upsert helper */
async function setKVRaw(key: string, value: unknown): Promise<void> {
  const str = typeof value === "string" ? value : JSON.stringify(value);
  await db
    .insert(kv)
    .values({ key, value: str })
    .onConflictDoUpdate({ target: kv.key, set: { value: str } });
}

/** KV read helper */
async function getKVRaw<T>(key: string): Promise<T | null> {
  const rows = await db.select().from(kv).where(eq(kv.key, key)).limit(1);
  if (!rows[0]?.value) return null;
  try { return JSON.parse(rows[0].value) as T; } catch { return rows[0].value as T; }
}

interface RateEntry {
  count: number;
  windowStart: number; // epoch ms when this window opened
}

/**
 * Check and increment a rate-limit window stored in the kv table.
 * Returns { allowed, remaining, resetAt }
 */
async function checkRateLimit(
  keyPrefix: string,
  partnerKeyHash: string,
  maxCount: number,
  windowMs: number
): Promise<{ allowed: boolean; remaining: number; resetAt: number }> {
  const kvKey = `${keyPrefix}${partnerKeyHash}`;
  const now = Date.now();

  let entry: RateEntry | null = await getKVRaw<RateEntry>(kvKey);

  // Reset window if expired
  if (!entry || now - entry.windowStart > windowMs) {
    entry = { count: 0, windowStart: now };
  }

  const resetAt = entry.windowStart + windowMs;

  if (entry.count >= maxCount) {
    return { allowed: false, remaining: 0, resetAt };
  }

  entry.count += 1;
  try {
    await setKVRaw(kvKey, entry);
  } catch (e) {
    console.error("[import] Rate limit write error:", e);
    // Don't block the import on a rate-limit write failure
  }

  return { allowed: true, remaining: maxCount - entry.count, resetAt };
}

/** Fetch the full discovery index */
async function fetchIndex(): Promise<DiscoveryEntry[]> {
  return (await getKVRaw<DiscoveryEntry[]>(DISCOVERY_KEY)) || [];
}

/** Persist the full discovery index */
async function storeIndex(entries: DiscoveryEntry[]): Promise<void> {
  await setKVRaw(DISCOVERY_KEY, entries);
}

/**
 * Verify content exists on storedon.net CDN.
 * Tries /storage/load/ first, falls back to /storage/raw/ for older contract pattern.
 */
async function verifyContentOnChain(
  address: string,
  key: string
): Promise<{ found: boolean; cdnUrl: string }> {
  const baseUrl = "https://storedon.net/net/8453";
  const primaryUrl = `${baseUrl}/storage/load/${address}/${encodeURIComponent(key)}`;

  try {
    const res = await fetch(primaryUrl, { method: "HEAD" });
    if (res.ok) return { found: true, cdnUrl: primaryUrl };
  } catch {
    // network error — try fallback
  }

  const rawUrl = `${baseUrl}/storage/raw/${address}/${key}`;
  try {
    const res = await fetch(rawUrl, { method: "HEAD" });
    if (res.ok) return { found: true, cdnUrl: rawUrl };
  } catch {
    // still not found
  }

  return { found: false, cdnUrl: primaryUrl };
}

/**
 * Add a content key to a stack, maintaining the item-stacks reverse index.
 * Mirrors the add-item logic in stacks/write/route.ts.
 * Partner stacks are pre-unlocked so no item limit applies.
 */
async function addItemToStack(stackId: string, contentKey: string, addedBy: string): Promise<void> {
  const stackItemsKey = `${STACK_ITEMS_PREFIX}${stackId}`;
  const stackKey = `${STACK_PREFIX}${stackId}`;
  const itemStacksKey = `${ITEM_STACKS_PREFIX}${contentKey}`;

  // Read current stack items
  const stackItems: Array<{ contentKey: string; addedAt: number; addedBy: string }> =
    (await getKVRaw(stackItemsKey)) || [];

  // Deduplicate — don't add twice
  if (stackItems.some((i) => i.contentKey === contentKey)) return;

  // Prepend (most recent first)
  stackItems.unshift({ contentKey, addedAt: Date.now(), addedBy });
  await setKVRaw(stackItemsKey, stackItems);

  // Update stack itemCount
  const stack = await getKVRaw<Record<string, unknown>>(stackKey);
  if (stack) {
    stack.itemCount = stackItems.length;
    await setKVRaw(stackKey, stack);
  }

  // Update reverse index: item → stacks
  const itemStacks: string[] = (await getKVRaw(itemStacksKey)) || [];
  if (!itemStacks.includes(stackId)) {
    itemStacks.push(stackId);
    await setKVRaw(itemStacksKey, itemStacks);
  }
}

// ---------------------------------------------------------------------------
// Route handlers
// ---------------------------------------------------------------------------

export async function OPTIONS() {
  return handleOptions();
}

export async function POST(request: NextRequest) {
  try {
    // 1. Extract partner key from header
    const rawKey = request.headers.get("x-partner-key")?.trim() || "";
    if (!rawKey || !rawKey.startsWith("pk_")) {
      return corsError("Missing or invalid x-partner-key header", 401);
    }

    // 2. Hash the key and look up partner record
    const keyHash = await sha256Hex(rawKey);
    const partnerRows = await db
      .select()
      .from(partners)
      .where(eq(partners.partnerKeyHash, keyHash))
      .limit(1);

    if (partnerRows.length === 0) {
      return corsError("Invalid partner key", 401);
    }

    const partner = partnerRows[0];

    if (!partner.isActive) {
      return corsError("This partner key has been deactivated", 401);
    }

    // 3. Rate limiting — hourly window
    const hourCheck = await checkRateLimit(
      RATE_LIMIT_HOUR_PREFIX,
      keyHash,
      MAX_PER_HOUR,
      60 * 60 * 1000
    );
    if (!hourCheck.allowed) {
      return new Response(
        JSON.stringify({ error: `Hourly import limit (${MAX_PER_HOUR}) exceeded` }),
        {
          status: 429,
          headers: {
            "Content-Type": "application/json",
            "Retry-After": String(Math.ceil((hourCheck.resetAt - Date.now()) / 1000)),
            "Access-Control-Allow-Origin": "*",
          },
        }
      );
    }

    // Rate limiting — daily window
    const dayCheck = await checkRateLimit(
      RATE_LIMIT_DAY_PREFIX,
      keyHash,
      MAX_PER_DAY,
      24 * 60 * 60 * 1000
    );
    if (!dayCheck.allowed) {
      return new Response(
        JSON.stringify({ error: `Daily import limit (${MAX_PER_DAY}) exceeded` }),
        {
          status: 429,
          headers: {
            "Content-Type": "application/json",
            "Retry-After": String(Math.ceil((dayCheck.resetAt - Date.now()) / 1000)),
            "Access-Control-Allow-Origin": "*",
          },
        }
      );
    }

    // 4. Parse and validate body
    let body: Record<string, unknown> = {};
    try {
      body = await request.json();
    } catch {
      return corsError("Invalid JSON body", 400);
    }

    const address = typeof body.address === "string" ? body.address.trim() : "";
    const key = typeof body.key === "string" ? body.key.trim() : "";
    const title = typeof body.title === "string" ? body.title.trim() : "";
    const category = typeof body.category === "string" ? body.category.trim() : "general";
    // uploaderAddress is optional — when absent leave undefined (not defaulted to address)
    const uploaderAddress =
      typeof body.uploaderAddress === "string" && body.uploaderAddress.trim()
        ? body.uploaderAddress.trim()
        : undefined;
    // mediaType: accept explicit value from caller, or detect from key/title
    const VALID_MEDIA_TYPES = ["image", "audio", "video", "pdf", "text", "unknown"] as const;
    type ValidMediaType = typeof VALID_MEDIA_TYPES[number];
    const callerMediaType = typeof body.mediaType === "string" ? body.mediaType.trim() : "";
    const resolvedMediaType: ValidMediaType = (VALID_MEDIA_TYPES as readonly string[]).includes(callerMediaType)
      ? callerMediaType as ValidMediaType
      : detectMediaType(key) !== "unknown"
        ? detectMediaType(key)
        : detectMediaType(title);

    if (!address) return corsError("address is required", 400);
    if (!isValidAddress(address)) return corsError("address must be a valid Ethereum address (0x + 40 hex chars)", 400);
    if (!key) return corsError("key is required", 400);
    if (key.length > 200) return corsError("key must be 200 characters or less", 400);
    if (!title) return corsError("title is required", 400);
    if (title.length > 200) return corsError("title must be 200 characters or less", 400);
    if (uploaderAddress && !isValidAddress(uploaderAddress)) {
      return corsError("uploaderAddress must be a valid Ethereum address", 400);
    }

    // 5. Deduplicate — check if this address+key already exists in the discovery index
    const currentEntries = await fetchIndex();
    const existing = currentEntries.find(
      (e) =>
        e.operator.toLowerCase() === address.toLowerCase() &&
        e.contentKey.toLowerCase() === key.toLowerCase()
    );

    if (existing) {
      const appUrl = process.env.NEXT_PUBLIC_URL || "";
      return corsResponse(
        {
          imported: false,
          reason: "already_exists",
          itemId: existing.contentKey,
          url: appUrl ? `${appUrl}/item/${encodeURIComponent(existing.contentKey)}` : null,
        },
        200
      );
    }

    // 6. Verify content exists on Net Protocol
    const { found, cdnUrl } = await verifyContentOnChain(address, key);
    if (!found) {
      return corsResponse(
        {
          error:
            "Content not found on Net Protocol. Verify the address and key are correct.",
          address,
          key,
        },
        404
      );
    }

    // 7. Build the discovery entry
    const entry: DiscoveryEntry = {
      contentKey: key,
      metadataKey: key,
      operator: address.toLowerCase(),
      // Only set uploaderAddress when the caller provided one — avoids showing
      // a storage contract address as the "uploader" in the UI
      ...(uploaderAddress ? { uploaderAddress: uploaderAddress.toLowerCase() } : {}),
      title,
      author: "Unknown",
      categories: category ? [category] : ["general"],
      fileSize: 0,
      storageType: "regular",
      uploadedAt: Date.now(),
      cdnUrl,
      mediaType: resolvedMediaType,
      source: partner.siteName, // Partner attribution
    };

    // 8. Prepend to discovery index (most recent first)
    currentEntries.unshift(entry);
    await storeIndex(currentEntries);

    // 9. Add to partner's dedicated stack (with proper reverse-index update)
    try {
      await addItemToStack(partner.stackId, key, address.toLowerCase());
    } catch (stackErr) {
      // Non-fatal — import succeeded even if stack update fails
      console.error("[import] Stack update error:", stackErr);
    }

    // 10. Increment partner total_imports counter
    try {
      await db
        .update(partners)
        .set({ totalImports: (partner.totalImports ?? 0) + 1 })
        .where(eq(partners.id, partner.id));
    } catch (e) {
      console.error("[import] Failed to increment totalImports:", e);
    }

    const appUrl = process.env.NEXT_PUBLIC_URL || "";

    console.log(
      `[POST /api/v1/library/import] Imported "${title}" for partner "${partner.siteName}" (id=${partner.id})`
    );

    return corsResponse(
      {
        imported: true,
        itemId: key,
        url: appUrl ? `${appUrl}/item/${encodeURIComponent(key)}` : null,
        stackId: partner.stackId,
        source: partner.siteName,
      },
      201
    );
  } catch (error) {
    console.error("[POST /api/v1/library/import] Error:", error);
    return corsError("Import failed", 500);
  }
}
src/app/api/v1/library/route.ts
/**
 * Library Catalog API
 *
 * GET /api/v1/library — Browse/paginate the library catalog
 * OPTIONS — CORS preflight
 */

import { NextRequest } from "next/server";
import {
  getKV,
  handleOptions,
  corsResponse,
  corsError,
} from "@/lib/agent-auth";
import type { DiscoveryEntry } from "@/lib/net-protocol";

// KV key for discovery index
const DISCOVERY_KEY = "discovery-index";

// Shape each item for the public API response
interface LibraryItem {
  title: string;
  author: string;
  categories: string[];
  contentKey: string;
  mediaType: string | null;
  cdnUrl: string | null;
  storageType: string;
  operator: string;
  uploadDate: number;
  uploader: {
    username: string | null;
    pfpUrl: string | null;
    address: string | null;
    fid: number | null;
  };
  // Social receipt fields
  isSocialReceipt: boolean;
  socialPlatform: string | null;
  originalUrl: string | null;
  sourceUrl: string | null;
  // Encryption flag
  encrypted: boolean;
  // Partner import attribution (null for directly uploaded items)
  source: string | null;
}

// For hex-encoded contentKeys (relay uploads), the stored cdnUrl uses /storage/load/
// with a title-derived filename which 404s. Override with /storage/raw/ + hex key,
// which is how book-content/route.ts fetches these correctly.
function resolvedCdnUrl(entry: DiscoveryEntry): string | null {
  const key = entry.contentKey;
  if (key && /^0x[0-9a-fA-F]+$/.test(key)) {
    return `https://storedon.net/net/8453/storage/raw/${entry.operator}/${key}`;
  }
  return entry.cdnUrl || null;
}

function shapeLibraryItem(entry: DiscoveryEntry): LibraryItem {
  return {
    title: entry.title,
    author: entry.author,
    categories: entry.categories || [],
    contentKey: entry.contentKey,
    mediaType: entry.mediaType || null,
    cdnUrl: resolvedCdnUrl(entry),
    storageType: entry.storageType,
    operator: entry.operator,
    uploadDate: entry.uploadedAt,
    uploader: {
      username: entry.uploaderUsername || entry.uploaderStoredUsername || null,
      pfpUrl: entry.uploaderPfpUrl || null,
      address: entry.uploaderAddress || entry.operator || null,
      fid: entry.uploaderFid || null,
    },
    isSocialReceipt: entry.isSocialReceipt || false,
    socialPlatform: entry.socialPlatform || null,
    originalUrl: entry.originalUrl || null,
    sourceUrl: entry.sourceUrl || entry.originalUrl || null,
    encrypted: entry.encrypted || false,
    source: entry.source || null,
  };
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/v1/library — Fetch library catalog with pagination, sorting, filtering
 *
 * Query params:
 * - page (default 1)
 * - limit (default 20, max 50)
 * - category (filter by category)
 * - mediaType (filter by media type)
 * - sort (newest/oldest/title)
 * - hidden (include hidden items if "true")
 * - socialOnly (only social receipts if "true")
 * - search (search in title/author)
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);

    // Parse query parameters
    const page = Math.max(1, parseInt(searchParams.get("page") || "1", 10));
    const limit = Math.min(50, Math.max(1, parseInt(searchParams.get("limit") || searchParams.get("pageSize") || "20", 10)));
    const sortParam = searchParams.get("sort") || searchParams.get("sortBy") || "newest";
    const category = searchParams.get("category")?.toLowerCase().trim() || null;
    const mediaType = searchParams.get("mediaType")?.toLowerCase().trim() || null;
    const includeHidden = searchParams.get("hidden") === "true";
    const socialOnly = searchParams.get("socialOnly") === "true";
    const search = searchParams.get("search")?.toLowerCase().trim() || null;

    // Fetch discovery index from KV
    const entries = await getKV<DiscoveryEntry[]>(DISCOVERY_KEY) || [];

    // Filter entries
    let filteredEntries = entries;

    // Filter hidden items (exclude by default)
    if (!includeHidden) {
      filteredEntries = filteredEntries.filter((e) => !e.hidden);
    }

    // Apply category filter
    if (category) {
      filteredEntries = filteredEntries.filter((e) =>
        e.categories?.some((c) => c.toLowerCase() === category)
      );
    }

    // Apply mediaType filter
    if (mediaType) {
      filteredEntries = filteredEntries.filter((e) =>
        e.mediaType?.toLowerCase() === mediaType
      );
    }

    // Apply socialOnly filter
    if (socialOnly) {
      filteredEntries = filteredEntries.filter((e) => e.isSocialReceipt === true);
    }

    // Apply search filter
    if (search) {
      filteredEntries = filteredEntries.filter((e) => {
        const titleMatch = e.title?.toLowerCase().includes(search);
        const authorMatch = e.author?.toLowerCase().includes(search);
        return titleMatch || authorMatch;
      });
    }

    // Sort entries
    switch (sortParam) {
      case "oldest":
        filteredEntries.sort((a, b) => (a.uploadedAt || 0) - (b.uploadedAt || 0));
        break;
      case "title":
        filteredEntries.sort((a, b) => (a.title || "").localeCompare(b.title || ""));
        break;
      case "newest":
      default:
        filteredEntries.sort((a, b) => (b.uploadedAt || 0) - (a.uploadedAt || 0));
        break;
    }

    // Calculate pagination
    const total = filteredEntries.length;
    const totalPages = Math.ceil(total / limit);
    const startIndex = (page - 1) * limit;
    const paginatedEntries = filteredEntries.slice(startIndex, startIndex + limit);
    const hasMore = page < totalPages;

    // Shape items for response
    const items = paginatedEntries.map(shapeLibraryItem);

    return corsResponse({
      success: true,
      items,
      pagination: {
        page,
        limit,
        total,
        totalPages,
        hasMore,
      },
    });
  } catch (error) {
    console.error("[GET /api/v1/library] Error:", error);
    return corsError("Failed to fetch library catalog", 500);
  }
}
src/app/api/v1/library/upload/route.ts
/* eslint-disable @neynar/no-process-env */
import { NextRequest } from "next/server";
import { stringToHex } from "viem";
import {
  getKV,
  setKV,
  authenticateAgent,
  isAuthError,
  hasPermission,
  addEntryAtomically,
  atomicArrayUpdate,
} from "@/lib/agent-auth";
import {
  STORAGE_CONTRACT_ADDRESS,
  CHUNKED_STORAGE_ADDRESS,
  STORAGE_ABI,
  CHUNKED_STORAGE_ABI,
  BASE_CHAIN_ID,
  getCdnUrl,
  generateStorageKey,
  detectMediaTypeFromMime,
  detectMediaTypeFromExtension,
} from "@/lib/net-protocol";
import { chunkDataForStorage } from "@net-protocol/storage";
import type { DiscoveryEntry } from "@/lib/net-protocol";
import type { Stack, StackItem } from "@/features/app/types";
import { checkServerUploadLimit, recordServerUpload } from "@/lib/upload-rate-limit";
import { RELAY_API_URL, RELAY_SECRET_KEY, CHUNK_THRESHOLD, CHUNKED_THRESHOLD } from "@/lib/relay-upload";

// CORS headers for all responses
const CORS_HEADERS = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "POST, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type, Authorization",
  "Content-Type": "application/json",
};

// KV Keys
const STACK_PREFIX = "stack:";
const STACK_ITEMS_PREFIX = "stack-items:";
const ITEM_STACKS_PREFIX = "item-stacks:";

// Stack item limit
const STACK_ITEM_LIMIT = 20;

// Fallback operator address when relay response doesn't include backendWalletAddress.
// Set RELAY_BACKEND_WALLET in your .env to the relay's backend wallet address.
const RELAY_BACKEND_WALLET_FALLBACK = process.env.RELAY_BACKEND_WALLET || "";

// Size limits
const MAX_FILE_SIZE = 15 * 1024 * 1024; // 15MB for member uploads
// CHUNK_THRESHOLD and CHUNKED_THRESHOLD are imported from relay-upload.ts (single source of truth)

// Helper: Convert buffer to base64
function bufferToBase64(buffer: Buffer): string {
  return buffer.toString("base64");
}

// Helper: Determine storage type based on file size
function getStorageType(fileSize: number): "regular" | "chunked" | "xml" {
  if (fileSize < CHUNK_THRESHOLD) return "regular";
  if (fileSize < CHUNKED_THRESHOLD) return "chunked";
  return "xml";
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return new Response(null, { status: 204, headers: CORS_HEADERS });
}

/**
 * POST /api/v1/library/upload — Upload a file to Net Protocol via relay
 * Requires API key with "library:write" permission
 *
 * Accepts multipart/form-data with:
 * - file: The binary file to upload (required)
 * - title: Item title (required)
 * - author: Author name (optional, defaults to agent name)
 * - categories: Comma-separated categories (optional)
 * - description: Item description (optional)
 * - addToStack: Stack ID to add the item to (optional)
 */
export async function POST(request: NextRequest) {
  try {
    // Authenticate agent
    const authResult = await authenticateAgent(request);
    if (isAuthError(authResult)) {
      // Convert NextResponse to Response with CORS headers
      const errorBody = await authResult.json();
      return new Response(
        JSON.stringify(errorBody),
        { status: authResult.status, headers: CORS_HEADERS }
      );
    }

    const { agent } = authResult;

    // Check permission
    if (!hasPermission(agent, "library:write")) {
      return new Response(
        JSON.stringify({ success: false, error: "Insufficient permissions. Requires 'library:write'" }),
        { status: 403, headers: CORS_HEADERS }
      );
    }

    // Server-side daily upload rate limit check.
    // Prevents CLI/API users from bypassing the client-side warm-up enforcement.
    if (agent.address) {
      const rateCheck = await checkServerUploadLimit(agent.address, agent.fid);
      if (!rateCheck.allowed) {
        return new Response(
          JSON.stringify({ success: false, error: rateCheck.error }),
          { status: rateCheck.status, headers: CORS_HEADERS }
        );
      }
    }

    // Parse multipart form data
    const formData = await request.formData();
    const file = formData.get("file") as File | null;
    const title = formData.get("title") as string | null;
    const author = formData.get("author") as string | null;
    const categoriesStr = formData.get("categories") as string | null;
    const description = formData.get("description") as string | null;
    const addToStack = formData.get("addToStack") as string | null;
    const encryptedStr = formData.get("encrypted") as string | null;
    const isEncrypted = encryptedStr === "true";
    // Session token created client-side via EIP-712 signing and sent with the upload request.
    // The server passes it through to the relay submit call — no server-side session creation needed.
    const clientSessionToken = formData.get("sessionToken") as string | null;

    // Validate required fields
    if (!file) {
      return new Response(
        JSON.stringify({ success: false, error: "File is required" }),
        { status: 400, headers: CORS_HEADERS }
      );
    }

    if (!title || !title.trim()) {
      return new Response(
        JSON.stringify({ success: false, error: "Title is required" }),
        { status: 400, headers: CORS_HEADERS }
      );
    }

    // Check file size
    if (file.size > MAX_FILE_SIZE) {
      return new Response(
        JSON.stringify({
          success: false,
          error: `File too large. Maximum size is ${MAX_FILE_SIZE / 1024 / 1024}MB`,
        }),
        { status: 413, headers: CORS_HEADERS }
      );
    }

    // Read file content
    const arrayBuffer = await file.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);
    const fileSize = buffer.length;

    // Determine storage type
    const storageType = getStorageType(fileSize);
    const timestamp = Date.now();

    // Generate storage key
    const storageKey = generateStorageKey(`netlib-${file.name}-${timestamp}`);

    // Convert file to base64 for storage
    const dataAsBase64 = bufferToBase64(buffer);
    const dataHex = stringToHex(dataAsBase64);

    console.log(`[UPLOAD] Starting upload: file="${file.name}" size=${fileSize}B storageType=${storageType}`);
    console.log(`[UPLOAD] storageKey=${storageKey}`);
    console.log(`[UPLOAD] agent: id=${agent.id} name=${agent.name}`);
    console.log(`[UPLOAD] relay: ${RELAY_API_URL} secretKey=${RELAY_SECRET_KEY.slice(0, 20)}...`);
    console.log(`[UPLOAD] agent.address=${agent.address} RELAY_BACKEND_WALLET fallback configured: ${!!RELAY_BACKEND_WALLET_FALLBACK}`);

    // Prepare transaction(s) based on storage type.
    //
    // The relay expects { to, abi, functionName, args } — NOT pre-encoded calldata.
    // It decodes the function call server-side, which is how it validates that only
    // allowed functions (e.g. "put") are being called on allowed contracts.
    // Sending pre-encoded `data` causes the relay to reject with:
    //   "Invalid function 'undefined' for contract 0x... Only 'put' is allowed."
     
    interface RelayTransaction {
      to: string;
      abi: readonly unknown[];
      functionName: string;
      args: unknown[];
    }

    const transactions: RelayTransaction[] = [];

    if (storageType === "regular") {
      // Small files: single Storage.put() call
      transactions.push({
        to: STORAGE_CONTRACT_ADDRESS,
        abi: STORAGE_ABI,
        functionName: "put",
        args: [storageKey, file.name, dataHex],
      });
    } else if (storageType === "chunked") {
      // Medium files: single ChunkedStorage.put() call
      const chunks = chunkDataForStorage(dataAsBase64);

      transactions.push({
        to: CHUNKED_STORAGE_ADDRESS,
        abi: CHUNKED_STORAGE_ABI,
        functionName: "put",
        args: [storageKey, file.name, chunks],
      });
    } else {
      // XML storage for large files (>80KB)
      // Split into 80KB chunks, compress each, store separately
      const XML_CHUNK_SIZE = 80000;
      const xmlChunks: Array<{ key: `0x${string}`; compressedChunks: string[] }> = [];

      for (let i = 0; i < dataAsBase64.length; i += XML_CHUNK_SIZE) {
        const chunkString = dataAsBase64.slice(i, i + XML_CHUNK_SIZE);
        const compressedChunks = chunkDataForStorage(chunkString);
        const chunkKey = generateStorageKey(`netlib-chunk-${file.name}-${timestamp}-${i}`);

        xmlChunks.push({ key: chunkKey, compressedChunks });

        transactions.push({
          to: CHUNKED_STORAGE_ADDRESS,
          abi: CHUNKED_STORAGE_ABI,
          functionName: "put",
          args: [chunkKey, "", compressedChunks],
        });
      }

      // Metadata transaction pointing to all chunks
      const xmlMetadata = JSON.stringify({
        type: "xml",
        chunks: xmlChunks.map(c => c.key),
        fileName: file.name,
        fileSize,
      });

      transactions.push({
        to: STORAGE_CONTRACT_ADDRESS,
        abi: STORAGE_ABI,
        functionName: "put",
        args: [storageKey, file.name, stringToHex(xmlMetadata)],
      });
    }

    console.log(`[UPLOAD] Prepared ${transactions.length} transaction(s)`);

    // Two-step relay flow for server-to-server uploads:
    //
    // Step 1: Balance — POST /api/relay/balance with agent.address as operatorAddress.
    //   Resolves backendWalletAddress (unique per operator) for CDN URL generation.
    //
    // Step 2: Submit — POST /api/relay/submit with secretKey + operatorAddress.
    //   secretKey in the body is sufficient auth — no sessionToken required.
    //   Confirmed: relay accepts { secretKey, operatorAddress, chainId, transactions }
    //   and only rejects if transactions is empty, not for missing sessionToken.
    //
    // We call netprotocol.app DIRECTLY (not via local proxies — those are client-session
    // proxies that require an already-established operatorAddress + sessionToken as input).

    if (!agent.address) {
      console.error(`[UPLOAD] Agent "${agent.id}" has no wallet address — cannot call relay`);
      return new Response(
        JSON.stringify({ success: false, error: "Agent has no wallet address configured" }),
        { status: 500, headers: CORS_HEADERS }
      );
    }

    // Step 1: Balance call — resolves backendWalletAddress for CDN URL generation.
    // backendWalletAddress is the relay's internal wallet that writes transactions on-chain.
    // It is NOT used as operatorAddress in the submit call — the session is tied to agent.address,
    // so submit must use agent.address as operatorAddress or the relay returns 401.
    const balanceUrl = `${RELAY_API_URL}/api/relay/balance`;
    console.log(`[UPLOAD] Step 1 — balance call: POST ${balanceUrl} operatorAddress=${agent.address.slice(0, 10)}...`);

    let backendWalletAddress: string | null = null;
    try {
      const balanceResponse = await fetch(balanceUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-Relay-Secret": RELAY_SECRET_KEY,
        },
        body: JSON.stringify({
          operatorAddress: agent.address,
          chainId: BASE_CHAIN_ID,
          secretKey: RELAY_SECRET_KEY,
        }),
      });
      const balanceRaw = await balanceResponse.text();
      console.log(`[UPLOAD] Balance response (${balanceResponse.status}): ${balanceRaw.slice(0, 300)}`);
      if (balanceResponse.ok) {
        const balanceResult = JSON.parse(balanceRaw);
        backendWalletAddress = balanceResult.backendWalletAddress || null;
        console.log(`[UPLOAD] backendWalletAddress resolved: ${backendWalletAddress}`);
      } else {
        console.error(`[UPLOAD] Balance call failed (${balanceResponse.status})`);
      }
    } catch (balanceErr) {
      console.error(`[UPLOAD] Balance call network error:`, balanceErr);
    }

    // operatorAddress for submit must match what the session was created with — agent.address.
    // backendWalletAddress (from balance call) is only used for CDN URL generation below.
    const operatorAddressForSubmit = agent.address;

    // Step 2: Submit transactions.
    // sessionToken was created client-side (EIP-712, tied to agent.address) and sent in form data.
    // Falls back to secretKey for direct server-to-server calls without a client session.
    const sessionTokenForSubmit = clientSessionToken || RELAY_SECRET_KEY;
    const submitUrl = `${RELAY_API_URL}/api/relay/submit`;
    const submitBody = {
      transactions,        // each has { to, abi, functionName, args } — relay encodes calldata
      operatorAddress: operatorAddressForSubmit,
      sessionToken: sessionTokenForSubmit,
      secretKey: RELAY_SECRET_KEY,
      chainId: BASE_CHAIN_ID,
    };

    console.log(`[UPLOAD] Step 2 — relay submit: POST ${submitUrl}`);
    console.log(`[UPLOAD] Submit request shape:`, {
      txCount: transactions.length,
      chainId: BASE_CHAIN_ID,
      operatorAddress: operatorAddressForSubmit.slice(0, 10) + "...",
      sessionTokenSource: clientSessionToken ? "client" : "secretKey_fallback",
      secretKeyPresent: !!RELAY_SECRET_KEY,
      firstTxTo: transactions[0]?.to,
      firstTxFunctionName: transactions[0]?.functionName,
    });

    let submitRawResponse: Response;
    try {
      submitRawResponse = await fetch(submitUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-Relay-Secret": RELAY_SECRET_KEY,
        },
        body: JSON.stringify(submitBody),
      });
    } catch (networkErr) {
      console.error(`[UPLOAD] Network error reaching relay at ${submitUrl}:`, networkErr);
      return new Response(
        JSON.stringify({ success: false, error: "Failed to reach relay service — network error" }),
        { status: 502, headers: CORS_HEADERS }
      );
    }

    console.log(`[UPLOAD] Relay submit HTTP status: ${submitRawResponse.status}`);

    // Always capture raw body text before parsing so we can log it on any error
    const rawResponseBody = await submitRawResponse.text();
    console.log(`[UPLOAD] Relay submit raw response (first 600 chars): ${rawResponseBody.slice(0, 600)}`);

    let submitResult: Record<string, unknown>;
    try {
      submitResult = JSON.parse(rawResponseBody);
    } catch {
      console.error(`[UPLOAD] Relay returned non-JSON (status=${submitRawResponse.status}): ${rawResponseBody.slice(0, 300)}`);
      return new Response(
        JSON.stringify({
          success: false,
          error: "Relay returned non-JSON response",
          relay_status: submitRawResponse.status,
          relay_body_preview: rawResponseBody.slice(0, 200),
        }),
        { status: 502, headers: CORS_HEADERS }
      );
    }

    if (!submitRawResponse.ok) {
      console.error(`[UPLOAD] Relay submit failed — HTTP ${submitRawResponse.status}:`, submitResult);
      return new Response(
        JSON.stringify({
          success: false,
          error: (submitResult.error as string) || `Relay submission failed (HTTP ${submitRawResponse.status})`,
          relay_status: submitRawResponse.status,
          relay_response: submitResult,
        }),
        { status: 502, headers: CORS_HEADERS }
      );
    }

    console.log(`[UPLOAD] Relay submit succeeded:`, {
      backendWalletAddress: submitResult.backendWalletAddress,
      transactionHashes: submitResult.transactionHashes,
      transactionHash: submitResult.transactionHash,
      successfulIndexes: submitResult.successfulIndexes,
      failedIndexes: submitResult.failedIndexes,
    });

    // Collect tx hashes
    const txHashes: string[] = [];
    if (Array.isArray(submitResult.transactionHashes)) {
      txHashes.push(...(submitResult.transactionHashes as string[]));
    } else if (typeof submitResult.transactionHash === "string") {
      txHashes.push(submitResult.transactionHash);
    }

    // Resolve the relay's backendWalletAddress for CDN URL generation.
    // The relay's backend wallet is what actually writes to chain, so CDN URLs must use it.
    // Priority: submit response (most authoritative) → balance call result → env var fallback.
    // NOTE: agent.address is NOT correct here — it's the operator identity, not the writer.
    const operatorAddress =
      (submitResult.backendWalletAddress as string | undefined) ||
      backendWalletAddress ||
      RELAY_BACKEND_WALLET_FALLBACK ||
      agent.address; // last resort — CDN URLs may not resolve but upload still succeeds

    console.log(`[UPLOAD] backendWalletAddress for CDN: "${operatorAddress}" (source: ${submitResult.backendWalletAddress ? "submit_response" : backendWalletAddress ? "balance_call" : RELAY_BACKEND_WALLET_FALLBACK ? "env_var" : "agent_address_fallback"})`);


    console.log(`[UPLOAD] All transactions submitted. operatorAddress=${operatorAddress} txCount=${txHashes.length}`);

    // Generate CDN URL
    const cdnUrl = getCdnUrl(BASE_CHAIN_ID, operatorAddress, storageKey, storageType, file.name);

    // Detect media type
    const mediaType = detectMediaTypeFromMime(file.type) || detectMediaTypeFromExtension(file.name) || "unknown";

    // Parse categories
    const categories = categoriesStr
      ? categoriesStr.split(",").map(c => c.trim()).filter(c => c.length > 0)
      : [];

    // Create discovery entry
    const newEntry: DiscoveryEntry = {
      contentKey: storageKey,
      metadataKey: storageKey,
      operator: operatorAddress,
      uploaderAddress: agent.address || "",
      title: title.trim(),
      author: author?.trim() || agent.name,
      categories,
      fileSize,
      uploadedAt: timestamp,
      storageType,
      cdnUrl,
      fileName: file.name,
      mediaType: mediaType as DiscoveryEntry["mediaType"],
      uploaderFid: agent.fid,
      uploaderUsername: agent.username || agent.name,
      uploaderPfpUrl: agent.pfpUrl,
      // Agent tracking
      isAgentUploaded: true,
      agentId: agent.id,
      // @ts-expect-error - description not in DiscoveryEntry type yet
      description: description?.trim() || undefined,
      // Encryption flag — content was encrypted client-side before upload
      ...(isEncrypted ? { encrypted: true } : {}),
    };

    // Append to discovery index atomically
    const addResult = await addEntryAtomically(newEntry, false); // append to end

    if (!addResult.success) {
      console.error("[UPLOAD] Atomic add to discovery index failed:", addResult.error);
      return new Response(
        JSON.stringify({ success: false, error: "Failed to register item in library" }),
        { status: 500, headers: CORS_HEADERS }
      );
    }

    if (addResult.isDuplicate) {
      console.log(`[UPLOAD] Item already exists: ${storageKey}`);
      // Still return success since the upload to blockchain succeeded
    }

    console.log(`[UPLOAD] Item registered: ${storageKey}`);

    // Increment server-side upload counter (fire-and-forget — doesn't block response)
    if (agent.address) {
      recordServerUpload(agent.address, fileSize).catch(err =>
        console.error("[UPLOAD] Failed to record upload counter:", err)
      );
    }

    // Optionally add to stack
    let addedToStack = false;
    let stackError: string | null = null;

    if (addToStack) {
      try {
        const stack = await getKV<Stack>(`${STACK_PREFIX}${addToStack}`);

        if (!stack) {
          stackError = `Stack "${addToStack}" not found`;
        } else {
          // Use atomic operation with 20-item limit check
          const atomicResult = await atomicArrayUpdate<StackItem, { duplicate?: boolean; limitExceeded?: boolean; itemCount?: number }>(
            `${STACK_ITEMS_PREFIX}${addToStack}`,
            (items) => {
              if (items.some(item => item.contentKey === storageKey)) {
                return { abort: true, result: { duplicate: true } };
              }

              // Check 20-item limit if stack is not unlocked
              if (!stack.unlocked && items.length >= STACK_ITEM_LIMIT) {
                return { abort: true, result: { limitExceeded: true } };
              }

              const newItem: StackItem = {
                contentKey: storageKey,
                addedAt: Date.now(),
                addedBy: agent.address?.toLowerCase() || agent.id,
              };

              return {
                updated: [...items, newItem],
                result: { itemCount: items.length + 1 }
              };
            }
          );

          if (!atomicResult.success) {
            stackError = atomicResult.error || "Failed to add to stack";
          } else if (atomicResult.result?.duplicate) {
            stackError = "Item already in stack";
          } else if (atomicResult.result?.limitExceeded) {
            stackError = `Stack is full (${STACK_ITEM_LIMIT} items) — unlock required`;
          } else {
            stack.itemCount = atomicResult.result?.itemCount || 0;
            await setKV(`${STACK_PREFIX}${addToStack}`, stack);

            const itemStacks = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${storageKey}`) || [];
            if (!itemStacks.includes(addToStack)) {
              itemStacks.push(addToStack);
              await setKV(`${ITEM_STACKS_PREFIX}${storageKey}`, itemStacks);
            }

            addedToStack = true;
            console.log(`[UPLOAD] Item added to stack ${addToStack}`);
          }
        }
      } catch (err) {
        console.error("[UPLOAD] Error adding to stack:", err);
        stackError = "Failed to add to stack";
      }
    }

    // Build response
    const responseData: Record<string, unknown> = {
      success: true,
      item: {
        contentKey: storageKey,
        cdnUrl,
        title: newEntry.title,
        author: newEntry.author,
        mediaType,
        fileSize,
        storageType,
        categories,
      },
      transactions: {
        count: txHashes.length,
        hashes: txHashes,
      },
    };

    if (addToStack) {
      if (addedToStack) {
        responseData.addedToStack = addToStack;
      } else if (stackError) {
        responseData.stackWarning = stackError;
      }
    }

    return new Response(
      JSON.stringify(responseData),
      { status: 201, headers: CORS_HEADERS }
    );
  } catch (error) {
    console.error("[POST /api/v1/library/upload] Error:", error);
    return new Response(
      JSON.stringify({ success: false, error: "Internal server error" }),
      { status: 500, headers: CORS_HEADERS }
    );
  }
}
src/app/api/v1/library/write/route.ts
/**
 * Library Write API
 *
 * POST /api/v1/library/write — Register a new library item
 * OPTIONS — CORS preflight
 *
 * Auth required, membership required.
 * Uses atomic add pattern with FOR UPDATE locking to prevent race conditions.
 */

import { NextRequest } from "next/server";
import { keccak256, toHex } from "viem";
import { checkServerUploadLimit, recordServerUpload } from "@/lib/upload-rate-limit";
import {
  getKV,
  setKV,
  authenticateCaller,
  resolveCallerMember,
  hasPermission,
  handleOptions,
  corsResponse,
  corsError,
  addEntryAtomically,
  atomicArrayUpdate,
  getMemberRegistry,
} from "@/lib/agent-auth";
import type { DiscoveryEntry } from "@/lib/net-protocol";
import type { Stack, StackItem } from "@/features/app/types";

// KV Keys
const STACK_PREFIX = "stack:";
const STACK_ITEMS_PREFIX = "stack-items:";
const ITEM_STACKS_PREFIX = "item-stacks:";

// Valid media types
const VALID_MEDIA_TYPES = ["pdf", "image", "audio", "video", "text", "unknown"] as const;
type MediaType = (typeof VALID_MEDIA_TYPES)[number];

// Valid storage types
const VALID_STORAGE_TYPES = ["regular", "chunked", "xml"] as const;
type StorageType = (typeof VALID_STORAGE_TYPES)[number];

// Helper: Generate content key from URL (if not provided)
function generateContentKeyFromUrl(url: string): string {
  const hash = keccak256(toHex(url));
  return hash.slice(0, 42); // 0x + 40 hex chars
}

// Helper: Detect media type from URL extension
function detectMediaTypeFromUrl(url: string): MediaType {
  const lowerUrl = url.toLowerCase();
  const urlPath = lowerUrl.split("?")[0];
  const extension = urlPath.split(".").pop();

  if (!extension) return "unknown";

  if (extension === "pdf") return "pdf";
  if (["jpg", "jpeg", "png", "gif", "webp", "svg", "bmp", "ico"].includes(extension)) return "image";
  if (["mp3", "wav", "ogg", "flac", "m4a", "aac", "wma"].includes(extension)) return "audio";
  if (["mp4", "webm", "mov", "avi", "mkv", "m4v", "wmv"].includes(extension)) return "video";
  if (["txt", "md", "markdown", "rtf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "json", "xml", "csv"].includes(extension)) return "text";

  return "unknown";
}

// Helper: Detect media type from a raw filename (uses same extension table)
function detectMediaTypeFromFileName(name: string): MediaType {
  return detectMediaTypeFromUrl(name); // extension table is identical
}

// Helper: Validate URL format
function isValidUrl(url: string): boolean {
  try {
    const parsed = new URL(url);
    return ["http:", "https:", "ipfs:"].includes(parsed.protocol);
  } catch {
    return false;
  }
}

// Helper: Validate content key format
function isValidContentKey(key: string): boolean {
  return /^0x[a-fA-F0-9]{40,64}$/.test(key);
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * POST /api/v1/library/write — Register a new library item
 *
 * Body:
 * - contentKey (optional): Net Protocol content key (if not provided, generated from cdnUrl)
 * - cdnUrl (required if no contentKey): Direct URL to the content
 * - title (required): Item title
 * - author (optional): Author name
 * - categories (optional): Array of category strings
 * - mediaType (optional): pdf, image, audio, video, text, unknown
 * - fileSize (optional): File size in bytes
 * - storageType (optional): regular, chunked, xml
 * - coverUrl (optional): Cover art URL
 * - fileName (optional): Original filename
 * - publicationYear (optional): Year of publication
 * - publisher (optional): Publisher name
 * - isbn (optional): ISBN number
 * - addToStack (optional): Stack ID to add the item to after registration
 *
 * Requires API key with "library:write" permission and membership.
 */
export async function POST(request: NextRequest) {
  try {
    // 1. Parse body first (needed for Farcaster/web auth identity)
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    let body: Record<string, any> = {};
    try {
      body = await request.json();
    } catch {
      // Body may be absent for Bearer-only callers
    }

    // 2. Authenticate caller (Bearer or Farcaster/web)
    const caller = await authenticateCaller(request, body);
    if (caller instanceof Response) return caller;

    // 3. Bearer agents must have library:write permission
    if (caller.type === "bearer" && caller.agent && !hasPermission(caller.agent, "library:write")) {
      return corsError("Insufficient permissions. Requires 'library:write'", 403);
    }

    // 4. Caller must be a member
    const registry = await getMemberRegistry();
    const memberEntry = resolveCallerMember(caller, registry);

    if (!memberEntry) {
      return corsError("Membership required. Register as a member to write to the library.", 403);
    }

    // 5a. Server-side daily upload rate limit check.
    // Prevents CLI/API users from bypassing the client-side warm-up enforcement.
    const uploaderAddress = memberEntry.address;
    const uploaderFid = memberEntry.fid ?? (caller.type === "farcaster" ? caller.fid : undefined);
    if (uploaderAddress) {
      const rateCheck = await checkServerUploadLimit(uploaderAddress, uploaderFid);
      if (!rateCheck.allowed) {
        return corsError(rateCheck.error, rateCheck.status);
      }
    }

    // 5. Destructure already-parsed body
    const {
      contentKey: providedContentKey,
      cdnUrl,
      title,
      author,
      categories,
      mediaType: requestedMediaType,
      fileSize,
      storageType: requestedStorageType,
      coverUrl,
      fileName,
      publicationYear,
      publisher,
      isbn,
      addToStack,
      encrypted: encryptedBody,
    } = body;
    const isEncrypted = encryptedBody === true;

    // 5. Validate required fields
    if (!title || typeof title !== "string" || !title.trim()) {
      return corsError("Title is required", 400);
    }

    // Need either contentKey or cdnUrl
    if (!providedContentKey && !cdnUrl) {
      return corsError("Either contentKey or cdnUrl is required", 400);
    }

    // Validate contentKey format if provided
    if (providedContentKey && !isValidContentKey(providedContentKey)) {
      return corsError("Invalid contentKey format. Must be 0x followed by 40-64 hex characters", 400);
    }

    // Validate cdnUrl format if provided
    if (cdnUrl && !isValidUrl(cdnUrl)) {
      return corsError("Invalid cdnUrl format. Must be http, https, or ipfs", 400);
    }

    // Validate media type if provided
    if (requestedMediaType && !VALID_MEDIA_TYPES.includes(requestedMediaType)) {
      return corsError(`Invalid mediaType. Valid types: ${VALID_MEDIA_TYPES.join(", ")}`, 400);
    }

    // Validate storage type if provided
    if (requestedStorageType && !VALID_STORAGE_TYPES.includes(requestedStorageType)) {
      return corsError(`Invalid storageType. Valid types: ${VALID_STORAGE_TYPES.join(", ")}`, 400);
    }

    // Validate categories if provided
    if (categories && (!Array.isArray(categories) || categories.some((c: unknown) => typeof c !== "string"))) {
      return corsError("Categories must be an array of strings", 400);
    }

    // 6. Determine content key
    const contentKey = providedContentKey || generateContentKeyFromUrl(cdnUrl);

    // 7. Determine media type — cascade: explicit > cdnUrl extension > fileName extension > "unknown"
    let mediaType: MediaType = requestedMediaType || "unknown";
    if (mediaType === "unknown" && cdnUrl) {
      mediaType = detectMediaTypeFromUrl(cdnUrl);
    }
    if (mediaType === "unknown" && fileName) {
      mediaType = detectMediaTypeFromFileName(fileName);
    }

    // 8. Determine storage type
    const storageType: StorageType = requestedStorageType || "regular";

    // 9. Extract filename from URL if not provided
    let resolvedFileName = fileName;
    if (!resolvedFileName && cdnUrl) {
      const urlPath = cdnUrl.split("?")[0];
      resolvedFileName = urlPath.split("/").pop() || title;
    }

    // 9b. Construct cdnUrl fallback when not provided but operator + fileName are available.
    // Agents that write directly to the blockchain (relay path) often know the fileName but
    // don't provide a cdnUrl — constructing it here ensures the viewer can load the content.
    let resolvedCdnUrl: string | undefined = cdnUrl || undefined;
    if (!resolvedCdnUrl && uploaderAddress && resolvedFileName) {
      // /storage/load/<operator>/<fileName> is the standard CDN path for named files
      resolvedCdnUrl = `https://storedon.net/net/8453/storage/load/${uploaderAddress}/${encodeURIComponent(resolvedFileName)}`;
    }

    // Resolve canonical uploader identity from member entry.
    // Priority: customUsername (user-set, most intentional) > farcasterUsername (stable,
    //           set at Farcaster signup) > username > ensSubname.
    // We deliberately exclude displayName — it's a mutable free-text field and produces
    // the "Cheryl the Librarian" / "GEAUX & Cheryl" inconsistencies seen in older entries.
    const uploaderUsername =
      memberEntry.customUsername ??
      memberEntry.farcasterUsername ??
      memberEntry.username ??
      memberEntry.ensSubname;
    const uploaderPfpUrl = memberEntry.customPfpUrl ?? memberEntry.pfpUrl;
    const displayName =
      memberEntry.displayName ?? uploaderUsername ?? `Member #${memberEntry.memberId}`;

    // 10. Create discovery entry
    const newEntry: DiscoveryEntry = {
      contentKey,
      metadataKey: contentKey,
      operator: uploaderAddress || "0x0000000000000000000000000000000000000000",
      uploaderAddress: memberEntry.address,
      title: title.trim(),
      author: author?.trim() || displayName,
      categories: categories || [],
      fileSize: typeof fileSize === "number" && fileSize > 0 ? fileSize : 0,
      uploadedAt: Date.now(),
      storageType,
      cdnUrl: resolvedCdnUrl,
      fileName: resolvedFileName || undefined,
      mediaType,
      coverUrl: coverUrl || undefined,
      uploaderFid,
      uploaderUsername,
      uploaderPfpUrl,
      // Additional metadata
      publicationYear: publicationYear || undefined,
      publisher: publisher?.trim() || undefined,
      isbn: isbn?.trim() || undefined,
      // Auth tracking
      isAgentUploaded: caller.type === "bearer",
      agentId: caller.type === "bearer" ? caller.agentId : undefined,
      // Member tracking
      uploaderMemberId: memberEntry.memberId,
      uploaderEnsSubname: memberEntry.ensSubname,
      // Encryption flag — content was encrypted client-side before upload
      ...(isEncrypted ? { encrypted: true } : {}),
    };

    // 11. Add entry atomically (with FOR UPDATE locking)
    const addResult = await addEntryAtomically(newEntry, true); // prepend to beginning

    if (!addResult.success) {
      console.error("[POST /api/v1/library/write] Atomic add failed:", addResult.error);
      return corsError(addResult.error || "Failed to register item", 500);
    }

    if (addResult.isDuplicate) {
      return corsResponse({
        success: false,
        error: "Content already exists in library",
        existingContentKey: contentKey,
      }, 409);
    }

    console.log(`[POST /api/v1/library/write] Item registered by member #${memberEntry.memberId} (${caller.type}): ${contentKey}`);

    // Increment server-side upload counter (fire-and-forget)
    if (uploaderAddress) {
      recordServerUpload(uploaderAddress, body.fileSize ?? 0).catch(err =>
        console.error("[POST /api/v1/library/write] Failed to record upload counter:", err)
      );
    }

    // 12. If addToStack was provided, add the item to that stack
    let addedToStack = false;
    let stackError: string | null = null;
    const STACK_ITEM_LIMIT = 20;

    if (addToStack && typeof addToStack === "string") {
      try {
        const stack = await getKV<Stack>(`${STACK_PREFIX}${addToStack}`);

        if (!stack) {
          stackError = `Stack "${addToStack}" not found`;
        } else if (
          stack.owner &&
          stack.owner.toLowerCase() !== uploaderAddress.toLowerCase()
        ) {
          stackError = "You can only add items to your own stacks";
        } else {
          // Use atomic operation with 20-item limit check
          const atomicResult = await atomicArrayUpdate<StackItem, { duplicate?: boolean; limitExceeded?: boolean; itemCount?: number }>(
            `${STACK_ITEMS_PREFIX}${addToStack}`,
            (items) => {
              if (items.some(item => item.contentKey === contentKey)) {
                return { abort: true, result: { duplicate: true } };
              }

              // Check 20-item limit if stack is not unlocked
              if (!stack.unlocked && items.length >= STACK_ITEM_LIMIT) {
                return { abort: true, result: { limitExceeded: true } };
              }

              const newItem: StackItem = {
                contentKey,
                addedAt: Date.now(),
                addedBy: memberEntry.address?.toLowerCase() || String(memberEntry.memberId),
              };

              return {
                updated: [...items, newItem],
                result: { itemCount: items.length + 1 }
              };
            }
          );

          if (!atomicResult.success) {
            stackError = atomicResult.error || "Failed to add to stack";
          } else if (atomicResult.result?.duplicate) {
            stackError = "Item already in stack";
          } else if (atomicResult.result?.limitExceeded) {
            stackError = `Stack is full (${STACK_ITEM_LIMIT} items) — unlock required`;
          } else {
            stack.itemCount = atomicResult.result?.itemCount || 0;
            await setKV(`${STACK_PREFIX}${addToStack}`, stack);

            const itemStacks = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${contentKey}`) || [];
            if (!itemStacks.includes(addToStack)) {
              itemStacks.push(addToStack);
              await setKV(`${ITEM_STACKS_PREFIX}${contentKey}`, itemStacks);
            }

            addedToStack = true;
            console.log(`[POST /api/v1/library/write] Item added to stack ${addToStack}`);
          }
        }
      } catch (err) {
        console.error("[POST /api/v1/library/write] Error adding to stack:", err);
        stackError = "Failed to add to stack";
      }
    }

    // 13. Build response
    const response: Record<string, unknown> = {
      success: true,
      contentKey,
      item: {
        contentKey,
        title: newEntry.title,
        author: newEntry.author,
        cdnUrl: resolvedCdnUrl,
        mediaType,
        fileSize: newEntry.fileSize,
        storageType,
        categories: newEntry.categories,
        uploaderMemberId: memberEntry.memberId,
        uploaderEnsSubname: memberEntry.ensSubname,
      },
    };

    if (addToStack) {
      if (addedToStack) {
        response.addedToStack = addToStack;
      } else if (stackError) {
        response.stackWarning = stackError;
      }
    }

    return corsResponse(response, 201);
  } catch (error) {
    console.error("[POST /api/v1/library/write] Error:", error);
    return corsError("Internal server error", 500);
  }
}
src/app/api/v1/membership/api-key/route.ts
 
/**
 * Member API Key Management
 *
 * POST   /api/v1/membership/api-key — Generate/regenerate/revoke a key, or check status
 * GET    /api/v1/membership/api-key — Check key status (Bearer auth only)
 * DELETE /api/v1/membership/api-key — Revoke current API key (Bearer auth only)
 * OPTIONS — CORS preflight
 *
 * Auth: Two paths, tried in order:
 *
 *   Path A — Bearer token (agents + web members who already have a key):
 *     Authorization: Bearer <nlk_key>
 *     Identity resolved from the agent record (agentId → member entry).
 *     If a Bearer header is present but invalid, return 401 immediately.
 *     Do NOT fall through to Path B.
 *
 *   Path B — Farcaster frame / web user (members without a Bearer key yet):
 *     Body: { fid: number }  or  { address: "0x..." }
 *     The FID or address is passed by the client from the Farcaster SDK context
 *     (useFarcasterUser) or wallet (wagmi useAccount). This is consistent with
 *     how /api/membership and every other non-agent route in this codebase
 *     identifies web users — there is no server-side Farcaster signer
 *     verification in this codebase; identity comes from the client.
 *     If the fid/address does not resolve to a member entry, return 403.
 *
 * Endpoint behaviour:
 *
 *   POST   — Both paths (A and B). Actions:
 *            { action: "status" }              → status check, no mutation
 *            { action: "revoke" }              → revoke current key
 *            { fid|address }                   → generate new key
 *            { fid|address, regenerate: true } → replace existing key
 *            POST is the universal path that works for all clients.
 *
 *   GET    — Bearer-only (Path A). Convenience alias for agents/CLI tools.
 *            Farcaster/web users use POST { action: "status" } instead —
 *            there is no header-based Farcaster auth in this codebase.
 *
 *   DELETE — Bearer-only (Path A). Convenience alias for agents/CLI tools.
 *            Farcaster/web users use POST { action: "revoke" } instead —
 *            DELETE bodies are unreliable across proxies and CDNs.
 *
 * Constraint: Caller must be a Net Library member. Non-members get 403.
 */

import { NextRequest } from "next/server";
import {
  getKV,
  setKV,
  deleteKV,
  authenticateAgent,
  authenticateCaller,
  resolveCallerMember,
  isAuthError,
  getMemberRegistry,
  handleOptions,
  corsResponse,
  corsError,
  atomicArrayUpdate,
  updateMemberAtomically,
  // Types
  type AuthenticatedCaller,
  type RegisteredAgent,
  type MemberEntry,
  type MemberRegistry,
  // Constants
  AGENT_KEY_PREFIX,
  AGENTS_REGISTRY_KEY,
} from "@/lib/agent-auth";

// JOIN URL for non-members
const MINIAPP_JOIN_URL = "https://miniapp-generator-fid-282520-251210015136529.neynar.app/";

// =============================================================================
// TYPES
// =============================================================================

interface ApiKeyAgentRecord extends RegisteredAgent {
  type: "web-member" | "api-agent";
  memberId?: number;
  apiKeyPrefix?: string;
}

// =============================================================================
// KEY + ID GENERATION
// =============================================================================

function generateNlkApiKey(): string {
  const bytes = new Uint8Array(16);
  crypto.getRandomValues(bytes);
  const hex = Array.from(bytes)
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
  return `nlk_${hex}`;
}

function generateWebMemberAgentId(): string {
  const timestamp = Date.now();
  const bytes = new Uint8Array(3);
  crypto.getRandomValues(bytes);
  const random = Array.from(bytes)
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
  return `agent-${timestamp}-${random}`;
}

function notMemberResponse() {
  return corsResponse(
    {
      error: "Must be a Net Library member to manage API keys",
      joinUrl: MINIAPP_JOIN_URL,
      agentJoinEndpoint: "POST /api/v1/agents/membership",
    },
    403
  );
}

// =============================================================================
// SHARED REVOKE HELPER
// =============================================================================

/**
 * Revoke the API key for a resolved member.
 * Used by both POST { action: "revoke" } and DELETE (Bearer-only).
 */
async function revokeCallerKey(member: MemberEntry): Promise<Response> {
  if (!member.apiKeyAgentId) {
    return corsError("No API key to revoke", 400);
  }

  const agentRecord = await getKV<ApiKeyAgentRecord>(
    `${AGENT_KEY_PREFIX}${member.apiKeyAgentId}`
  );
  if (agentRecord) {
    await setKV(`${AGENT_KEY_PREFIX}${member.apiKeyAgentId}`, {
      ...agentRecord,
      isActive: false,
      deactivatedAt: Date.now(),
    });
    if (agentRecord.address) {
      await deleteKV(`agent-by-address:${agentRecord.address.toLowerCase()}`);
    }
  }

  await updateMemberAtomically(
    (reg: MemberRegistry) => reg.members.find((m) => m.memberId === member.memberId),
    (m: MemberEntry) => {
      delete m.apiKeyAgentId;
      delete m.apiKeyCreatedAt;
      return { memberId: m.memberId };
    }
  );

  console.log(
    `[/api/v1/membership/api-key] API key revoked for member #${member.memberId}`
  );

  return corsResponse({ success: true, message: "API key revoked" });
}

// =============================================================================
// OPTIONS
// =============================================================================

export async function OPTIONS() {
  return handleOptions();
}

// =============================================================================
// GET — Check if caller has an API key
// =============================================================================

export async function GET(request: NextRequest) {
  try {
    // GET is Bearer-only — no body parsing, no Farcaster path.
    // Farcaster/web users: use POST { action: "status" } for status checks.
    const authHeader =
      request.headers.get("Authorization") || request.headers.get("authorization");
    if (!authHeader?.startsWith("Bearer ")) {
      return corsError(
        'GET requires a Bearer token. Web/Farcaster users: POST { action: "status", fid } or { action: "status", address } instead.',
        401
      );
    }
    const result = await authenticateAgent(request);
    if (isAuthError(result)) return result;
    const caller: AuthenticatedCaller = {
      type: "bearer",
      agentId: result.agentId,
      agent: result.agent,
    };

    const registry = await getMemberRegistry();
    const member = resolveCallerMember(caller, registry);

    if (!member) return notMemberResponse();

    if (!member.apiKeyAgentId) {
      return corsResponse({ hasKey: false });
    }

    const agentRecord = await getKV<ApiKeyAgentRecord>(
      `${AGENT_KEY_PREFIX}${member.apiKeyAgentId}`
    );

    if (!agentRecord) {
      // Stale reference — treat as no key
      return corsResponse({ hasKey: false });
    }

    return corsResponse({
      hasKey: true,
      apiKeyPrefix: agentRecord.apiKeyPrefix || "nlk_???...",
      agentId: agentRecord.id,
      createdAt: agentRecord.createdAt,
      isActive: agentRecord.isActive !== false,
    });
  } catch (error) {
    console.error("[GET /api/v1/membership/api-key] Error:", error);
    return corsError("Failed to check API key status", 500);
  }
}

// =============================================================================
// POST — Generate or regenerate an API key
// =============================================================================

export async function POST(request: NextRequest) {
  try {
    let body: Record<string, unknown> = {};
    try {
      body = await request.json();
    } catch {
      // Body optional
    }

    const caller = await authenticateCaller(request, body);
    if (caller instanceof Response) return caller;

    const registry = await getMemberRegistry();
    const member = resolveCallerMember(caller, registry);

    if (!member) return notMemberResponse();

    // ------------------------------------------------------------------
    // action: "status" — status-only check, no key generation.
    // Used by Farcaster/web clients in place of GET (GET is Bearer-only).
    // ------------------------------------------------------------------
    if (body.action === "status") {
      if (!member.apiKeyAgentId) {
        return corsResponse({ hasKey: false });
      }
      const agentRecord = await getKV<ApiKeyAgentRecord>(
        `${AGENT_KEY_PREFIX}${member.apiKeyAgentId}`
      );
      if (!agentRecord) {
        return corsResponse({ hasKey: false });
      }
      return corsResponse({
        hasKey: true,
        apiKeyPrefix: agentRecord.apiKeyPrefix || "nlk_???...",
        agentId: agentRecord.id,
        createdAt: agentRecord.createdAt,
        isActive: agentRecord.isActive !== false,
      });
    }

    // ------------------------------------------------------------------
    // action: "revoke" — revoke current key.
    // Used by Farcaster/web clients in place of DELETE (DELETE is Bearer-only).
    // ------------------------------------------------------------------
    if (body.action === "revoke") {
      return revokeCallerKey(member);
    }

    const regenerate = body.regenerate === true;

    // ------------------------------------------------------------------
    // Existing key — return info or deactivate for regeneration
    // ------------------------------------------------------------------
    if (member.apiKeyAgentId) {
      if (!regenerate) {
        const existingAgent = await getKV<ApiKeyAgentRecord>(
          `${AGENT_KEY_PREFIX}${member.apiKeyAgentId}`
        );
        const prefix = existingAgent?.apiKeyPrefix || "nlk_???...";
        return corsResponse({
          success: true,
          hasKey: true,
          apiKeyPrefix: `${prefix}...`,
          createdAt: member.apiKeyCreatedAt || existingAgent?.createdAt,
          message:
            'You already have an API key. Send { "regenerate": true } to create a new one (this will invalidate your current key).',
        });
      }

      // Regenerate: deactivate old agent record and clean up its address index
      const oldAgentRecord = await getKV<ApiKeyAgentRecord>(
        `${AGENT_KEY_PREFIX}${member.apiKeyAgentId}`
      );
      if (oldAgentRecord) {
        await setKV(`${AGENT_KEY_PREFIX}${member.apiKeyAgentId}`, {
          ...oldAgentRecord,
          isActive: false,
          deactivatedAt: Date.now(),
        });
        // Clean up address index so it can be re-pointed to the new agentId
        if (oldAgentRecord.address) {
          await deleteKV(`agent-by-address:${oldAgentRecord.address.toLowerCase()}`);
        }
      }
    }

    // ------------------------------------------------------------------
    // Derive agent type from how the caller authenticated (B)
    // ------------------------------------------------------------------
    const agentType: "web-member" | "api-agent" =
      caller.type === "farcaster" ? "web-member" : "api-agent";

    // ------------------------------------------------------------------
    // Generate new agent record + key
    // ------------------------------------------------------------------
    const newAgentId = generateWebMemberAgentId();
    const newApiKey = generateNlkApiKey();
    // Prefix = "nlk_" + first 6 hex chars of key body (positions 4–9)
    const apiKeyPrefix = `nlk_${newApiKey.slice(4, 10)}`;

    const displayName =
      member.displayName ||
      member.farcasterUsername ||
      member.username ||
      member.ensSubname ||
      `Member #${member.memberId}`;

    // Full key intentionally NOT stored in agent record — only in api-key-lookup.
    // apiKey field is omitted entirely (it is optional on RegisteredAgent since C20).
    const newAgentRecord: ApiKeyAgentRecord = {
      id: newAgentId,
      name: displayName,
      fid: member.fid,
      address: member.address,
      memberId: member.memberId,
      isActive: true,
      createdAt: Date.now(),
      type: agentType,
      apiKeyPrefix,
      permissions: ["library:write", "stacks:create", "stacks:write", "stacks:delete"],
    };

    await setKV(`${AGENT_KEY_PREFIX}${newAgentId}`, newAgentRecord);
    await setKV(`api-key-lookup:${newApiKey}`, newAgentId);

    // Address index
    if (member.address) {
      await setKV(`agent-by-address:${member.address.toLowerCase()}`, newAgentId);
    }

    // Add to agents registry
    await atomicArrayUpdate<string, null>(AGENTS_REGISTRY_KEY, (current) => {
      const arr = current || [];
      if (!arr.includes(newAgentId)) arr.push(newAgentId);
      return { updated: arr, result: null };
    });

    // ------------------------------------------------------------------
    // Atomic member entry update — MUST succeed. Roll back on failure. (C)
    // ------------------------------------------------------------------
    const updateResult = await updateMemberAtomically(
      (reg: MemberRegistry) => reg.members.find((m) => m.memberId === member.memberId),
      (m: MemberEntry) => {
        m.apiKeyAgentId = newAgentId;
        m.apiKeyCreatedAt = Date.now();
        return { memberId: m.memberId };
      }
    );

    if (!updateResult.success) {
      // Roll back all created records so we don't orphan them
      await deleteKV(`${AGENT_KEY_PREFIX}${newAgentId}`);
      await deleteKV(`api-key-lookup:${newApiKey}`);
      if (member.address) {
        await deleteKV(`agent-by-address:${member.address.toLowerCase()}`);
      }
      console.error(
        "[POST /api/v1/membership/api-key] Member update failed, rolled back:",
        updateResult.error
      );
      return corsError("Failed to complete key generation. Please try again.", 500);
    }

    console.log(
      `[POST /api/v1/membership/api-key] API key generated for member #${member.memberId} (${agentType})`
    );

    return corsResponse(
      {
        success: true,
        apiKey: newApiKey,
        agentId: newAgentId,
        memberId: member.memberId,
        warning: "Save this key now — it cannot be retrieved again after you leave this page.",
      },
      201
    );
  } catch (error) {
    console.error("[POST /api/v1/membership/api-key] Error:", error);
    return corsError("Failed to generate API key", 500);
  }
}

// =============================================================================
// DELETE — Revoke current API key (Bearer-only convenience alias)
// =============================================================================

export async function DELETE(request: NextRequest) {
  try {
    // DELETE is Bearer-only — no body parsing.
    // Farcaster/web users: use POST { action: "revoke", fid } or
    // { action: "revoke", address } instead — DELETE bodies are unreliable
    // across proxies and CDNs.
    const authHeader =
      request.headers.get("Authorization") || request.headers.get("authorization");
    if (!authHeader?.startsWith("Bearer ")) {
      return corsError(
        'DELETE requires a Bearer token. Web/Farcaster users: POST { action: "revoke", fid } or { action: "revoke", address } instead.',
        401
      );
    }

    const result = await authenticateAgent(request);
    if (isAuthError(result)) return result;

    const caller: AuthenticatedCaller = {
      type: "bearer",
      agentId: result.agentId,
      agent: result.agent,
    };

    const registry = await getMemberRegistry();
    const member = resolveCallerMember(caller, registry);
    if (!member) return notMemberResponse();

    return revokeCallerKey(member);
  } catch (error) {
    console.error("[DELETE /api/v1/membership/api-key] Error:", error);
    return corsError("Failed to revoke API key", 500);
  }
}
src/app/api/v1/partners/[id]/route.ts
/**
 * Partner Admin — Single Partner
 *
 * PATCH /api/v1/partners/:id — Toggle active status (admin only)
 * OPTIONS — CORS preflight
 *
 * Auth: x-admin-secret header
 *
 * Body: { "isActive": boolean }
 *
 * When isActive is set to false the partner's key stops working immediately —
 * import requests return 401. Existing items remain in the library.
 */

import { NextRequest } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { partners } from "@/db/schema";
import { eq } from "drizzle-orm";
import { handleOptions, corsResponse, corsError } from "@/lib/agent-auth";

function isAdmin(request: NextRequest): boolean {
  // eslint-disable-next-line @neynar/no-process-env
  const secret = process.env.ADMIN_SECRET;
  if (!secret) return false;
  const provided =
    request.headers.get("x-admin-secret") ||
    request.headers.get("X-Admin-Secret") || "";
  return provided === secret;
}

export async function OPTIONS() {
  return handleOptions();
}

export async function PATCH(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  if (!isAdmin(request)) {
    return corsError("Admin authentication required", 401);
  }

  const { id: idParam } = await params;
  const partnerId = parseInt(idParam, 10);
  if (isNaN(partnerId)) {
    return corsError("Invalid partner ID", 400);
  }

  let body: Record<string, unknown> = {};
  try {
    body = await request.json();
  } catch {
    return corsError("Invalid JSON body", 400);
  }

  if (typeof body.isActive !== "boolean") {
    return corsError("isActive (boolean) is required", 400);
  }

  try {
    // Verify partner exists
    const existing = await db
      .select({ id: partners.id, siteName: partners.siteName })
      .from(partners)
      .where(eq(partners.id, partnerId))
      .limit(1);

    if (existing.length === 0) {
      return corsError("Partner not found", 404);
    }

    // Update active status
    await db
      .update(partners)
      .set({ isActive: body.isActive })
      .where(eq(partners.id, partnerId));

    const action = body.isActive ? "activated" : "deactivated";
    console.log(
      `[PATCH /api/v1/partners/${partnerId}] Partner "${existing[0].siteName}" ${action}`
    );

    return corsResponse({
      partnerId,
      siteName: existing[0].siteName,
      isActive: body.isActive,
      message: `Partner ${action} successfully. ${
        !body.isActive
          ? "Their import key is now invalid. Existing library items are unaffected."
          : "Their import key is active again."
      }`,
    });
  } catch (error) {
    console.error(`[PATCH /api/v1/partners/${partnerId}] Error:`, error);
    return corsError("Failed to update partner", 500);
  }
}
src/app/api/v1/partners/register/route.ts
/**
 * Partner Registration API
 *
 * POST /api/v1/partners/register — Register as an import partner
 * OPTIONS — CORS preflight
 *
 * Auth: Bearer token (existing Net Library API key, nlk_...) OR Farcaster/web.
 * Caller must be an active Net Library member.
 *
 * A partner gets a unique partner key (pk_<32 hex chars>) and a dedicated stack
 * where all their imports will land. The partner key is shown once and never
 * retrievable — only a SHA-256 hash is stored.
 *
 * One partner registration per member. siteName must be globally unique.
 */

import { NextRequest } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { kv, partners } from "@/db/schema";
import { eq, or } from "drizzle-orm";
import { keccak256, encodePacked } from "viem";
import {
  authenticateCaller,
  resolveCallerMember,
  getMemberRegistry,
  handleOptions,
  corsResponse,
  corsError,
} from "@/lib/agent-auth";
import type { Stack } from "@/features/app/types";

// KV keys — must match stacks/write/route.ts exactly
const STACK_PREFIX = "stack:";
const STACK_ITEMS_PREFIX = "stack-items:";
const USER_STACKS_PREFIX = "user-stacks:";
const STACKS_REGISTRY_KEY = "stacks-registry";

// Validate siteName: 3-100 chars, alphanumeric + dots + hyphens only
const SITE_NAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9.\-]{1,98}[a-zA-Z0-9]$|^[a-zA-Z0-9]{3,100}$/;

function validateSiteName(name: string): string | null {
  if (!name || typeof name !== "string") return "siteName is required";
  const trimmed = name.trim();
  if (trimmed.length < 3) return "siteName must be at least 3 characters";
  if (trimmed.length > 100) return "siteName must be 100 characters or less";
  if (!SITE_NAME_RE.test(trimmed)) {
    return "siteName may only contain letters, numbers, dots, and hyphens";
  }
  return null;
}

/** Generate a raw partner key: pk_ + 32 random hex chars (16 bytes) */
function generatePartnerKey(): string {
  const bytes = new Uint8Array(16);
  crypto.getRandomValues(bytes);
  const hex = Array.from(bytes)
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
  return `pk_${hex}`;
}

/** SHA-256 hash of a string, returned as lowercase hex */
async function sha256Hex(input: string): Promise<string> {
  const data = new TextEncoder().encode(input);
  const hashBuffer = await crypto.subtle.digest("SHA-256", data);
  return Array.from(new Uint8Array(hashBuffer))
    .map((b) => b.toString(16).padStart(2, "0"))
    .join("");
}

/** Generate unique stack ID — mirrors stacks/write/route.ts exactly */
function generateStackId(owner: string, name: string): string {
  const hash = keccak256(
    encodePacked(
      ["address", "string", "uint256"],
      [owner as `0x${string}`, name, BigInt(Date.now())]
    )
  );
  return hash.slice(0, 18);
}

/** KV upsert helper */
async function setKVRaw(key: string, value: unknown): Promise<void> {
  const str = typeof value === "string" ? value : JSON.stringify(value);
  await db
    .insert(kv)
    .values({ key, value: str })
    .onConflictDoUpdate({ target: kv.key, set: { value: str } });
}

/** KV read helper */
async function getKVRaw<T>(key: string): Promise<T | null> {
  const rows = await db.select().from(kv).where(eq(kv.key, key)).limit(1);
  if (!rows[0]?.value) return null;
  try { return JSON.parse(rows[0].value) as T; } catch { return rows[0].value as T; }
}

/**
 * Create a partner stack directly in KV — no HTTP self-call.
 * Stack is created pre-unlocked so it can hold unlimited imports.
 * Mirrors the logic in POST /api/v1/stacks/write exactly.
 */
async function createPartnerStackInternal(
  ownerAddress: string,
  ownerFid: number | undefined,
  ownerUsername: string | undefined,
  siteName: string
): Promise<string> {
  const owner = ownerAddress.toLowerCase();
  const stackId = generateStackId(owner, siteName);

  const stack: Stack = {
    id: stackId,
    name: siteName,
    description: `Content stored via ${siteName} and imported to Net Library by their users.`,
    owner,
    ownerFid,
    ownerUsername,
    createdAt: Date.now(),
    // Pre-unlock so the stack can hold unlimited partner imports
    unlocked: true,
    unlockedAt: Date.now(),
    itemCount: 0,
    isPrivate: false,
  };

  // Persist stack object
  await setKVRaw(`${STACK_PREFIX}${stackId}`, stack);

  // Initialise empty items array
  await setKVRaw(`${STACK_ITEMS_PREFIX}${stackId}`, []);

  // Add to owner's stack list
  const userStacks = (await getKVRaw<string[]>(`${USER_STACKS_PREFIX}${owner}`)) || [];
  if (!userStacks.includes(stackId)) {
    userStacks.push(stackId);
    await setKVRaw(`${USER_STACKS_PREFIX}${owner}`, userStacks);
  }

  // Add to global registry
  const allStacks = (await getKVRaw<string[]>(STACKS_REGISTRY_KEY)) || [];
  if (!allStacks.includes(stackId)) {
    allStacks.push(stackId);
    await setKVRaw(STACKS_REGISTRY_KEY, allStacks);
  }

  return stackId;
}

export async function OPTIONS() {
  return handleOptions();
}

export async function POST(request: NextRequest) {
  try {
    // 1. Parse body
    let body: Record<string, unknown> = {};
    try {
      body = await request.json();
    } catch {
      // empty body
    }

    // 2. Authenticate
    const caller = await authenticateCaller(request, body);
    if (caller instanceof Response) return caller;

    // 3. Must be a member
    const registry = await getMemberRegistry();
    const member = resolveCallerMember(caller, registry);
    if (!member) {
      return corsError("Must be a Net Library member to register as a partner", 403);
    }

    // 4. Validate siteName
    const siteName = typeof body.siteName === "string" ? body.siteName.trim() : "";
    const siteUrl = typeof body.siteUrl === "string" ? body.siteUrl.trim() : null;
    const nameError = validateSiteName(siteName);
    if (nameError) {
      return corsError(nameError, 400);
    }

    // 5. Check for conflicts (member already registered, or siteName taken)
    const existing = await db
      .select({ id: partners.id, memberId: partners.memberId, siteName: partners.siteName })
      .from(partners)
      .where(
        or(
          eq(partners.memberId, member.memberId),
          eq(partners.siteName, siteName)
        )
      );

    for (const row of existing) {
      if (row.memberId === member.memberId) {
        return corsError(
          "This member already has a partner registration. Each member may only register one partner.",
          409
        );
      }
      if (row.siteName === siteName) {
        return corsError(`The site name "${siteName}" is already registered by another partner.`, 409);
      }
    }

    // 6. Create the partner stack directly in KV (no HTTP self-call)
    const ownerAddress = member.address || "0x0000000000000000000000000000000000000000";
    const ownerUsername =
      member.farcasterUsername ?? member.username ?? member.ensSubname;

    const stackId = await createPartnerStackInternal(
      ownerAddress,
      member.fid,
      ownerUsername,
      siteName
    );

    // 7. Generate partner key + hash
    const rawKey = generatePartnerKey();
    const keyHash = await sha256Hex(rawKey);

    // 8. Insert into DB
    const [inserted] = await db
      .insert(partners)
      .values({
        memberId: member.memberId,
        siteName,
        siteUrl: siteUrl || null,
        partnerKeyHash: keyHash,
        stackId,
        isActive: true,
        totalImports: 0,
      })
      .returning({ id: partners.id });

    console.log(
      `[POST /api/v1/partners/register] Partner registered: member #${member.memberId} → "${siteName}" (id=${inserted.id}, stack=${stackId})`
    );

    // 9. Return — raw key shown ONCE, never again
    return corsResponse(
      {
        partnerId: inserted.id,
        partnerKey: rawKey,
        stackId,
        siteName,
        message:
          "Partner registered. Use your partner key to import content. Save this key now — it cannot be retrieved again.",
      },
      201
    );
  } catch (error) {
    console.error("[POST /api/v1/partners/register] Error:", error);
    return corsError("Failed to register partner", 500);
  }
}
src/app/api/v1/partners/route.ts
/**
 * Partners Admin API
 *
 * GET /api/v1/partners — List all registered partners (admin only)
 * OPTIONS — CORS preflight
 *
 * Auth: x-admin-secret header (matches ADMIN_SECRET env var)
 */

import { NextRequest } from "next/server";
import { db } from "@/neynar-db-sdk/src/db";
import { partners } from "@/db/schema";
import { handleOptions, corsResponse, corsError } from "@/lib/agent-auth";

function isAdmin(request: NextRequest): boolean {
  // eslint-disable-next-line @neynar/no-process-env
  const secret = process.env.ADMIN_SECRET;
  if (!secret) return false;
  const provided =
    request.headers.get("x-admin-secret") ||
    request.headers.get("X-Admin-Secret") || "";
  return provided === secret;
}

export async function OPTIONS() {
  return handleOptions();
}

export async function GET(request: NextRequest) {
  if (!isAdmin(request)) {
    return corsError("Admin authentication required", 401);
  }

  try {
    const rows = await db
      .select({
        id: partners.id,
        memberId: partners.memberId,
        siteName: partners.siteName,
        siteUrl: partners.siteUrl,
        stackId: partners.stackId,
        isActive: partners.isActive,
        createdAt: partners.createdAt,
        totalImports: partners.totalImports,
      })
      .from(partners)
      .orderBy(partners.createdAt);

    return corsResponse({
      partners: rows.map((r) => ({
        partnerId: r.id,
        memberId: r.memberId,
        siteName: r.siteName,
        siteUrl: r.siteUrl,
        stackId: r.stackId,
        totalImports: r.totalImports,
        isActive: r.isActive,
        createdAt: r.createdAt,
      })),
      total: rows.length,
    });
  } catch (error) {
    console.error("[GET /api/v1/partners] Error:", error);
    return corsError("Failed to fetch partners", 500);
  }
}
src/app/api/v1/search/route.ts
/**
 * Search API
 *
 * GET /api/v1/search — Search across library items and stacks
 * OPTIONS — CORS preflight
 */

import { NextRequest } from "next/server";
import {
  getKV,
  handleOptions,
  corsResponse,
  corsError,
} from "@/lib/agent-auth";
import type { Stack } from "@/features/app/types";
import type { DiscoveryEntry } from "@/lib/net-protocol";

// KV keys
const DISCOVERY_KEY = "discovery-index";
const STACKS_REGISTRY_KEY = "stacks-registry";
const STACK_PREFIX = "stack:";

// Shape item for search results
interface SearchItem {
  title: string;
  author: string;
  categories: string[];
  contentKey: string;
  mediaType: string | null;
  cdnUrl: string | null;
  storageType: string;
  operator: string;
  uploadDate: number;
  uploader: {
    username: string | null;
    pfpUrl: string | null;
    address: string | null;
    fid: number | null;
  };
  isSocialReceipt: boolean;
  socialPlatform: string | null;
  originalUrl: string | null;
  // Relevance score for sorting
  relevance: number;
}

function shapeItem(entry: DiscoveryEntry, relevance: number): SearchItem {
  return {
    title: entry.title,
    author: entry.author,
    categories: entry.categories || [],
    contentKey: entry.contentKey,
    mediaType: entry.mediaType || null,
    cdnUrl: entry.cdnUrl || null,
    storageType: entry.storageType,
    operator: entry.operator,
    uploadDate: entry.uploadedAt,
    uploader: {
      username: entry.uploaderUsername || entry.uploaderStoredUsername || null,
      pfpUrl: entry.uploaderPfpUrl || null,
      address: entry.uploaderAddress || entry.operator || null,
      fid: entry.uploaderFid || null,
    },
    isSocialReceipt: entry.isSocialReceipt || false,
    socialPlatform: entry.socialPlatform || null,
    originalUrl: entry.originalUrl || null,
    relevance,
  };
}

// Shape stack for search results
interface SearchStack {
  id: string;
  name: string;
  description: string | null;
  owner: string;
  ownerUsername: string | null;
  ownerPfpUrl: string | null;
  createdAt: number;
  itemCount: number;
  upvotes: number;
  views: number;
  relevance: number;
}

function shapeStack(stack: Stack, relevance: number): SearchStack {
  return {
    id: stack.id,
    name: stack.name,
    description: stack.description || null,
    owner: stack.owner,
    ownerUsername: stack.ownerUsername || null,
    ownerPfpUrl: stack.ownerPfpUrl || null,
    createdAt: stack.createdAt,
    itemCount: stack.itemCount || 0,
    upvotes: stack.upvotes || 0,
    views: stack.views || 0,
    relevance,
  };
}

/**
 * Calculate relevance score for text matching
 * Exact match > starts with > contains
 */
function calculateRelevance(text: string, query: string): number {
  const lowerText = text.toLowerCase();
  const lowerQuery = query.toLowerCase();

  if (lowerText === lowerQuery) return 100; // Exact match
  if (lowerText.startsWith(lowerQuery)) return 75; // Starts with
  if (lowerText.includes(lowerQuery)) return 50; // Contains

  return 0;
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/v1/search — Search across library items and stacks
 *
 * Query params:
 * - q (search query)
 * - category (filter by category)
 * - author (filter by author)
 * - mediaType (filter by media type)
 * - limit (max 50)
 *
 * At least one of q, category, or author required.
 * Results sorted by relevance: exact title > starts with > contains
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);

    // Parse query parameters
    const query = searchParams.get("q")?.trim() || "";
    const categoryFilter = searchParams.get("category")?.toLowerCase().trim() || null;
    const authorFilter = searchParams.get("author")?.toLowerCase().trim() || null;
    const mediaTypeFilter = searchParams.get("mediaType")?.toLowerCase().trim() || null;
    const limit = Math.min(50, Math.max(1, parseInt(searchParams.get("limit") || "20", 10)));

    // Require at least one search criterion
    if (!query && !categoryFilter && !authorFilter) {
      return corsError("At least one of 'q', 'category', or 'author' is required", 400);
    }

    const queryLower = query.toLowerCase();

    // Search items — handle both storage shapes: flat DiscoveryEntry[] OR wrapped { entries, lastUpdated }
    const rawDiscovery = await getKV<DiscoveryEntry[] | { entries: DiscoveryEntry[]; lastUpdated: number }>(DISCOVERY_KEY);
    const entries: DiscoveryEntry[] = Array.isArray(rawDiscovery) ? rawDiscovery : (rawDiscovery?.entries || []);

    const matchedItems: SearchItem[] = [];

    for (const entry of entries) {
      // Skip hidden entries
      if (entry.hidden) continue;

      // Apply category filter
      if (categoryFilter && !entry.categories?.some(c => c.toLowerCase() === categoryFilter)) {
        continue;
      }

      // Apply author filter
      if (authorFilter && !entry.author?.toLowerCase().includes(authorFilter)) {
        continue;
      }

      // Apply media type filter
      if (mediaTypeFilter && entry.mediaType?.toLowerCase() !== mediaTypeFilter) {
        continue;
      }

      // Calculate relevance if we have a query
      let relevance = 50; // Default score when no query (just filtering)
      if (query) {
        const titleRelevance = calculateRelevance(entry.title || "", queryLower);
        const authorRelevance = calculateRelevance(entry.author || "", queryLower) * 0.8; // Author matches worth slightly less
        const categoryRelevance = entry.categories?.some(c => c.toLowerCase().includes(queryLower)) ? 30 : 0;

        relevance = Math.max(titleRelevance, authorRelevance, categoryRelevance);

        // Skip if no match found
        if (relevance === 0) continue;
      }

      matchedItems.push(shapeItem(entry, relevance));
    }

    // Sort by relevance (highest first), then by recent
    matchedItems.sort((a, b) => {
      if (b.relevance !== a.relevance) return b.relevance - a.relevance;
      return b.uploadDate - a.uploadDate;
    });

    // Search stacks (only if we have a text query)
    const matchedStacks: SearchStack[] = [];

    if (query) {
      const stackIds = await getKV<string[]>(STACKS_REGISTRY_KEY) || [];
      const stackPromises = stackIds.map((id) => getKV<Stack>(`${STACK_PREFIX}${id}`));
      const stackResults = await Promise.all(stackPromises);

      for (const stack of stackResults) {
        if (!stack || stack.isPrivate) continue;

        const nameRelevance = calculateRelevance(stack.name || "", queryLower);
        const descRelevance = calculateRelevance(stack.description || "", queryLower) * 0.6;
        const relevance = Math.max(nameRelevance, descRelevance);

        if (relevance > 0) {
          matchedStacks.push(shapeStack(stack, relevance));
        }
      }

      // Sort stacks by relevance
      matchedStacks.sort((a, b) => {
        if (b.relevance !== a.relevance) return b.relevance - a.relevance;
        return b.createdAt - a.createdAt;
      });
    }

    // Apply limits
    const items = matchedItems.slice(0, limit);
    const stacks = matchedStacks.slice(0, limit);

    return corsResponse({
      success: true,
      query: query || null,
      filters: {
        category: categoryFilter,
        author: authorFilter,
        mediaType: mediaTypeFilter,
      },
      items,
      stacks,
      totalResults: items.length + stacks.length,
    });
  } catch (error) {
    console.error("[GET /api/v1/search] Error:", error);
    return corsError("Search failed", 500);
  }
}
src/app/api/v1/stacks/[stackId]/route.ts
/**
 * Single Stack API
 *
 * GET /api/v1/stacks/[stackId] — Fetch a single stack with items
 * OPTIONS — CORS preflight
 */

import { NextRequest } from "next/server";
import {
  getKV,
  handleOptions,
  corsResponse,
  corsError,
} from "@/lib/agent-auth";
import type { Stack, StackItem } from "@/features/app/types";
import type { DiscoveryEntry } from "@/lib/net-protocol";

// KV keys
const STACK_PREFIX = "stack:";
const STACK_ITEMS_PREFIX = "stack-items:";
const DISCOVERY_KEY = "discovery-index";

// Shape stack for public API response
interface PublicStack {
  id: string;
  name: string;
  description: string | null;
  owner: string;
  ownerUsername: string | null;
  ownerPfpUrl: string | null;
  createdAt: number;
  itemCount: number;
  upvotes: number;
  views: number;
  // Filesystem fields (only present when isFileSystem is true)
  isFileSystem?: boolean;
  fileCount?: number;
  totalSize?: number;
  sourceUrl?: string;
  sourceType?: string;
  sourceCommit?: string;
}

function shapeStack(stack: Stack): PublicStack {
  const base: PublicStack = {
    id: stack.id,
    name: stack.name,
    description: stack.description || null,
    owner: stack.owner,
    ownerUsername: stack.ownerUsername || null,
    ownerPfpUrl: stack.ownerPfpUrl || null,
    createdAt: stack.createdAt,
    itemCount: stack.itemCount || 0,
    upvotes: stack.upvotes || 0,
    views: stack.views || 0,
  };

  if (stack.isFileSystem) {
    base.isFileSystem = true;
    base.fileCount = stack.fileCount ?? 0;
    base.totalSize = stack.totalSize ?? 0;
    if (stack.sourceUrl) base.sourceUrl = stack.sourceUrl;
    if (stack.sourceType) base.sourceType = stack.sourceType;
    if (stack.sourceCommit) base.sourceCommit = stack.sourceCommit;
  }

  return base;
}

// Shape book details from discovery entry
interface ItemBook {
  title: string;
  author: string;
  mediaType: string | null;
  cdnUrl: string | null;
  categories: string[];
  isSocialReceipt: boolean;
  socialPlatform: string | null;
  originalUrl: string | null;
}

function shapeBookFromEntry(entry: DiscoveryEntry): ItemBook {
  return {
    title: entry.title,
    author: entry.author,
    mediaType: entry.mediaType || null,
    cdnUrl: entry.cdnUrl || null,
    categories: entry.categories || [],
    isSocialReceipt: entry.isSocialReceipt || false,
    socialPlatform: entry.socialPlatform || null,
    originalUrl: entry.originalUrl || null,
  };
}

// Shape stack item for response
interface PublicStackItem {
  contentKey: string;
  addedAt: number;
  addedBy: string;
  book: ItemBook | null;
  // Filesystem fields (only present when parent stack is a filesystem stack)
  path?: string;
  fileName?: string;
  fileSize?: number;
  mimeType?: string;
  isDirectory?: boolean;
  parentPath?: string;
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/v1/stacks/[stackId] — Fetch a single stack with items
 *
 * Returns stack details and all visible items
 * Returns 404 for private stacks (no auth in this version)
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ stackId: string }> }
) {
  try {
    const { stackId } = await params;

    // Fetch the stack
    const stack = await getKV<Stack>(`${STACK_PREFIX}${stackId}`);

    // Return 404 if stack doesn't exist or has been moderation-hidden
    if (!stack || stack.hidden) {
      return corsError("Stack not found", 404);
    }

    // Return 403 for private stacks (auth required but not supported in public read API)
    if (stack.isPrivate) {
      return corsError("This stack is private", 403);
    }

    // Fetch stack items
    const allStackItems = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${stackId}`) || [];

    // Fetch discovery index to look up book details
    const discoveryEntries = await getKV<DiscoveryEntry[]>(DISCOVERY_KEY) || [];

    // Create a map of contentKey -> entry for quick lookup (only non-hidden entries)
    const visibleEntryMap = new Map<string, DiscoveryEntry>();
    for (const entry of discoveryEntries) {
      if (!entry.hidden) {
        visibleEntryMap.set(entry.contentKey, entry);
      }
    }

    // Filter items:
    // - Filesystem stacks: all items are shown (files don't have discovery entries)
    // - Regular stacks: only items that exist in discovery and are not hidden
    const stackItems = stack.isFileSystem
      ? allStackItems
      : allStackItems.filter(item => visibleEntryMap.has(item.contentKey));

    // Shape items with book details (and filesystem metadata if applicable)
    const items: PublicStackItem[] = stackItems.map((item) => {
      const entry = visibleEntryMap.get(item.contentKey);
      const shaped: PublicStackItem = {
        contentKey: item.contentKey,
        addedAt: item.addedAt,
        addedBy: item.addedBy,
        book: entry ? shapeBookFromEntry(entry) : null,
      };

      // Include filesystem metadata when present
      if (item.path !== undefined) shaped.path = item.path;
      if (item.fileName !== undefined) shaped.fileName = item.fileName;
      if (item.fileSize !== undefined) shaped.fileSize = item.fileSize;
      if (item.mimeType !== undefined) shaped.mimeType = item.mimeType;
      if (item.isDirectory !== undefined) shaped.isDirectory = item.isDirectory;
      if (item.parentPath !== undefined) shaped.parentPath = item.parentPath;

      return shaped;
    });

    return corsResponse({
      success: true,
      stack: shapeStack(stack),
      items,
      visibleItemCount: items.length,
    });
  } catch (error) {
    console.error("[GET /api/v1/stacks/[stackId]] Error:", error);
    return corsError("Failed to fetch stack", 500);
  }
}
src/app/api/v1/stacks/route.ts
/**
 * Stacks Browse API
 *
 * GET /api/v1/stacks — Browse public stacks with pagination
 * OPTIONS — CORS preflight
 */

import { NextRequest } from "next/server";
import {
  getKV,
  handleOptions,
  corsResponse,
  corsError,
} from "@/lib/agent-auth";
import type { Stack, StackItem } from "@/features/app/types";
import type { DiscoveryEntry } from "@/lib/net-protocol";

// KV keys
const STACKS_REGISTRY_KEY = "stacks-registry";
const STACK_PREFIX = "stack:";
const STACK_ITEMS_PREFIX = "stack-items:";
const DISCOVERY_KEY = "discovery-index";

// Shape stack for public API response
interface PublicStack {
  id: string;
  name: string;
  description: string | null;
  owner: string;
  ownerUsername: string | null;
  ownerPfpUrl: string | null;
  createdAt: number;
  itemCount: number;
  visibleItemCount: number;
  upvotes: number;
  views: number;
  previewCovers: string[];
}

function shapeStack(stack: Stack, visibleItemCount?: number): PublicStack {
  return {
    id: stack.id,
    name: stack.name,
    description: stack.description || null,
    owner: stack.owner,
    ownerUsername: stack.ownerUsername || null,
    ownerPfpUrl: stack.ownerPfpUrl || null,
    createdAt: stack.createdAt,
    itemCount: stack.itemCount || 0,
    visibleItemCount: visibleItemCount ?? stack.itemCount ?? 0,
    upvotes: stack.upvotes || 0,
    views: stack.views || 0,
    previewCovers: stack.previewCovers || [],
  };
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/v1/stacks — Browse public stacks
 *
 * Query params:
 * - page (default 1)
 * - limit (default 20, max 50)
 * - owner (filter by address)
 * - sort (newest/oldest/name/popular)
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);

    // Parse query parameters
    const page = Math.max(1, parseInt(searchParams.get("page") || "1", 10));
    const limit = Math.min(50, Math.max(1, parseInt(searchParams.get("limit") || searchParams.get("pageSize") || "20", 10)));
    const sortParam = searchParams.get("sort") || searchParams.get("sortBy") || "newest";
    const ownerFilter = searchParams.get("owner")?.toLowerCase().trim() || null;

    // Fetch stacks registry to get all stack IDs
    const stackIds = await getKV<string[]>(STACKS_REGISTRY_KEY);

    if (!stackIds || stackIds.length === 0) {
      return corsResponse({
        success: true,
        stacks: [],
        pagination: {
          page,
          limit,
          total: 0,
          totalPages: 0,
          hasMore: false,
        },
      });
    }

    // Fetch all stacks in parallel
    const stackPromises = stackIds.map((id) => getKV<Stack>(`${STACK_PREFIX}${id}`));
    const stackResults = await Promise.all(stackPromises);

    // Filter out null results, hidden stacks, and private stacks.
    // stack.hidden is set via POST /api/admin/hide-stack — no code deploy needed.
    let stacks = stackResults.filter((stack): stack is Stack => {
      if (!stack) return false;
      // Always exclude moderation-hidden stacks from public listings
      if (stack.hidden) return false;
      // If owner filter specified, show all their non-hidden stacks (including private)
      if (ownerFilter && stack.owner?.toLowerCase() === ownerFilter) {
        return true;
      }
      // Otherwise only show public stacks
      return !stack.isPrivate;
    });

    // Apply owner filter
    if (ownerFilter) {
      stacks = stacks.filter((stack) =>
        stack.owner?.toLowerCase() === ownerFilter
      );
    }

    // Sort stacks
    switch (sortParam) {
      case "oldest":
        stacks.sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0));
        break;
      case "name":
        stacks.sort((a, b) => (a.name || "").localeCompare(b.name || ""));
        break;
      case "popular":
        stacks.sort((a, b) => (b.upvotes || 0) - (a.upvotes || 0));
        break;
      case "newest":
      default:
        stacks.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0));
        break;
    }

    // Calculate pagination
    const total = stacks.length;
    const totalPages = Math.ceil(total / limit);
    const startIndex = (page - 1) * limit;
    const paginatedStacks = stacks.slice(startIndex, startIndex + limit);
    const hasMore = page < totalPages;

    // Fetch discovery index to filter hidden items
    const discoveryEntries = await getKV<DiscoveryEntry[]>(DISCOVERY_KEY) || [];
    const visibleContentKeys = new Set(
      discoveryEntries
        .filter(entry => !entry.hidden)
        .map(entry => entry.contentKey)
    );

    // Calculate visible item counts for each stack
    const shapedStacks = await Promise.all(
      paginatedStacks.map(async (stack) => {
        const items = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${stack.id}`) || [];
        const visibleCount = items.filter(item => visibleContentKeys.has(item.contentKey)).length;
        return shapeStack(stack, visibleCount);
      })
    );

    return corsResponse({
      success: true,
      stacks: shapedStacks,
      pagination: {
        page,
        limit,
        total,
        totalPages,
        hasMore,
      },
    });
  } catch (error) {
    console.error("[GET /api/v1/stacks] Error:", error);
    return corsError("Failed to fetch stacks", 500);
  }
}
src/app/api/v1/stacks/write/route.ts
 
/**
 * Stacks Write API
 *
 * POST /api/v1/stacks/write — Create a new stack
 * PUT /api/v1/stacks/write — Modify stack (action-based: add-item, remove-item, unlock, update-metadata)
 * OPTIONS — CORS preflight
 *
 * Auth required.
 * - Members create stacks free
 * - Non-members pay $5 USDC to create stacks
 * - Stacks have 20-item limit unless unlocked ($5 USDC)
 */

import { NextRequest } from "next/server";
import { keccak256, encodePacked } from "viem";
import {
  getKV,
  setKV,
  authenticateCaller,
  resolveCallerMember,
  hasPermission,
  handleOptions,
  corsResponse,
  corsError,
  verifyUsdcPayment,
  markTxUsed,
  getMemberRegistry,
  atomicArrayUpdate,
  PRICING,
  type AuthenticatedCaller,
  type MemberEntry,
} from "@/lib/agent-auth";
import type { Stack, StackItem } from "@/features/app/types";

// KV Keys
const STACKS_REGISTRY_KEY = "stacks-registry";
const STACK_PREFIX = "stack:";
const STACK_ITEMS_PREFIX = "stack-items:";
const USER_STACKS_PREFIX = "user-stacks:";
const ITEM_STACKS_PREFIX = "item-stacks:";

// Stack item limit for non-unlocked stacks
const STACK_ITEM_LIMIT = 20;

// Helper: Generate unique stack ID
function generateStackId(owner: string, name: string): string {
  const hash = keccak256(
    encodePacked(
      ["address", "string", "uint256"],
      [owner as `0x${string}`, name, BigInt(Date.now())]
    )
  );
  return hash.slice(0, 18); // Short ID for URLs
}

// Narrow identity type for stack ownership checks — avoids fake MemberEntry casts
interface StackOwnerIdentity {
  fid?: number;
  address?: string;
}

// Helper: Check if an identity owns a stack (by address or FID)
function canManageStack(stack: Stack, owner: StackOwnerIdentity): boolean {
  if (owner.address && stack.owner.toLowerCase() === owner.address.toLowerCase()) return true;
  if (owner.fid && stack.ownerFid === owner.fid) return true;
  return false;
}

// Helper: Build ownership identity from resolved member + caller fallback
function ownerIdentity(caller: AuthenticatedCaller, member: MemberEntry | null): StackOwnerIdentity {
  return {
    fid: member?.fid ?? caller.fid,
    address: member?.address ?? caller.address,
  };
}

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * POST /api/v1/stacks/write — Create a new stack
 *
 * Body:
 * - name (required): Stack name
 * - description (optional): Stack description
 * - isPublic (optional): Whether stack is public (default: true)
 * - isFileSystem (optional): Whether stack is a file system (default: false)
 * - items (optional): Initial content keys to add
 * - txHash (optional): Payment transaction hash (required for non-members)
 *
 * Members create free. Non-members pay $5 USDC.
 */
export async function POST(request: NextRequest) {
  try {
    // 1. Parse body (needed for Farcaster/web auth identity)
    let body: Record<string, unknown> = {};
    try {
      body = await request.json();
    } catch {
      // Body may be absent for Bearer-only callers
    }

    // 2. Authenticate caller (Bearer or Farcaster/web)
    const caller = await authenticateCaller(request, body);
    if (caller instanceof Response) return caller;

    // 3. Bearer agents must have stacks:create permission
    if (caller.type === "bearer" && caller.agent && !hasPermission(caller.agent, "stacks:create")) {
      return corsError("Insufficient permissions. Requires 'stacks:create'", 403);
    }

    // 4. Extract typed fields from body
    const name = typeof body.name === "string" ? body.name : undefined;
    const description = typeof body.description === "string" ? body.description : undefined;
    const isPublic = body.isPublic === false ? false : true;
    const isFileSystem = body.isFileSystem === true;
    const initialItems = Array.isArray(body.items) ? (body.items as unknown[]) : undefined;
    const txHash = typeof body.txHash === "string" ? body.txHash : null;

    // 5. Validate required fields
    if (!name?.trim()) {
      return corsError("Name is required", 400);
    }

    // Validate initial items if provided
    let validatedItems: string[] | undefined;
    if (initialItems !== undefined) {
      for (const item of initialItems) {
        if (typeof item !== "string") {
          return corsError("Each item must be a content key string", 400);
        }
      }
      validatedItems = initialItems as string[];
      // Enforce 20-item limit on initial creation (unlocked stacks can add more via PUT)
      if (validatedItems.length > STACK_ITEM_LIMIT) {
        return corsError(`Cannot create stack with more than ${STACK_ITEM_LIMIT} items. Unlock the stack to add more.`, 400);
      }
    }

    // 6. Check membership - members create free, non-members pay $5
    const registry = await getMemberRegistry();
    const memberEntry = resolveCallerMember(caller, registry);

    const isMember = !!memberEntry;

    // Non-members must pay
    if (!isMember) {
      if (!txHash) {
        return corsResponse({
          success: false,
          error: "Non-members must pay to create stacks",
          paymentRequired: true,
          price: PRICING.STACK_CREATION_NON_MEMBER,
          currency: "USDC",
        }, 402);
      }

      // Verify payment
      const paymentResult = await verifyUsdcPayment(txHash, PRICING.STACK_CREATION_NON_MEMBER);
      if (!paymentResult.valid) {
        return corsError(paymentResult.error || "Payment verification failed", 402);
      }

      // Mark transaction as used
      await markTxUsed(txHash, "stack-creation");
    }

    // 7. Use member's address as owner (fall back to caller.address for Farcaster path)
    const ownerAddress = (memberEntry?.address ?? (caller.type === "farcaster" ? caller.address : undefined) ?? "0x0000000000000000000000000000000000000000").toLowerCase();
    const ownerFid = memberEntry?.fid ?? (caller.type === "farcaster" ? caller.fid : undefined);
    const ownerUsername =
      memberEntry?.farcasterUsername ?? memberEntry?.username ?? memberEntry?.ensSubname;
    const ownerPfpUrl = memberEntry?.customPfpUrl ?? memberEntry?.pfpUrl;

    // 8. Generate stack ID
    const stackId = generateStackId(ownerAddress, name);

    // 9. Create stack object
    const stack: Stack = {
      id: stackId,
      name: name.trim(),
      description: description?.trim() || undefined,
      owner: ownerAddress,
      ownerFid,
      ownerUsername,
      ownerPfpUrl,
      createdAt: Date.now(),
      unlocked: false, // Starts locked (20-item limit)
      itemCount: 0,
      isPrivate: !isPublic,
      isFileSystem,
      isAgentCreated: caller.type === "bearer",
      agentId: caller.type === "bearer" ? caller.agentId : undefined,
    };

    // 10. Store the stack
    await setKV(`${STACK_PREFIX}${stackId}`, stack);

    // 11. Initialize items array
    const stackItems: StackItem[] = [];

    // If initial items were provided, add them
    if (validatedItems && validatedItems.length > 0) {
      for (const contentKey of validatedItems) {
        const newItem: StackItem = {
          contentKey,
          addedAt: Date.now(),
          addedBy: ownerAddress,
        };
        stackItems.push(newItem);

        // Update reverse index
        const itemStacks = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${contentKey}`) || [];
        if (!itemStacks.includes(stackId)) {
          itemStacks.push(stackId);
          await setKV(`${ITEM_STACKS_PREFIX}${contentKey}`, itemStacks);
        }
      }

      stack.itemCount = stackItems.length;
      await setKV(`${STACK_PREFIX}${stackId}`, stack);
    }

    // 11. Save stack items
    await setKV(`${STACK_ITEMS_PREFIX}${stackId}`, stackItems);

    // 12. Add to user's stacks
    const userStacks = await getKV<string[]>(`${USER_STACKS_PREFIX}${ownerAddress}`) || [];
    userStacks.push(stackId);
    await setKV(`${USER_STACKS_PREFIX}${ownerAddress}`, userStacks);

    // 13. Add to global registry
    const allStacks = await getKV<string[]>(STACKS_REGISTRY_KEY) || [];
    allStacks.push(stackId);
    await setKV(STACKS_REGISTRY_KEY, allStacks);

    console.log(`[POST /api/v1/stacks/write] Stack created by member #${memberEntry?.memberId ?? "non-member"} (${caller.type}): ${stackId}`);

    return corsResponse({
      success: true,
      stack: {
        id: stackId,
        name: stack.name,
        itemCount: stack.itemCount,
        unlocked: stack.unlocked,
      },
    }, 201);
  } catch (error) {
    console.error("[POST /api/v1/stacks/write] Error:", error);
    return corsError("Internal server error", 500);
  }
}

/**
 * PUT /api/v1/stacks/write — Modify a stack
 *
 * Body:
 * - stackId (required): Stack ID to modify
 * - action (required): One of "add-item", "remove-item", "unlock", "update-metadata"
 *
 * Action-specific fields:
 * - add-item: contentKey (required)
 * - remove-item: contentKey (required)
 * - unlock: txHash (required) - $5 USDC payment
 * - update-metadata: name, description, isPrivate (at least one required)
 */
export async function PUT(request: NextRequest) {
  try {
    // 1. Parse body (needed for Farcaster/web auth identity)
    let body: Record<string, unknown> = {};
    try {
      body = await request.json();
    } catch {
      // Body may be absent for Bearer-only callers
    }

    // 2. Authenticate caller (Bearer or Farcaster/web)
    const caller = await authenticateCaller(request, body);
    if (caller instanceof Response) return caller;

    // 3. Bearer agents must have stacks:write permission
    if (caller.type === "bearer" && caller.agent && !hasPermission(caller.agent, "stacks:write")) {
      return corsError("Insufficient permissions. Requires 'stacks:write'", 403);
    }

    // 4. Resolve member for ownership checks
    const registry = await getMemberRegistry();
    const memberEntry = resolveCallerMember(caller, registry);
    // Note: non-members can still manage stacks they own by address/FID — membership
    // is not required for PUT (only POST requires membership or payment).

    const stackId = typeof body.stackId === "string" ? body.stackId : null;
    const action = typeof body.action === "string" ? body.action : null;

    // 4. Validate required fields
    if (!stackId) {
      return corsError("stackId is required", 400);
    }

    const validActions = ["add-item", "remove-item", "unlock", "update-metadata", "add-fs-item"];
    if (!action || !validActions.includes(action)) {
      return corsError(`action must be one of: ${validActions.join(", ")}`, 400);
    }

    // 5. Get the stack
    const stack = await getKV<Stack>(`${STACK_PREFIX}${stackId}`);
    if (!stack) {
      return corsError("Stack not found", 404);
    }

    // 6. Check ownership or admin
    const isAdmin = caller.type === "bearer" && caller.agent && hasPermission(caller.agent, "admin");
    if (!isAdmin && !canManageStack(stack, ownerIdentity(caller, memberEntry))) {
      return corsError("Not authorized to modify this stack", 403);
    }

    // 7. Handle action
    switch (action) {
      case "add-item": {
        const contentKey = typeof body.contentKey === "string" ? body.contentKey : null;
        if (!contentKey) {
          return corsError("contentKey is required for add-item action", 400);
        }

        // Use atomic operation to prevent race conditions
        const atomicResult = await atomicArrayUpdate<StackItem, { error?: string; itemCount?: number; duplicate?: boolean; limitExceeded?: boolean }>(
          `${STACK_ITEMS_PREFIX}${stackId}`,
          (stackItems) => {
            // Check if already in stack
            if (stackItems.some(item => item.contentKey === contentKey)) {
              return { abort: true, result: { duplicate: true } };
            }

            // Check 20-item limit if stack is not unlocked
            if (!stack.unlocked && stackItems.length >= STACK_ITEM_LIMIT) {
              return { abort: true, result: { limitExceeded: true } };
            }

            // Add item
            const newItem: StackItem = {
              contentKey,
              addedAt: Date.now(),
              addedBy: (memberEntry?.address ?? caller.address)?.toLowerCase() || String(memberEntry?.memberId ?? "unknown"),
            };

            return {
              updated: [...stackItems, newItem],
              result: { itemCount: stackItems.length + 1 }
            };
          }
        );

        if (!atomicResult.success) {
          console.error("[PUT /api/v1/stacks/write] Atomic add-item failed:", atomicResult.error);
          return corsError(atomicResult.error || "Failed to add item", 500);
        }

        if (atomicResult.result?.duplicate) {
          return corsError("Item already in stack", 409);
        }

        if (atomicResult.result?.limitExceeded) {
          return corsResponse({
            success: false,
            error: `Stack has reached the ${STACK_ITEM_LIMIT}-item limit. Unlock the stack to add more.`,
            unlockRequired: true,
            price: PRICING.STACK_UNLOCK,
            currency: "USDC",
          }, 402); // Changed from 403 to 402 (Payment Required)
        }

        // Update stack item count
        stack.itemCount = atomicResult.result?.itemCount || 0;
        await setKV(`${STACK_PREFIX}${stackId}`, stack);

        // Update reverse index
        const itemStacks = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${contentKey}`) || [];
        if (!itemStacks.includes(stackId)) {
          itemStacks.push(stackId);
          await setKV(`${ITEM_STACKS_PREFIX}${contentKey}`, itemStacks);
        }

        console.log(`[PUT /api/v1/stacks/write] Item ${contentKey} added to stack ${stackId}`);

        return corsResponse({
          success: true,
          action: "add-item",
          stackId,
          contentKey,
          itemCount: stack.itemCount,
        });
      }

      case "remove-item": {
        const contentKey = typeof body.contentKey === "string" ? body.contentKey : null;
        if (!contentKey) {
          return corsError("contentKey is required for remove-item action", 400);
        }

        // Use atomic operation to prevent race conditions
        const atomicResult = await atomicArrayUpdate<StackItem, { notFound?: boolean; itemCount?: number }>(
          `${STACK_ITEMS_PREFIX}${stackId}`,
          (stackItems) => {
            const itemIndex = stackItems.findIndex(item => item.contentKey === contentKey);

            if (itemIndex === -1) {
              return { abort: true, result: { notFound: true } };
            }

            // Remove item
            const updated = [...stackItems];
            updated.splice(itemIndex, 1);

            return {
              updated,
              result: { itemCount: updated.length }
            };
          }
        );

        if (!atomicResult.success) {
          console.error("[PUT /api/v1/stacks/write] Atomic remove-item failed:", atomicResult.error);
          return corsError(atomicResult.error || "Failed to remove item", 500);
        }

        if (atomicResult.result?.notFound) {
          return corsError("Item not found in stack", 404);
        }

        // Update stack item count
        stack.itemCount = atomicResult.result?.itemCount || 0;
        await setKV(`${STACK_PREFIX}${stackId}`, stack);

        // Update reverse index
        const itemStacks = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${contentKey}`) || [];
        const updatedItemStacks = itemStacks.filter(id => id !== stackId);
        await setKV(`${ITEM_STACKS_PREFIX}${contentKey}`, updatedItemStacks);

        console.log(`[PUT /api/v1/stacks/write] Item ${contentKey} removed from stack ${stackId}`);

        return corsResponse({
          success: true,
          action: "remove-item",
          stackId,
          contentKey,
          itemCount: stack.itemCount,
        });
      }

      case "unlock": {
        // Check if already unlocked
        if (stack.unlocked) {
          return corsResponse({
            success: true,
            message: "Stack is already unlocked",
            stackId,
            unlocked: true,
          });
        }

        const txHash = typeof body.txHash === "string" ? body.txHash : null;
        if (!txHash) {
          return corsResponse({
            success: false,
            error: "txHash is required for unlock action",
            price: PRICING.STACK_UNLOCK,
            currency: "USDC",
          }, 402);
        }

        // Verify payment
        const paymentResult = await verifyUsdcPayment(txHash, PRICING.STACK_UNLOCK);
        if (!paymentResult.valid) {
          return corsError(paymentResult.error || "Payment verification failed", 402);
        }

        // Mark transaction as used
        await markTxUsed(txHash, "stack-unlock");

        // Unlock the stack
        stack.unlocked = true;
        stack.unlockedAt = Date.now();
        stack.unlockTxHash = txHash;
        await setKV(`${STACK_PREFIX}${stackId}`, stack);

        console.log(`[PUT /api/v1/stacks/write] Stack ${stackId} unlocked`);

        return corsResponse({
          success: true,
          action: "unlock",
          stackId,
          unlocked: true,
        });
      }

      case "update-metadata": {
        const name = typeof body.name === "string" ? body.name : undefined;
        const description = typeof body.description === "string" ? body.description : undefined;
        const isPrivate = typeof body.isPrivate === "boolean" ? body.isPrivate : undefined;

        // At least one field must be provided
        if (name === undefined && description === undefined && isPrivate === undefined) {
          return corsError("At least one of name, description, or isPrivate must be provided", 400);
        }

        // Update fields
        if (name?.trim()) {
          stack.name = name.trim();
        }
        if (description !== undefined) {
          stack.description = description.trim() || undefined;
        }
        if (isPrivate !== undefined) {
          stack.isPrivate = isPrivate;
        }

        await setKV(`${STACK_PREFIX}${stackId}`, stack);

        console.log(`[PUT /api/v1/stacks/write] Stack ${stackId} metadata updated`);

        return corsResponse({
          success: true,
          action: "update-metadata",
          stackId,
          stack: {
            id: stackId,
            name: stack.name,
            description: stack.description,
            isPrivate: stack.isPrivate,
          },
        });
      }

      case "add-fs-item": {
        // add-fs-item is only valid for filesystem stacks
        if (!stack.isFileSystem) {
          return corsError("add-fs-item is only valid for filesystem stacks", 400);
        }

        const contentKey = typeof body.contentKey === "string" ? body.contentKey : null;
        const path = typeof body.path === "string" ? body.path : null;
        const fileName = typeof body.fileName === "string" ? body.fileName : undefined;
        const fileSize = typeof body.fileSize === "number" ? body.fileSize : undefined;
        const mimeType = typeof body.mimeType === "string" ? body.mimeType : undefined;

        if (!contentKey) {
          return corsError("contentKey is required for add-fs-item action", 400);
        }
        if (!path || !path.startsWith("/")) {
          return corsError("path is required and must start with /", 400);
        }

        // Normalize path (collapse double slashes)
        const cleanPath = ("/" + path.replace(/^\/+/, "")).replace(/\/\//g, "/");

        const atomicResult = await atomicArrayUpdate<StackItem, { error?: string; itemCount?: number; duplicate?: boolean; limitExceeded?: boolean }>(
          `${STACK_ITEMS_PREFIX}${stackId}`,
          (stackItems) => {
            // Check duplicate by contentKey
            if (stackItems.some(item => item.contentKey === contentKey)) {
              return { abort: true, result: { duplicate: true } };
            }

            // Enforce 20-item limit unless unlocked
            if (!stack.unlocked && stackItems.length >= STACK_ITEM_LIMIT) {
              return { abort: true, result: { limitExceeded: true } };
            }

            const resolvedFileName = fileName || cleanPath.split("/").pop() || "unknown";
            const resolvedParentPath = "/" + cleanPath.split("/").slice(0, -1).filter(Boolean).join("/");

            const newItem: StackItem = {
              contentKey,
              addedAt: Date.now(),
              addedBy: (memberEntry?.address ?? caller.address)?.toLowerCase() || String(memberEntry?.memberId ?? "unknown"),
              path: cleanPath,
              fileName: resolvedFileName,
              fileSize: fileSize ?? 0,
              mimeType: mimeType,
              isDirectory: false,
              parentPath: resolvedParentPath,
            };

            return {
              updated: [...stackItems, newItem],
              result: { itemCount: stackItems.length + 1 },
            };
          }
        );

        if (!atomicResult.success) {
          console.error("[PUT /api/v1/stacks/write] Atomic add-fs-item failed:", atomicResult.error);
          return corsError(atomicResult.error || "Failed to add filesystem item", 500);
        }

        if (atomicResult.result?.duplicate) {
          return corsError("Item already in stack", 409);
        }

        if (atomicResult.result?.limitExceeded) {
          return corsResponse({
            success: false,
            error: `Stack has reached the ${STACK_ITEM_LIMIT}-item limit. Unlock the stack to add more.`,
            unlockRequired: true,
            price: PRICING.STACK_UNLOCK,
            currency: "USDC",
          }, 402);
        }

        // Update stack metadata: itemCount, fileCount, totalSize
        const allItems = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${stackId}`) || [];
        stack.itemCount = atomicResult.result?.itemCount || allItems.length;
        stack.fileCount = allItems.filter(i => !i.isDirectory).length;
        stack.totalSize = allItems.reduce((sum, i) => sum + (i.fileSize || 0), 0);
        await setKV(`${STACK_PREFIX}${stackId}`, stack);

        // Update reverse index
        const itemStacks = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${contentKey}`) || [];
        if (!itemStacks.includes(stackId)) {
          itemStacks.push(stackId);
          await setKV(`${ITEM_STACKS_PREFIX}${contentKey}`, itemStacks);
        }

        console.log(`[PUT /api/v1/stacks/write] FS item ${contentKey} added to stack ${stackId} at path ${cleanPath}`);

        return corsResponse({
          success: true,
          action: "add-fs-item",
          stackId,
          contentKey,
          path: cleanPath,
          itemCount: stack.itemCount,
        });
      }

      default:
        return corsError(`Unknown action: ${action}`, 400);
    }
  } catch (error) {
    console.error("[PUT /api/v1/stacks/write] Error:", error);
    return corsError("Internal server error", 500);
  }
}

/**
 * DELETE /api/v1/stacks/write — Remove items from a stack
 *
 * Body:
 * - stackId (required): Stack ID
 * - items (required): Array of content keys to remove
 */
export async function DELETE(request: NextRequest) {
  try {
    // 1. Parse body (needed for Farcaster/web auth identity)
    let body: Record<string, unknown> = {};
    try {
      body = await request.json();
    } catch {
      // Body may be absent for Bearer-only callers
    }

    // 2. Authenticate caller (Bearer or Farcaster/web)
    const caller = await authenticateCaller(request, body);
    if (caller instanceof Response) return caller;

    // 3. Bearer agents must have stacks:write permission
    if (caller.type === "bearer" && caller.agent && !hasPermission(caller.agent, "stacks:write")) {
      return corsError("Insufficient permissions. Requires 'stacks:write'", 403);
    }

    // 4. Resolve member for ownership checks
    const registry = await getMemberRegistry();
    const memberEntry = resolveCallerMember(caller, registry);

    const stackId = typeof body.stackId === "string" ? body.stackId : null;

    // 4. Validate required fields
    if (!stackId) {
      return corsError("stackId is required", 400);
    }

    const rawItems = Array.isArray(body.items) ? body.items : null;
    if (!rawItems || rawItems.length === 0) {
      return corsError("Items array is required and must not be empty", 400);
    }

    // Validate all items are strings
    for (const item of rawItems) {
      if (typeof item !== "string") {
        return corsError("Each item must be a content key string", 400);
      }
    }
    const items = rawItems as string[];

    // 5. Get the stack
    const stack = await getKV<Stack>(`${STACK_PREFIX}${stackId}`);
    if (!stack) {
      return corsError("Stack not found", 404);
    }

    // 6. Check ownership or admin
    const isAdmin = caller.type === "bearer" && caller.agent && hasPermission(caller.agent, "admin");
    if (!isAdmin && !canManageStack(stack, ownerIdentity(caller, memberEntry))) {
      return corsError("Not authorized to modify this stack", 403);
    }

    // 7. Get current items
    const stackItems = await getKV<StackItem[]>(`${STACK_ITEMS_PREFIX}${stackId}`) || [];

    // 8. Create a set of items to remove
    const itemsToRemove = new Set(items);
    const originalCount = stackItems.length;

    // 9. Filter out items to remove
    const remainingItems = stackItems.filter(item => !itemsToRemove.has(item.contentKey));
    const removedCount = originalCount - remainingItems.length;

    // 10. Save updated items
    await setKV(`${STACK_ITEMS_PREFIX}${stackId}`, remainingItems);

    // 11. Update stack item count
    stack.itemCount = remainingItems.length;
    await setKV(`${STACK_PREFIX}${stackId}`, stack);

    // 12. Update reverse index for each removed item
    for (const contentKey of items) {
      const itemStacks = await getKV<string[]>(`${ITEM_STACKS_PREFIX}${contentKey}`) || [];
      const updatedItemStacks = itemStacks.filter(id => id !== stackId);
      await setKV(`${ITEM_STACKS_PREFIX}${contentKey}`, updatedItemStacks);
    }

    console.log(`[DELETE /api/v1/stacks/write] Removed ${removedCount} items from stack ${stackId}`);

    return corsResponse({
      success: true,
      removed: removedCount,
      stackId,
      itemCount: stack.itemCount,
    });
  } catch (error) {
    console.error("[DELETE /api/v1/stacks/write] Error:", error);
    return corsError("Internal server error", 500);
  }
}
src/app/api/v1/stats/route.ts
/**
 * Library Statistics API
 *
 * GET /api/v1/stats — Get library, member, and stack statistics
 * OPTIONS — CORS preflight
 */

import {
  getKV,
  getMemberRegistry,
  handleOptions,
  corsResponse,
  corsError,
} from "@/lib/agent-auth";
import type { DiscoveryEntry } from "@/lib/net-protocol";

// KV keys
const DISCOVERY_KEY = "discovery-index";
const STACKS_REGISTRY_KEY = "stacks-registry";

// OPTIONS handler for CORS preflight
export async function OPTIONS() {
  return handleOptions();
}

/**
 * GET /api/v1/stats — Library statistics
 *
 * Returns:
 * - library: { totalItems, categories, mediaTypes }
 * - members: { total, agents, humans }
 * - stacks: { total }
 */
export async function GET() {
  try {
    // Fetch all data in parallel
    const [discoveryEntries, stackIds, memberRegistry] = await Promise.all([
      getKV<DiscoveryEntry[]>(DISCOVERY_KEY),
      getKV<string[]>(STACKS_REGISTRY_KEY),
      getMemberRegistry(),
    ]);

    // Process discovery entries
    const entries = discoveryEntries || [];
    const visibleEntries = entries.filter(e => !e.hidden);

    // Count by category
    const categories: Record<string, number> = {};
    for (const entry of visibleEntries) {
      for (const category of entry.categories || []) {
        const lowerCategory = category.toLowerCase();
        categories[lowerCategory] = (categories[lowerCategory] || 0) + 1;
      }
    }

    // Count by media type
    const mediaTypes: Record<string, number> = {};
    for (const entry of visibleEntries) {
      const mediaType = entry.mediaType?.toLowerCase() || "unknown";
      mediaTypes[mediaType] = (mediaTypes[mediaType] || 0) + 1;
    }

    // Count members
    const totalMembers = memberRegistry.members.length;
    const agentMembers = memberRegistry.members.filter(m => m.isAgent).length;
    const humanMembers = totalMembers - agentMembers;

    // Count stacks
    const totalStacks = stackIds?.length || 0;

    return corsResponse({
      success: true,
      library: {
        totalItems: visibleEntries.length,
        categories,
        mediaTypes,
      },
      members: {
        total: totalMembers,
        agents: agentMembers,
        humans: humanMembers,
      },
      stacks: {
        total: totalStacks,
      },
    });
  } catch (error) {
    console.error("[GET /api/v1/stats] Error:", error);
    return corsError("Failed to fetch stats", 500);
  }
}
src/app/api/v1/webhooks/farcaster/route.ts
/* eslint-disable @neynar/no-process-env */
import { NextRequest, NextResponse } from "next/server";
import { createHmac, timingSafeEqual } from "crypto";
import { atomicArrayUpdate } from "@/lib/agent-auth";

// Webhook signature verification
const WEBHOOK_SECRET = process.env.NEYNAR_WEBHOOK_SECRET || "";

function verifyWebhookSignature(body: string, signature: string): boolean {
  if (!WEBHOOK_SECRET) {
    // Fail closed — if no secret is configured we cannot verify, so reject all requests
    console.error("[Webhook] NEYNAR_WEBHOOK_SECRET is not set — rejecting all webhook requests");
    return false;
  }
  const hmac = createHmac("sha512", WEBHOOK_SECRET);
  hmac.update(body);
  const expectedSignature = hmac.digest("hex");
  // Use constant-time comparison to prevent timing-attack enumeration of the secret
  if (signature.length !== expectedSignature.length) return false;
  return timingSafeEqual(
    Buffer.from(signature, "utf-8"),
    Buffer.from(expectedSignature, "utf-8")
  );
}

// Types
interface WebhookPayload {
  created_at: number;
  type: string;
  data: {
    object: string;
    hash: string;
    thread_hash: string;
    parent_hash: string | null;
    parent_url: string | null;
    parent_author: { fid: number | null };
    author: {
      fid: number;
      username: string;
      display_name: string;
      pfp_url: string;
      custody_address: string;
    };
    text: string;
    timestamp: string;
    embeds: Array<{ url?: string }>;
    mentioned_profiles: Array<{
      fid: number;
      username: string;
    }>;
  };
}

interface AgentTask {
  id: string;
  type: "farcaster_mention";
  status: "pending" | "processing" | "completed" | "failed";
  createdAt: string;
  updatedAt: string;
  assignedTo: string; // agent ID
  data: {
    castHash: string;
    castText: string;
    authorFid: number;
    authorUsername: string;
    authorDisplayName: string;
    authorPfpUrl: string;
    parentHash: string | null;
    threadHash: string;
    embeds: Array<{ url?: string }>;
    timestamp: string;
  };
  result?: {
    action: string;
    details: string;
    completedAt: string;
  };
}

const CHERYL_FID = 2798272;
const TASKS_KEY = "agent-tasks";
const MAX_PENDING_TASKS = 100; // prevent unbounded growth

// CORS headers
const corsHeaders = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "POST, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type",
};

export async function OPTIONS() {
  return NextResponse.json({}, { headers: corsHeaders });
}

export async function POST(request: NextRequest) {
  try {
    // Verify webhook signature before processing
    const rawBody = await request.text();
    const signature = request.headers.get("x-neynar-signature") || "";

    if (!verifyWebhookSignature(rawBody, signature)) {
      console.warn("[Webhook] Invalid signature — rejecting");
      return NextResponse.json(
        { success: false, error: "Invalid signature" },
        { status: 401, headers: corsHeaders }
      );
    }

    const body: WebhookPayload = JSON.parse(rawBody);

    // Validate it's a cast.created event
    if (body.type !== "cast.created") {
      return NextResponse.json(
        { success: true, message: "Ignored non-cast event" },
        { headers: corsHeaders }
      );
    }

    const cast = body.data;

    // Check if Cheryl is actually mentioned
    const cherylMentioned = cast.mentioned_profiles?.some(
      (profile) => profile.fid === CHERYL_FID
    );

    if (!cherylMentioned) {
      return NextResponse.json(
        { success: true, message: "Cheryl not mentioned, ignored" },
        { headers: corsHeaders }
      );
    }

    // Don't process Cheryl's own casts (avoid self-reply loops)
    if (cast.author.fid === CHERYL_FID) {
      return NextResponse.json(
        { success: true, message: "Ignoring own cast" },
        { headers: corsHeaders }
      );
    }

    // Create a task for Cheryl
    const task: AgentTask = {
      id: `task_${cast.hash.slice(0, 12)}_${Date.now()}`,
      type: "farcaster_mention",
      status: "pending",
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
      assignedTo: "cheryl",
      data: {
        castHash: cast.hash,
        castText: cast.text,
        authorFid: cast.author.fid,
        authorUsername: cast.author.username,
        authorDisplayName: cast.author.display_name,
        authorPfpUrl: cast.author.pfp_url,
        parentHash: cast.parent_hash,
        threadHash: cast.thread_hash,
        embeds: cast.embeds || [],
        timestamp: cast.timestamp,
      },
    };

    // Use atomic array update to prevent race conditions
    const atomicResult = await atomicArrayUpdate<AgentTask, { duplicate: boolean; taskId?: string }>(
      TASKS_KEY,
      (existingTasks) => {
        // Check for duplicate (same cast hash)
        const isDuplicate = existingTasks.some(
          (t) => t.data.castHash === cast.hash
        );
        if (isDuplicate) {
          return { abort: true, result: { duplicate: true } };
        }

        // Add new task, trim old completed/failed tasks if over limit
        const activeTasks = existingTasks.filter(
          (t) => t.status === "pending" || t.status === "processing"
        );
        const recentDoneTasks = existingTasks
          .filter((t) => t.status === "completed" || t.status === "failed")
          .slice(-20); // keep last 20 completed for history

        const updatedTasks = [...activeTasks, ...recentDoneTasks, task];

        // Cap total tasks
        const finalTasks = updatedTasks.slice(-MAX_PENDING_TASKS);

        return { updated: finalTasks, result: { duplicate: false, taskId: task.id } };
      }
    );

    if (!atomicResult.success) {
      console.error("[Webhook] Atomic task update failed:", atomicResult.error);
      // Return 200 to prevent Neynar retries
      return NextResponse.json(
        { success: false, error: "Failed to queue task" },
        { status: 200, headers: corsHeaders }
      );
    }

    if (atomicResult.result?.duplicate) {
      return NextResponse.json(
        { success: true, message: "Duplicate mention, already queued" },
        { headers: corsHeaders }
      );
    }

    console.log(
      `[Webhook] New mention from @${cast.author.username}: "${cast.text.slice(0, 80)}..."`
    );

    return NextResponse.json(
      {
        success: true,
        message: "Mention queued for Cheryl",
        taskId: atomicResult.result?.taskId,
      },
      { headers: corsHeaders }
    );
  } catch (error) {
    console.error("[Webhook] Error processing:", error);
    // Always return 200 to Neynar so it doesn't retry endlessly
    return NextResponse.json(
      { success: false, error: "Failed to process webhook" },
      { status: 200, headers: corsHeaders }
    );
  }
}
src/app/api/verify-content/route.ts
import { NextRequest, NextResponse } from "next/server";

const BASE_CHAIN_ID = 8453;

/**
 * GET handler for simple single-item verification
 * Used by upload hook to verify content exists after upload
 *
 * Query params: key, operator
 * Returns: { exists: boolean, error?: string }
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const key = searchParams.get("key");
    const operator = searchParams.get("operator");

    if (!key || !operator) {
      return NextResponse.json(
        { exists: false, error: "Missing key or operator" },
        { status: 400 }
      );
    }

    console.log(`[VERIFY-GET] Checking: key=${key.slice(0, 20)}..., operator=${operator.slice(0, 10)}...`);

    // Try raw storage endpoint
    const rawUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${operator}/${key}`;

    try {
      const response = await fetch(rawUrl, {
        method: "HEAD",
        signal: AbortSignal.timeout(10000),
      });

      if (response.ok) {
        console.log(`[VERIFY-GET] ✅ Content exists (HEAD)`);
        return NextResponse.json({ exists: true });
      }

      // HEAD failed, try GET
      const getResponse = await fetch(rawUrl, {
        method: "GET",
        signal: AbortSignal.timeout(10000),
      });

      const contentType = getResponse.headers.get("content-type") || "";

      // If we get content (not JSON error), it exists
      if (getResponse.ok && !contentType.includes("application/json")) {
        console.log(`[VERIFY-GET] ✅ Content exists (GET)`);
        return NextResponse.json({ exists: true });
      }

      // Check for JSON error response
      if (contentType.includes("application/json")) {
        const data = await getResponse.json().catch(() => ({}));
        console.log(`[VERIFY-GET] ❌ Content not found:`, data.error || "Unknown error");
        return NextResponse.json({ exists: false, error: data.error || "Content not found" });
      }

      console.log(`[VERIFY-GET] ❌ Content not found (status ${getResponse.status})`);
      return NextResponse.json({ exists: false, error: `HTTP ${getResponse.status}` });
    } catch (fetchError) {
      const errMsg = fetchError instanceof Error ? fetchError.message : "Network error";
      console.error(`[VERIFY-GET] Fetch error:`, errMsg);
      return NextResponse.json({ exists: false, error: errMsg });
    }
  } catch (error) {
    console.error("[VERIFY-GET] Error:", error);
    return NextResponse.json(
      { exists: false, error: error instanceof Error ? error.message : "Verification failed" },
      { status: 500 }
    );
  }
}

/**
 * POST handler for batch verification
 * Checks if the content key is accessible via Net Protocol CDN
 * Returns verification status for each content key
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { items } = body as {
      items: Array<{
        contentKey: string;
        operator: string;
        title?: string;
      }>;
    };

    if (!items || !Array.isArray(items) || items.length === 0) {
      return NextResponse.json(
        { success: false, error: "Missing items array" },
        { status: 400 }
      );
    }

    // Limit batch size
    const maxBatch = 20;
    const itemsToCheck = items.slice(0, maxBatch);

    console.log(`[VERIFY] Checking ${itemsToCheck.length} items...`);

    // Check each item in parallel
    const results = await Promise.all(
      itemsToCheck.map(async (item) => {
        const { contentKey, operator, title } = item;

        // Skip items without required fields
        if (!contentKey || !operator) {
          return {
            contentKey,
            operator,
            title,
            status: "invalid" as const,
            error: "Missing contentKey or operator",
          };
        }

        // Try multiple verification methods
        let verified = false;
        let errorMsg = "";

        // Method 1: Try raw storage endpoint
        try {
          const rawUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${operator}/${contentKey}`;
          const response = await fetch(rawUrl, {
            method: "HEAD",
            signal: AbortSignal.timeout(10000),
          });

          if (response.ok) {
            verified = true;
          } else if (response.status === 404) {
            errorMsg = "Content not found on chain";
          } else {
            errorMsg = `HTTP ${response.status}`;
          }
        } catch {
          // HEAD might not be supported, try GET
          try {
            const rawUrl = `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${operator}/${contentKey}`;
            const response = await fetch(rawUrl, {
              method: "GET",
              signal: AbortSignal.timeout(10000),
            });

            // Check if response is valid (not an error JSON)
            const contentType = response.headers.get("content-type") || "";
            if (response.ok && !contentType.includes("application/json")) {
              verified = true;
            } else if (contentType.includes("application/json")) {
              const data = await response.json().catch(() => ({}));
              if (data.error) {
                errorMsg = data.error;
              }
            } else if (response.status === 404) {
              errorMsg = "Content not found on chain";
            }
          } catch (getErr) {
            errorMsg = getErr instanceof Error ? getErr.message : "Network error";
          }
        }

        // Method 2: Legacy handling for old CDN imports with fake keys
        // NOTE: As of the stricter CDN import rules, new imports MUST have real
        // Net Protocol storage keys. This handling is only for legacy entries
        // created before that change. These items cannot be upvoted on-chain.
        if (!verified && contentKey.startsWith("cdn-")) {
          return {
            contentKey,
            operator,
            title,
            status: "external" as const,
            message: "Legacy CDN import (cannot be upvoted - predates strict validation)",
          };
        }

        // Note: /content/{key} endpoint is DEPRECATED and returns 404 - don't try it

        return {
          contentKey,
          operator,
          title,
          status: verified ? ("verified" as const) : ("broken" as const),
          error: verified ? undefined : errorMsg || "Content not accessible",
        };
      })
    );

    // Summarize results
    const verified = results.filter((r) => r.status === "verified").length;
    const broken = results.filter((r) => r.status === "broken").length;
    const external = results.filter((r) => r.status === "external").length;
    const invalid = results.filter((r) => r.status === "invalid").length;

    console.log(`[VERIFY] Results: ${verified} verified, ${broken} broken, ${external} external, ${invalid} invalid`);

    return NextResponse.json({
      success: true,
      results,
      summary: {
        total: results.length,
        verified,
        broken,
        external,
        invalid,
      },
    });
  } catch (error) {
    console.error("[VERIFY] Error:", error);
    return NextResponse.json(
      { success: false, error: error instanceof Error ? error.message : "Verification failed" },
      { status: 500 }
    );
  }
}
src/app/api/verify-ens/route.ts
import { NextRequest, NextResponse } from "next/server";
import { createPublicClient, http } from "viem";
import { mainnet } from "viem/chains";
import { normalize } from "viem/ens";

// Create a mainnet client for ENS resolution (ENS is on mainnet)
const publicClient = createPublicClient({
  chain: mainnet,
  transport: http("https://eth.llamarpc.com"),
});

// GET - Verify ENS subname resolves to expected address
export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const name = searchParams.get("name"); // e.g., "4.netlibrary.eth"
  const memberId = searchParams.get("memberId"); // e.g., "4"

  // Build the ENS name if memberId is provided
  const ensName = name || (memberId ? `${memberId}.netlibrary.eth` : null);

  if (!ensName) {
    return NextResponse.json(
      { error: "Either 'name' or 'memberId' parameter is required" },
      { status: 400 }
    );
  }

  try {
    console.log("[verify-ens] Resolving ENS name:", ensName);

    // Normalize the ENS name
    const normalizedName = normalize(ensName);

    // Resolve ENS name to address
    const resolvedAddress = await publicClient.getEnsAddress({
      name: normalizedName,
    });

    if (!resolvedAddress) {
      return NextResponse.json({
        success: true,
        ensName,
        resolved: false,
        address: null,
        message: `ENS name '${ensName}' does not resolve to any address`,
      });
    }

    // Also try to get text records
    let textRecords: Record<string, string | null> = {};
    try {
      const [description, comFarcaster, avatar] = await Promise.all([
        publicClient.getEnsText({ name: normalizedName, key: "description" }),
        publicClient.getEnsText({ name: normalizedName, key: "com.farcaster" }),
        publicClient.getEnsText({ name: normalizedName, key: "avatar" }),
      ]);
      textRecords = {
        description,
        "com.farcaster": comFarcaster,
        avatar,
      };
    } catch (textError) {
      console.log("[verify-ens] Could not fetch text records:", textError);
    }

    return NextResponse.json({
      success: true,
      ensName,
      resolved: true,
      address: resolvedAddress,
      textRecords,
      message: `ENS name '${ensName}' resolves to ${resolvedAddress}`,
    });
  } catch (error) {
    console.error("[verify-ens] Error:", error);
    return NextResponse.json(
      {
        success: false,
        ensName,
        error: error instanceof Error ? error.message : "Failed to resolve ENS",
      },
      { status: 500 }
    );
  }
}

// POST - Verify multiple ENS subnames or compare with member registry
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { memberIds, verifyAgainstRegistry } = body;

    if (!memberIds || !Array.isArray(memberIds)) {
      return NextResponse.json(
        { error: "memberIds array is required" },
        { status: 400 }
      );
    }

    const results: Array<{
      memberId: number;
      ensName: string;
      resolved: boolean;
      ensAddress: string | null;
      registryAddress?: string | null;
      match?: boolean;
    }> = [];

    // Optionally fetch the member registry to compare
    let registry: { members: Array<{ id: number; address: string }> } | null = null;
    if (verifyAgainstRegistry) {
      try {
        const registryResponse = await fetch(
          `${request.nextUrl.origin}/api/membership?debug=true`
        );
        if (registryResponse.ok) {
          const data = await registryResponse.json();
          registry = { members: data.members || [] };
          console.log("[verify-ens] Registry loaded:", registry.members.length, "members");
        }
      } catch (err) {
        console.error("[verify-ens] Failed to fetch registry:", err);
      }
    }

    // Resolve each member's ENS
    for (const memberId of memberIds.slice(0, 20)) { // Limit to 20
      const ensName = `${memberId}.netlibrary.eth`;

      try {
        const normalizedName = normalize(ensName);
        const resolvedAddress = await publicClient.getEnsAddress({
          name: normalizedName,
        });

        const result: typeof results[0] = {
          memberId,
          ensName,
          resolved: !!resolvedAddress,
          ensAddress: resolvedAddress,
        };

        // Compare with registry if available
        if (registry) {
          const member = registry.members.find(m => m.id === memberId);
          result.registryAddress = member?.address || null;
          result.match = member && resolvedAddress
            ? resolvedAddress.toLowerCase() === member.address.toLowerCase()
            : false;
        }

        results.push(result);
      } catch {
        results.push({
          memberId,
          ensName,
          resolved: false,
          ensAddress: null,
        });
      }
    }

    const allResolved = results.every(r => r.resolved);
    const allMatch = registry ? results.every(r => r.match) : undefined;

    return NextResponse.json({
      success: true,
      totalChecked: results.length,
      allResolved,
      allMatch,
      results,
    });
  } catch (error) {
    console.error("[verify-ens] Error:", error);
    return NextResponse.json(
      { error: "Failed to verify ENS names" },
      { status: 500 }
    );
  }
}
src/app/api/verify-siwe/route.ts
import { NextRequest, NextResponse } from "next/server";
import { verifyMessage } from "viem";
import { parseSiweMessage } from "@/lib/siwe";

/**
 * POST /api/verify-siwe
 * Verifies a Sign In With Ethereum (SIWE) signature
 *
 * Body:
 * - message: The SIWE message that was signed
 * - signature: The signature from the wallet
 * - expectedAddress: The address we expect to have signed
 *
 * Returns:
 * - valid: boolean - whether the signature is valid
 * - address: string - the verified address (if valid)
 * - fid: number - the FID from the message (if present)
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { message, signature, expectedAddress } = body;

    if (!message || !signature || !expectedAddress) {
      return NextResponse.json(
        { error: "Missing required fields: message, signature, expectedAddress" },
        { status: 400 }
      );
    }

    // Parse the SIWE message to extract components
    const parsed = parseSiweMessage(message);

    if (!parsed.address) {
      return NextResponse.json(
        { error: "Invalid SIWE message: no address found" },
        { status: 400 }
      );
    }

    // Verify the address in the message matches expected
    if (parsed.address.toLowerCase() !== expectedAddress.toLowerCase()) {
      return NextResponse.json(
        { error: "Address mismatch: message address doesn't match expected" },
        { status: 400 }
      );
    }

    // Check expiration if present
    if (parsed.expirationTime) {
      const expiration = new Date(parsed.expirationTime);
      if (expiration < new Date()) {
        return NextResponse.json(
          { error: "SIWE message has expired" },
          { status: 400 }
        );
      }
    }

    // Check issued at - reject messages older than 1 hour
    if (parsed.issuedAt) {
      const issuedAt = new Date(parsed.issuedAt);
      const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
      if (issuedAt < oneHourAgo) {
        return NextResponse.json(
          { error: "SIWE message is too old" },
          { status: 400 }
        );
      }
    }

    // Verify the signature using viem
    const isValid = await verifyMessage({
      address: expectedAddress as `0x${string}`,
      message,
      signature: signature as `0x${string}`,
    });

    if (!isValid) {
      return NextResponse.json(
        { valid: false, error: "Invalid signature" },
        { status: 401 }
      );
    }

    // Extract FID from statement if present
    let fid: number | undefined;
    if (parsed.statement) {
      const fidMatch = parsed.statement.match(/FID:\s*(\d+)/);
      if (fidMatch) {
        fid = parseInt(fidMatch[1], 10);
      }
    }

    return NextResponse.json({
      valid: true,
      address: parsed.address,
      fid,
      domain: parsed.domain,
      chainId: parsed.chainId,
      nonce: parsed.nonce,
    });
  } catch (error) {
    console.error("[POST /api/verify-siwe] Error:", error);
    return NextResponse.json(
      { error: "Failed to verify SIWE signature" },
      { status: 500 }
    );
  }
}
src/app/api/wallet-tokens/route.ts
import { NextRequest, NextResponse } from "next/server";
import { formatUnits, createPublicClient, http, erc20Abi } from "viem";
import { base } from "viem/chains";

// USDC on Base
const USDC_ADDRESS = "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913";
const USDC_DECIMALS = 6;

// Create public client lazily to avoid module-level initialization issues
function getPublicClient() {
  return createPublicClient({
    chain: base,
    transport: http(),
  });
}

interface WalletToken {
  symbol: string;
  name: string;
  address: string;
  decimals: number;
  balance: string;
  balanceFormatted: string;
  logoUrl?: string;
  usdValue?: number;
  usdPrice?: number;
}

// Fetch ALL token balances using Routescan API (free, no API key required)
async function fetchAllTokensViaRoutescan(address: string): Promise<Array<{
  address: string;
  symbol: string;
  name: string;
  decimals: number;
  balance: bigint;
  balanceUsd?: number;
  priceUsd?: number;
}>> {
  const allTokens: Array<{
    address: string;
    symbol: string;
    name: string;
    decimals: number;
    balance: bigint;
    balanceUsd?: number;
    priceUsd?: number;
  }> = [];

  try {
    console.log("[wallet-tokens] Fetching ALL tokens from Routescan for:", address);

    let nextToken: string | null = null;
    let pageCount = 0;
    const maxPages = 5; // Safety limit

    do {
      const url: string = nextToken
        ? `https://api.routescan.io/v2/network/mainnet/evm/8453/address/${address}/erc20-holdings?next=${nextToken}`
        : `https://api.routescan.io/v2/network/mainnet/evm/8453/address/${address}/erc20-holdings`;

      const response = await fetch(url, {
        headers: { "Accept": "application/json" },
        cache: "no-store",
      });

      if (!response.ok) {
        console.log("[wallet-tokens] Routescan API error:", response.status);
        break;
      }

      const data = await response.json();
      const items = data.items || [];

      console.log("[wallet-tokens] Routescan page", pageCount + 1, "returned", items.length, "tokens");

      for (const item of items) {
        if (!item.tokenAddress || !item.tokenQuantity) continue;

        const decimals = item.tokenDecimals || 18;
        const balance = BigInt(item.tokenQuantity);

        // Routescan uses different field names - check all possibilities
        const priceUsd = item.tokenPrice ?? item.price ?? item.priceUsd ?? item.usdPrice ?? undefined;
        const balanceUsd = item.tokenValueInUsd ?? item.valueInUsd ?? item.usdValue ?? item.balanceUsd ?? undefined;

        // Log first few tokens to debug field names
        if (allTokens.length < 3) {
          console.log("[wallet-tokens] Token item fields:", JSON.stringify(item, null, 2));
        }

        allTokens.push({
          address: item.tokenAddress.toLowerCase(),
          symbol: item.tokenSymbol || "???",
          name: item.tokenName || "Unknown Token",
          decimals,
          balance,
          balanceUsd: balanceUsd !== undefined ? parseFloat(String(balanceUsd)) : undefined,
          priceUsd: priceUsd !== undefined ? parseFloat(String(priceUsd)) : undefined,
        });
      }

      nextToken = data.link?.nextToken || null;
      pageCount++;
    } while (nextToken && pageCount < maxPages);

    console.log("[wallet-tokens] Routescan found", allTokens.length, "total ERC20 tokens on Base");
    return allTokens;
  } catch (err) {
    console.error("[wallet-tokens] Routescan fetch error:", err);
    return allTokens;
  }
}

export async function GET(request: NextRequest) {
  console.log("[wallet-tokens] API called with URL:", request.url);
  const addressParam = request.nextUrl.searchParams.get("address");

  if (!addressParam) {
    console.log("[wallet-tokens] No address provided");
    return NextResponse.json({ error: "Address required" }, { status: 400 });
  }

  const walletAddress = addressParam.toLowerCase();
  console.log("[wallet-tokens] Checking ONLY the provided address:", walletAddress);

  try {
    // Fetch tokens ONLY for the provided address (the connected Farcaster wallet)
    const tokens = await fetchAllTokensViaRoutescan(walletAddress);

    console.log("[wallet-tokens] Found", tokens.length, "tokens for address", walletAddress);

    // Check if USDC is in the list, if not fetch it directly
    const hasUsdc = tokens.some(t => t.address.toLowerCase() === USDC_ADDRESS.toLowerCase());
    if (!hasUsdc) {
      console.log("[wallet-tokens] USDC not in Routescan results, fetching directly...");
      try {
        const usdcBalance = await getPublicClient().readContract({
          address: USDC_ADDRESS as `0x${string}`,
          abi: erc20Abi,
          functionName: "balanceOf",
          args: [walletAddress as `0x${string}`],
        });

        if (usdcBalance > 0n) {
          const usdcFormatted = formatUnits(usdcBalance, USDC_DECIMALS);
          const usdcUsdValue = parseFloat(usdcFormatted); // USDC is 1:1 with USD
          console.log("[wallet-tokens] Direct USDC balance:", usdcFormatted, "($" + usdcUsdValue.toFixed(2) + ")");

          tokens.push({
            address: USDC_ADDRESS,
            symbol: "USDC",
            name: "USD Coin",
            decimals: USDC_DECIMALS,
            balance: usdcBalance,
            balanceUsd: usdcUsdValue,
            priceUsd: 1.0,
          });
        }
      } catch (usdcErr) {
        console.error("[wallet-tokens] Failed to fetch USDC directly:", usdcErr);
      }
    } else {
      console.log("[wallet-tokens] USDC found in Routescan results");
    }

    // Filter tokens worth less than $0.01 USD
    const tokensWithInfo = tokens.filter(token => {
      // If we have USD value, use that for filtering
      if (token.balanceUsd !== undefined) {
        return token.balanceUsd >= 0.01;
      }
      // If no USD value, keep tokens with reasonable balance (fallback)
      const balanceFormatted = formatUnits(token.balance, token.decimals);
      return parseFloat(balanceFormatted) >= 0.0001;
    });

    console.log("[wallet-tokens] After filtering <$0.01 tokens:", tokensWithInfo.length, "tokens");

    // Build final token list
    const finalTokens: WalletToken[] = tokensWithInfo.map(token => {
      const balanceFormatted = formatUnits(token.balance, token.decimals);

      return {
        symbol: token.symbol,
        name: token.name,
        address: token.address,
        decimals: token.decimals,
        balance: token.balance.toString(),
        balanceFormatted: balanceFormatted,
        usdValue: token.balanceUsd,
        usdPrice: token.priceUsd,
      };
    });

    // Sort by USD value (highest first)
    finalTokens.sort((a, b) => {
      if (a.usdValue !== undefined && b.usdValue !== undefined) {
        return b.usdValue - a.usdValue;
      }
      if (a.usdValue !== undefined) return -1;
      if (b.usdValue !== undefined) return 1;
      return parseFloat(b.balanceFormatted) - parseFloat(a.balanceFormatted);
    });

    console.log(`[wallet-tokens] Final: ${finalTokens.length} tokens`);
    console.log("[wallet-tokens] Tokens:", finalTokens.map(t => `${t.symbol}: ${t.balanceFormatted} ($${t.usdValue?.toFixed(2) || 'N/A'})`).join(", "));

    return NextResponse.json({
      success: true,
      tokens: finalTokens,
      count: finalTokens.length,
      address: walletAddress,
    });
  } catch (error) {
    console.error("[wallet-tokens] Error:", error);
    return NextResponse.json(
      { error: "Failed to fetch wallet tokens", tokens: [] },
      { status: 500 }
    );
  }
}

🔗 Share Routes (19)

src/app/api/share/image/achievement/route.tsx
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';

export const runtime = 'edge';
export const maxDuration = 30;

// Rarity colors matching the app
const RARITY_COLORS: Record<string, { border: string; bg: string; text: string; glow: string }> = {
  common: { border: '#6b7280', bg: 'rgba(107,114,128,0.2)', text: '#9ca3af', glow: 'rgba(107,114,128,0.3)' },
  uncommon: { border: '#22c55e', bg: 'rgba(34,197,94,0.2)', text: '#4ade80', glow: 'rgba(34,197,94,0.4)' },
  rare: { border: '#3b82f6', bg: 'rgba(59,130,246,0.2)', text: '#60a5fa', glow: 'rgba(59,130,246,0.4)' },
  epic: { border: '#8A63D2', bg: 'rgba(138,99,210,0.2)', text: '#B794F6', glow: 'rgba(138,99,210,0.5)' },
  legendary: { border: '#eab308', bg: 'rgba(234,179,8,0.2)', text: '#facc15', glow: 'rgba(234,179,8,0.6)' },
};

// SVG paths for achievement icons (for Satori image generation)
function getAchievementIconSvg(iconId: string, color: string = 'currentColor'): React.ReactNode {
  const size = 80;
  const style = { width: size, height: size, color };

  switch (iconId) {
    case 'shield':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
        </svg>
      );
    case 'link':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71" />
          <path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71" />
        </svg>
      );
    case 'star':
    case 'star-shine':
      return (
        <svg style={style} viewBox="0 0 24 24" fill={color} stroke="none">
          <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" />
        </svg>
      );
    case 'gem':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M6 3h12l4 6-10 13L2 9z" />
          <path d="M2 9h20" />
          <path d="M12 22V9" />
          <path d="M6 3l6 6 6-6" />
        </svg>
      );
    case 'upload':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
          <polyline points="17 8 12 3 7 8" />
          <line x1="12" y1="3" x2="12" y2="15" />
        </svg>
      );
    case 'sparkle':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 3v4m0 10v4M3 12h4m10 0h4" />
          <path d="M5.6 5.6l2.8 2.8m7.2 7.2l2.8 2.8M5.6 18.4l2.8-2.8m7.2-7.2l2.8-2.8" />
        </svg>
      );
    case 'crown':
    case 'crown-gold':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M2 4l3 12h14l3-12-6 7-4-7-4 7-6-7z" />
          <path d="M3 20h18" />
        </svg>
      );
    case 'arrow-up':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 19V5" />
          <path d="M5 12l7-7 7 7" />
        </svg>
      );
    case 'heart':
    case 'heart-green':
      return (
        <svg style={style} viewBox="0 0 24 24" fill={color} stroke="none">
          <path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
        </svg>
      );
    case 'circle-green':
      return (
        <svg style={style} viewBox="0 0 24 24" fill={color} stroke="none">
          <circle cx="12" cy="12" r="10" />
        </svg>
      );
    case 'square-green':
      return (
        <svg style={style} viewBox="0 0 24 24" fill={color} stroke="none">
          <rect x="3" y="3" width="18" height="18" rx="2" />
        </svg>
      );
    case 'chart':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <rect x="3" y="12" width="4" height="9" rx="1" />
          <rect x="10" y="8" width="4" height="13" rx="1" />
          <rect x="17" y="3" width="4" height="18" rx="1" />
        </svg>
      );
    case 'rocket':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z" />
          <path d="M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z" />
          <path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0" />
          <path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5" />
        </svg>
      );
    case 'save':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
          <polyline points="17 21 17 13 7 13 7 21" />
          <polyline points="7 3 7 8 15 8" />
        </svg>
      );
    case 'disc':
    case 'disc-shine':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="10" />
          <circle cx="12" cy="12" r="3" />
        </svg>
      );
    case 'archive':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <rect x="2" y="3" width="20" height="5" rx="1" />
          <path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8" />
          <path d="M10 12h4" />
        </svg>
      );
    case 'message':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
        </svg>
      );
    case 'megaphone':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M3 11l18-5v12L3 13V11z" />
          <path d="M11.6 16.8a3 3 0 1 1-5.8-1.6" />
        </svg>
      );
    case 'broadcast':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="2" />
          <path d="M16.24 7.76a6 6 0 0 1 0 8.49m-8.48-.01a6 6 0 0 1 0-8.49m11.31-2.82a10 10 0 0 1 0 14.14m-14.14 0a10 10 0 0 1 0-14.14" />
        </svg>
      );
    case 'crystal':
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="12" r="10" />
          <path d="M12 2a4.5 4.5 0 0 0 0 9 4.5 4.5 0 0 1 0 9" />
          <path d="M12 7v10" />
        </svg>
      );
    default:
      // Default medal icon
      return (
        <svg style={style} viewBox="0 0 24 24" fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <circle cx="12" cy="8" r="6" />
          <path d="M15.477 12.89 17 22l-5-3-5 3 1.523-9.11" />
        </svg>
      );
  }
}

// Achievement share image - redesigned to show user info and cleaner layout
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const name = searchParams.get('name') || 'Achievement';
    const iconId = searchParams.get('iconId') || 'shield';
    const rarity = searchParams.get('rarity') || 'common';
    const username = searchParams.get('username') || '';
    const pfpUrl = searchParams.get('pfpUrl') || '';

    // Build the absolute URL for the app logo
    const host = request.headers.get('host') || 'netlibrary.neynar.com';
    const protocol = host.includes('localhost') ? 'http' : 'https';
    const appLogoUrl = `${protocol}://${host}/app-logo.png?v=2`;

    // Get user's PFP - use dicebear as fallback
    const userPfp = pfpUrl || (username ? `https://api.dicebear.com/7.x/identicon/svg?seed=${username}` : '');

    const colors = RARITY_COLORS[rarity.toLowerCase()] || RARITY_COLORS.common;

    return new ImageResponse(
      (
        <div
          style={{
            height: '100%',
            width: '100%',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: '#000000',
            backgroundImage: 'linear-gradient(135deg, #0a0a0a 0%, #001a00 50%, #0a0a0a 100%)',
            position: 'relative',
          }}
        >
          {/* Scanline effect overlay */}
          <div
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              backgroundImage: 'repeating-linear-gradient(0deg, transparent 0px, transparent 2px, rgba(0,0,0,0.1) 2px, rgba(0,0,0,0.1) 4px)',
              opacity: 0.3,
              display: 'flex',
            }}
          />

          {/* Rarity glow in corners */}
          <div
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: 300,
              height: 300,
              background: `radial-gradient(circle, ${colors.glow} 0%, transparent 70%)`,
              display: 'flex',
            }}
          />
          <div
            style={{
              position: 'absolute',
              bottom: 0,
              right: 0,
              width: 300,
              height: 300,
              background: `radial-gradient(circle, ${colors.glow} 0%, transparent 70%)`,
              display: 'flex',
            }}
          />

          {/* Header with app branding */}
          <div
            style={{
              position: 'absolute',
              top: 30,
              display: 'flex',
              alignItems: 'center',
              gap: 16,
            }}
          >
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={appLogoUrl}
              alt="Net Library"
              style={{
                width: 40,
                height: 40,
                objectFit: 'contain',
              }}
            />
            <div
              style={{
                display: 'flex',
                fontSize: 24,
                fontWeight: 'bold',
                color: '#00ff00',
                fontFamily: 'monospace',
                letterSpacing: 4,
              }}
            >
              NET LIBRARY
            </div>
          </div>

          {/* Main content */}
          <div
            style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              padding: '60px',
            }}
          >
            {/* Achievement Unlocked header */}
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                gap: 12,
                fontSize: 28,
                color: '#00ff00',
                fontFamily: 'monospace',
                letterSpacing: 6,
                textTransform: 'uppercase',
                marginBottom: 32,
                textShadow: '0 0 20px rgba(0,255,0,0.5)',
              }}
            >
              <svg width={32} height={32} viewBox="0 0 24 24" fill="none" stroke="#00ff00" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <circle cx="12" cy="8" r="6" />
                <path d="M15.477 12.89 17 22l-5-3-5 3 1.523-9.11" />
              </svg>
              Achievement Unlocked
            </div>

            {/* Achievement badge circle */}
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: 160,
                height: 160,
                borderRadius: '50%',
                border: `6px solid ${colors.border}`,
                backgroundColor: colors.bg,
                boxShadow: `0 0 60px ${colors.glow}, inset 0 0 30px ${colors.glow}`,
                marginBottom: 24,
              }}
            >
              {getAchievementIconSvg(iconId, colors.text)}
            </div>

            {/* Achievement name */}
            <div
              style={{
                display: 'flex',
                fontSize: 48,
                fontWeight: 'bold',
                color: '#ffffff',
                fontFamily: 'monospace',
                marginBottom: 16,
                textShadow: '0 0 10px rgba(255,255,255,0.3)',
              }}
            >
              {name}
            </div>

            {/* Rarity badge */}
            <div
              style={{
                display: 'flex',
                padding: '10px 28px',
                borderRadius: 30,
                border: `3px solid ${colors.border}`,
                backgroundColor: colors.bg,
                boxShadow: `0 0 20px ${colors.glow}`,
              }}
            >
              <span
                style={{
                  fontSize: 18,
                  fontWeight: 'bold',
                  color: colors.text,
                  fontFamily: 'monospace',
                  textTransform: 'uppercase',
                  letterSpacing: 4,
                }}
              >
                {rarity}
              </span>
            </div>
          </div>

          {/* Footer with user info */}
          <div
            style={{
              position: 'absolute',
              bottom: 30,
              display: 'flex',
              alignItems: 'center',
              gap: 16,
            }}
          >
            {/* User PFP */}
            {userPfp && (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={userPfp}
                alt={username || 'user'}
                style={{
                  width: 48,
                  height: 48,
                  borderRadius: '50%',
                  border: '2px solid rgba(0,255,0,0.5)',
                  objectFit: 'cover',
                }}
              />
            )}
            <div style={{ display: 'flex', flexDirection: 'column' }}>
              {username && (
                <div
                  style={{
                    display: 'flex',
                    fontSize: 22,
                    fontWeight: 'bold',
                    color: '#ffffff',
                    fontFamily: 'monospace',
                  }}
                >
                  @{username}
                </div>
              )}
              <div
                style={{
                  display: 'flex',
                  fontSize: 14,
                  color: 'rgba(0,255,0,0.5)',
                  fontFamily: 'monospace',
                  letterSpacing: 2,
                }}
              >
                {username ? 'unlocked this achievement' : 'netlibrary.neynar.com'}
              </div>
            </div>
          </div>
        </div>
      ),
      {
        width: 1200,
        height: 800, // 3:2 aspect ratio for Farcaster
        headers: {
          'Cache-Control': 'no-cache, no-store, must-revalidate',
          'Pragma': 'no-cache',
          'Expires': '0',
        },
      }
    );
  } catch (e: unknown) {
    console.error('Failed to generate achievement image:', e);
    return new Response('Failed to generate image', { status: 500 });
  }
}
src/app/api/share/image/book/route.tsx
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';

export const runtime = 'edge';
export const maxDuration = 30; // Increase timeout for image generation

// Helper to check if an image URL looks valid (quick check, no network request)
function isValidImageUrl(url: string): boolean {
  if (!url) return false;
  try {
    const parsed = new URL(url);
    // Must be http/https and look like an image
    if (!['http:', 'https:'].includes(parsed.protocol)) return false;
    // Check for common image extensions or CDN patterns
    const path = parsed.pathname.toLowerCase();
    const isImageExt = /\.(jpg|jpeg|png|gif|webp|svg|bmp)(\?|$)/i.test(path);
    const isCdnUrl = parsed.hostname.includes('storedon.net') ||
                     parsed.hostname.includes('cloudinary') ||
                     parsed.hostname.includes('imgix') ||
                     parsed.hostname.includes('imgur');
    return isImageExt || isCdnUrl || url.includes('/api/') || url.includes('cover');
  } catch {
    return false;
  }
}

// Book share image - large cover art with subtle bottom branding banner
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const title = searchParams.get('title') || 'Untitled';
    const author = searchParams.get('author') || 'Unknown';
    let coverUrl = searchParams.get('coverUrl') || '';

    // Build the absolute URL for the app logo (with cache buster)
    const host = request.headers.get('host') || 'netlibrary.neynar.com';
    const protocol = host.includes('localhost') ? 'http' : 'https';
    const appLogoUrl = `${protocol}://${host}/app-logo.png?v=2`;

    console.log(`[book-share-image] Generating image for "${title}" by "${author}", coverUrl: ${coverUrl ? coverUrl.slice(0, 80) + '...' : 'none'}`);

    // Quick validation of cover URL format (no network request to avoid timeouts)
    if (coverUrl && !isValidImageUrl(coverUrl)) {
      console.log(`[book-share-image] Cover URL invalid format, falling back to placeholder`);
      coverUrl = '';
    }

    // If cover URL is from our own /api/covers/ endpoint, verify it's accessible
    // Edge runtime can have issues with same-origin requests, so we do a quick HEAD check with timeout
    if (coverUrl && coverUrl.includes('/api/covers/')) {
      try {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 3000); // 3 second timeout
        const checkResponse = await fetch(coverUrl, {
          method: 'HEAD',
          signal: controller.signal,
        });
        clearTimeout(timeoutId);
        if (!checkResponse.ok) {
          console.log(`[book-share-image] Cover URL returned ${checkResponse.status}, falling back to placeholder`);
          coverUrl = '';
        } else {
          console.log(`[book-share-image] Cover URL verified OK`);
        }
      } catch (err) {
        const errorMsg = err instanceof Error ? err.message : String(err);
        console.log(`[book-share-image] Cover URL fetch failed: ${errorMsg}, falling back to placeholder`);
        coverUrl = '';
      }
    } else if (coverUrl) {
      console.log(`[book-share-image] Using external cover URL: ${coverUrl.slice(0, 80)}`);
    }

    return new ImageResponse(
      (
        <div
          style={{
            height: '100%',
            width: '100%',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'flex-start',
            backgroundColor: '#000000',
            padding: 0,
          }}
        >
          {/* Main cover area - takes up most of the image */}
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: '100%',
              height: 530,
              position: 'relative',
              overflow: 'hidden',
            }}
          >
            {/* Background blur effect from cover */}
            {coverUrl && (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={coverUrl}
                alt=""
                style={{
                  position: 'absolute',
                  width: '120%',
                  height: '120%',
                  objectFit: 'cover',
                  filter: 'blur(40px) brightness(0.3)',
                  transform: 'scale(1.2)',
                }}
              />
            )}

            {/* Cover image - large and unobstructed */}
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: 340,
                height: 480,
                borderRadius: 12,
                border: '3px solid rgba(0,255,0,0.4)',
                backgroundColor: '#0a0a0a',
                boxShadow: '0 20px 60px rgba(0,0,0,0.8), 0 0 40px rgba(0,255,0,0.15)',
                overflow: 'hidden',
                position: 'relative',
              }}
            >
              {coverUrl ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={coverUrl}
                  alt={title}
                  style={{
                    width: '100%',
                    height: '100%',
                    objectFit: 'cover',
                  }}
                />
              ) : (
                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                    width: '100%',
                    height: '100%',
                    background: 'linear-gradient(180deg, #1a1a1a 0%, #0a0a0a 100%)',
                    padding: 40,
                  }}
                >
                  {/* Net Library logo as placeholder */}
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={appLogoUrl}
                    alt="Net Library"
                    style={{
                      width: 120,
                      height: 120,
                      objectFit: 'contain',
                      opacity: 0.8,
                    }}
                  />
                  {/* Title truncated */}
                  <div
                    style={{
                      display: 'flex',
                      fontSize: 24,
                      fontWeight: 'bold',
                      color: '#00ff00',
                      fontFamily: 'monospace',
                      marginTop: 24,
                      textAlign: 'center',
                      lineHeight: 1.3,
                      maxWidth: 280,
                    }}
                  >
                    {title.length > 40 ? title.slice(0, 40) + '...' : title}
                  </div>
                  <div
                    style={{
                      display: 'flex',
                      fontSize: 16,
                      color: 'rgba(0,255,0,0.6)',
                      fontFamily: 'monospace',
                      marginTop: 8,
                    }}
                  >
                    by {author.length > 30 ? author.slice(0, 30) + '...' : author}
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Bottom branding banner */}
          <div
            style={{
              display: 'flex',
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'space-between',
              width: '100%',
              height: 100,
              backgroundColor: 'rgba(0,20,0,0.95)',
              borderTop: '2px solid rgba(0,255,0,0.3)',
              padding: '0 40px',
            }}
          >
            {/* Left - Book info */}
            <div
              style={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'flex-start',
                flex: 1,
                maxWidth: 700,
              }}
            >
              <div
                style={{
                  display: 'flex',
                  fontSize: 28,
                  fontWeight: 'bold',
                  color: '#00ff00',
                  fontFamily: 'monospace',
                  lineHeight: 1.2,
                  textShadow: '0 0 10px rgba(0,255,0,0.3)',
                }}
              >
                {title.length > 45 ? title.slice(0, 45) + '...' : title}
              </div>
              <div
                style={{
                  display: 'flex',
                  fontSize: 18,
                  color: 'rgba(0,255,0,0.6)',
                  fontFamily: 'monospace',
                  marginTop: 4,
                }}
              >
                by {author.length > 35 ? author.slice(0, 35) + '...' : author}
              </div>
            </div>

            {/* Right - Net Library branding */}
            <div
              style={{
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                gap: 16,
              }}
            >
              {/* App logo */}
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={appLogoUrl}
                alt="Net Library"
                style={{
                  width: 50,
                  height: 50,
                  objectFit: 'contain',
                }}
              />
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'flex-start',
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    fontSize: 20,
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    fontWeight: 'bold',
                    letterSpacing: 2,
                  }}
                >
                  NET LIBRARY
                </div>
                <div
                  style={{
                    display: 'flex',
                    fontSize: 11,
                    color: 'rgba(0,255,0,0.5)',
                    fontFamily: 'monospace',
                    letterSpacing: 1,
                  }}
                >
                  POWERED BY NET PROTOCOL
                </div>
              </div>
            </div>
          </div>
        </div>
      ),
      {
        width: 1200,
        height: 800, // 3:2 aspect ratio for Farcaster
        headers: {
          'Cache-Control': 'no-cache, no-store, must-revalidate',
          'Pragma': 'no-cache',
          'Expires': '0',
        },
      }
    );
  } catch (e: unknown) {
    console.error('Failed to generate book share image:', e);
    return new Response('Failed to generate image', { status: 500 });
  }
}
src/app/api/share/image/book-twitter/route.tsx
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';

export const runtime = 'edge';
export const maxDuration = 30;

// Twitter requires 1.91:1 aspect ratio for summary_large_image cards
const TWITTER_WIDTH = 1200;
const TWITTER_HEIGHT = 628;

// Helper to check if an image URL looks valid (quick check, no network request)
function isValidImageUrl(url: string): boolean {
  if (!url) return false;
  try {
    const parsed = new URL(url);
    if (!['http:', 'https:'].includes(parsed.protocol)) return false;
    const path = parsed.pathname.toLowerCase();
    const isImageExt = /\.(jpg|jpeg|png|gif|webp|svg|bmp)(\?|$)/i.test(path);
    const isCdnUrl = parsed.hostname.includes('storedon.net') ||
                     parsed.hostname.includes('cloudinary') ||
                     parsed.hostname.includes('imgix') ||
                     parsed.hostname.includes('imgur');
    return isImageExt || isCdnUrl || url.includes('/api/') || url.includes('cover');
  } catch {
    return false;
  }
}

// Twitter-optimized book share image (1200x628)
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const title = searchParams.get('title') || 'Untitled';
    const author = searchParams.get('author') || 'Unknown';
    let coverUrl = searchParams.get('coverUrl') || '';

    const host = request.headers.get('host') || 'netlibrary.neynar.com';
    const protocol = host.includes('localhost') ? 'http' : 'https';
    const appLogoUrl = `${protocol}://${host}/app-logo.png?v=2`;

    console.log(`[book-twitter-image] Generating image for "${title}" by "${author}", coverUrl: ${coverUrl ? coverUrl.slice(0, 80) + '...' : 'none'}`);

    if (coverUrl && !isValidImageUrl(coverUrl)) {
      console.log(`[book-twitter-image] Cover URL invalid format, falling back to placeholder`);
      coverUrl = '';
    }

    // If cover URL is from our own /api/covers/ endpoint, verify it's accessible
    // Edge runtime can have issues with same-origin requests, so we do a quick HEAD check with timeout
    if (coverUrl && coverUrl.includes('/api/covers/')) {
      try {
        const controller = new AbortController();
        const timeoutId = setTimeout(() => controller.abort(), 3000); // 3 second timeout
        const checkResponse = await fetch(coverUrl, {
          method: 'HEAD',
          signal: controller.signal,
        });
        clearTimeout(timeoutId);
        if (!checkResponse.ok) {
          console.log(`[book-twitter-image] Cover URL returned ${checkResponse.status}, falling back to placeholder`);
          coverUrl = '';
        } else {
          console.log(`[book-twitter-image] Cover URL verified OK`);
        }
      } catch (err) {
        const errorMsg = err instanceof Error ? err.message : String(err);
        console.log(`[book-twitter-image] Cover URL fetch failed: ${errorMsg}, falling back to placeholder`);
        coverUrl = '';
      }
    } else if (coverUrl) {
      console.log(`[book-twitter-image] Using external cover URL: ${coverUrl.slice(0, 80)}`);
    }

    return new ImageResponse(
      (
        <div
          style={{
            height: '100%',
            width: '100%',
            display: 'flex',
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'flex-start',
            backgroundColor: '#000000',
            padding: 0,
          }}
        >
          {/* Left side - Cover art area */}
          <div
            style={{
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              width: 480,
              height: '100%',
              position: 'relative',
              overflow: 'hidden',
            }}
          >
            {/* Background blur effect */}
            {coverUrl && (
              // eslint-disable-next-line @next/next/no-img-element
              <img
                src={coverUrl}
                alt=""
                style={{
                  position: 'absolute',
                  width: '150%',
                  height: '150%',
                  objectFit: 'cover',
                  filter: 'blur(30px) brightness(0.25)',
                  transform: 'scale(1.3)',
                }}
              />
            )}

            {/* Cover image */}
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                width: 280,
                height: 400,
                borderRadius: 12,
                border: '3px solid rgba(0,255,0,0.4)',
                backgroundColor: '#0a0a0a',
                boxShadow: '0 15px 50px rgba(0,0,0,0.8), 0 0 30px rgba(0,255,0,0.15)',
                overflow: 'hidden',
                position: 'relative',
              }}
            >
              {coverUrl ? (
                // eslint-disable-next-line @next/next/no-img-element
                <img
                  src={coverUrl}
                  alt={title}
                  style={{
                    width: '100%',
                    height: '100%',
                    objectFit: 'cover',
                  }}
                />
              ) : (
                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                    width: '100%',
                    height: '100%',
                    background: 'linear-gradient(180deg, #1a1a1a 0%, #0a0a0a 100%)',
                    padding: 30,
                  }}
                >
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={appLogoUrl}
                    alt="Net Library"
                    style={{
                      width: 80,
                      height: 80,
                      objectFit: 'contain',
                      opacity: 0.8,
                    }}
                  />
                  <div
                    style={{
                      display: 'flex',
                      fontSize: 18,
                      fontWeight: 'bold',
                      color: '#00ff00',
                      fontFamily: 'monospace',
                      marginTop: 16,
                      textAlign: 'center',
                      lineHeight: 1.3,
                      maxWidth: 220,
                    }}
                  >
                    {title.length > 35 ? title.slice(0, 35) + '...' : title}
                  </div>
                </div>
              )}
            </div>
          </div>

          {/* Right side - Info and branding */}
          <div
            style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'flex-start',
              justifyContent: 'center',
              flex: 1,
              height: '100%',
              padding: '40px 50px 40px 30px',
              backgroundColor: 'rgba(0,10,0,0.95)',
              borderLeft: '2px solid rgba(0,255,0,0.2)',
            }}
          >
            {/* Title */}
            <div
              style={{
                display: 'flex',
                fontSize: 42,
                fontWeight: 'bold',
                color: '#00ff00',
                fontFamily: 'monospace',
                lineHeight: 1.2,
                textShadow: '0 0 20px rgba(0,255,0,0.3)',
                marginBottom: 12,
              }}
            >
              {title.length > 40 ? title.slice(0, 40) + '...' : title}
            </div>

            {/* Author */}
            <div
              style={{
                display: 'flex',
                fontSize: 24,
                color: 'rgba(0,255,0,0.6)',
                fontFamily: 'monospace',
                marginBottom: 40,
              }}
            >
              by {author.length > 30 ? author.slice(0, 30) + '...' : author}
            </div>

            {/* Divider */}
            <div
              style={{
                display: 'flex',
                width: 100,
                height: 3,
                backgroundColor: 'rgba(0,255,0,0.3)',
                marginBottom: 40,
              }}
            />

            {/* Branding */}
            <div
              style={{
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                gap: 16,
              }}
            >
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={appLogoUrl}
                alt="Net Library"
                style={{
                  width: 48,
                  height: 48,
                  objectFit: 'contain',
                }}
              />
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'flex-start',
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    fontSize: 22,
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    fontWeight: 'bold',
                    letterSpacing: 2,
                  }}
                >
                  NET LIBRARY
                </div>
                <div
                  style={{
                    display: 'flex',
                    fontSize: 12,
                    color: 'rgba(0,255,0,0.5)',
                    fontFamily: 'monospace',
                    letterSpacing: 1,
                  }}
                >
                  DECENTRALIZED ONCHAIN MEDIA
                </div>
              </div>
            </div>
          </div>
        </div>
      ),
      {
        width: TWITTER_WIDTH,
        height: TWITTER_HEIGHT,
        headers: {
          'Cache-Control': 'no-cache, no-store, must-revalidate',
          'Pragma': 'no-cache',
          'Expires': '0',
        },
      }
    );
  } catch (e: unknown) {
    console.error('Failed to generate Twitter book share image:', e);
    return new Response('Failed to generate image', { status: 500 });
  }
}
src/app/api/share/image/grid/route.tsx
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';

export const runtime = 'edge';
export const maxDuration = 30;

// Cell data with position and cover URL
interface CellData {
  row: number;
  col: number;
  coverUrl: string;
}

// Grid share image - receives data via query params from the share page
// This avoids database access in edge runtime which can fail in production
// Supports two formats:
// - "farcaster" (default): 1200x800 (3:2 aspect ratio)
// - "twitter": 1200x628 (1.91:1 aspect ratio for Twitter summary_large_image)
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const format = searchParams.get('format') || 'farcaster';

    // Get grid data from query params (passed by share page which has DB access)
    const name = searchParams.get('name') || 'Untitled Grid';
    const subtitle = searchParams.get('subtitle') || '';
    const size = parseInt(searchParams.get('size') || '5', 10);
    const creatorUsername = searchParams.get('creator') || 'anon';
    const isMember = searchParams.get('isMember') === 'true';
    const pfpUrl = searchParams.get('pfp') || '';

    // Parse cells with cover URLs (format: "row,col,coverUrl;row,col,coverUrl")
    const cellsParam = searchParams.get('cells') || '';
    const cellsData: CellData[] = [];
    const filledPositions = new Set<string>();

    if (cellsParam) {
      cellsParam.split(';').forEach(cellStr => {
        if (!cellStr) return;
        const parts = cellStr.split(',');
        if (parts.length >= 2) {
          const row = parseInt(parts[0], 10);
          const col = parseInt(parts[1], 10);
          const coverUrl = parts.length > 2 ? decodeURIComponent(parts.slice(2).join(',')) : '';
          cellsData.push({ row, col, coverUrl });
          filledPositions.add(`${row},${col}`);
        }
      });
    }

    // Dimensions based on format
    const isTwitter = format === 'twitter';
    const imageWidth = 1200;
    const imageHeight = isTwitter ? 628 : 800;

    // Build base URL
    const host = request.headers.get('host') || 'netlibrary.neynar.com';
    const protocol = host.includes('localhost') ? 'http' : 'https';
    const appLogoUrl = `${protocol}://${host}/app-logo.png?v=2`;

    const creatorInfo = { username: creatorUsername, isMember };

    console.log(`[grid-share-image] Generating name="${name}", size=${size}, cells=${cellsData.length}, format=${format}`);

    // Responsive font sizes
    const titleLength = name.length;
    const baseTitleSize = isTwitter ? 40 : 56;
    const medTitleSize = isTwitter ? 36 : 48;
    const smallTitleSize = isTwitter ? 32 : 42;
    const titleFontSize = titleLength > 35 ? smallTitleSize : titleLength > 25 ? medTitleSize : baseTitleSize;
    const truncatedName = name.length > 50 ? name.slice(0, 47) + '...' : name;
    const truncatedCreator = creatorInfo.username.length > 15 ? creatorInfo.username.slice(0, 12) + '...' : creatorInfo.username;

    // Calculate cell size for display (up to 5x5 preview)
    const displaySize = Math.min(size, 5);
    const cellGap = isTwitter ? 3 : 4;
    const gridAreaHeight = isTwitter ? 350 : 700;
    const cellSize = Math.floor((gridAreaHeight - (displaySize - 1) * cellGap) / displaySize);

    // Build rows for display - include cover URLs
    const rows: Array<Array<{ row: number; col: number; isFilled: boolean; coverUrl: string }>> = [];
    for (let row = 0; row < displaySize; row++) {
      const rowCells: Array<{ row: number; col: number; isFilled: boolean; coverUrl: string }> = [];
      for (let col = 0; col < displaySize; col++) {
        const cellData = cellsData.find(c => c.row === row && c.col === col);
        rowCells.push({
          row,
          col,
          isFilled: !!cellData,
          coverUrl: cellData?.coverUrl || '',
        });
      }
      rows.push(rowCells);
    }

    return new ImageResponse(
      (
        <div
          style={{
            height: '100%',
            width: '100%',
            display: 'flex',
            position: 'relative',
            backgroundColor: '#000',
          }}
        >
          {/* Grid background */}
          <div
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              gap: cellGap,
            }}
          >
            {rows.map((rowCells, rowIndex) => (
              <div
                key={`row-${rowIndex}`}
                style={{
                  display: 'flex',
                  flexDirection: 'row',
                  gap: cellGap,
                }}
              >
                {rowCells.map((cell) => (
                  <div
                    key={`cell-${cell.row}-${cell.col}`}
                    style={{
                      display: 'flex',
                      width: cellSize,
                      height: cellSize,
                      backgroundColor: cell.isFilled ? 'rgba(0,255,0,0.1)' : 'rgba(0,255,0,0.03)',
                      border: cell.isFilled ? '2px solid rgba(0,255,0,0.5)' : '1px solid rgba(0,255,0,0.1)',
                      alignItems: 'center',
                      justifyContent: 'center',
                      overflow: 'hidden',
                      borderRadius: 4,
                    }}
                  >
                    {cell.isFilled && cell.coverUrl ? (
                      // eslint-disable-next-line @next/next/no-img-element
                      <img
                        src={cell.coverUrl}
                        alt=""
                        style={{
                          width: '100%',
                          height: '100%',
                          objectFit: 'cover',
                        }}
                      />
                    ) : cell.isFilled ? (
                      // Filled but no cover - show placeholder
                      <div
                        style={{
                          display: 'flex',
                          width: '100%',
                          height: '100%',
                          backgroundColor: 'rgba(0,255,0,0.15)',
                          alignItems: 'center',
                          justifyContent: 'center',
                        }}
                      >
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img
                          src={appLogoUrl}
                          alt=""
                          style={{
                            width: '40%',
                            height: '40%',
                            objectFit: 'contain',
                            opacity: 0.4,
                          }}
                        />
                      </div>
                    ) : null}
                  </div>
                ))}
              </div>
            ))}
          </div>

          {/* Dark gradient overlay */}
          <div
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              background: isTwitter
                ? 'linear-gradient(180deg, rgba(0,0,0,0.75) 0%, rgba(0,0,0,0.3) 25%, rgba(0,0,0,0.3) 65%, rgba(0,0,0,0.9) 100%)'
                : 'linear-gradient(180deg, rgba(0,0,0,0.7) 0%, rgba(0,0,0,0.2) 30%, rgba(0,0,0,0.2) 70%, rgba(0,0,0,0.85) 100%)',
              display: 'flex',
            }}
          />

          {/* Top section - Title and subtitle */}
          <div
            style={{
              position: 'absolute',
              top: isTwitter ? 30 : 40,
              left: isTwitter ? 30 : 50,
              right: isTwitter ? 30 : 50,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
            }}
          >
            <div
              style={{
                display: 'flex',
                fontSize: titleFontSize,
                fontWeight: 'bold',
                color: '#00ff00',
                fontFamily: 'monospace',
                textAlign: 'center',
                lineHeight: 1.2,
                textShadow: '0 2px 20px rgba(0,0,0,0.8), 0 0 40px rgba(0,255,0,0.4)',
                maxWidth: 1100,
              }}
            >
              {truncatedName}
            </div>
            {subtitle && (
              <div
                style={{
                  display: 'flex',
                  fontSize: isTwitter ? 18 : 24,
                  color: 'rgba(255,255,255,0.85)',
                  fontFamily: 'monospace',
                  textAlign: 'center',
                  maxWidth: isTwitter ? 800 : 900,
                  marginTop: isTwitter ? 4 : 8,
                  textShadow: '0 2px 10px rgba(0,0,0,0.8)',
                }}
              >
                {subtitle.length > 70 ? subtitle.slice(0, 67) + '...' : subtitle}
              </div>
            )}
          </div>

          {/* Bottom section - Creator info centered */}
          <div
            style={{
              position: 'absolute',
              bottom: 0,
              left: 0,
              right: 0,
              display: 'flex',
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'center',
              padding: isTwitter ? '25px 30px' : '30px 50px',
              background: isTwitter
                ? 'linear-gradient(0deg, rgba(0,10,0,0.98) 0%, rgba(0,10,0,0.9) 60%, transparent 100%)'
                : 'linear-gradient(0deg, rgba(0,10,0,0.95) 0%, rgba(0,10,0,0.8) 70%, transparent 100%)',
            }}
          >
            {/* Creator info - centered */}
            <div
              style={{
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                gap: isTwitter ? 12 : 16,
              }}
            >
              {/* Creator PFP */}
              <div
                style={{
                  display: 'flex',
                  width: isTwitter ? 48 : 60,
                  height: isTwitter ? 48 : 60,
                  borderRadius: isTwitter ? 24 : 30,
                  backgroundColor: 'rgba(0,255,0,0.15)',
                  border: isTwitter ? '2px solid rgba(0,255,0,0.4)' : '3px solid rgba(0,255,0,0.4)',
                  alignItems: 'center',
                  justifyContent: 'center',
                  overflow: 'hidden',
                }}
              >
                {pfpUrl ? (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={pfpUrl}
                    alt=""
                    style={{
                      width: '100%',
                      height: '100%',
                      objectFit: 'cover',
                    }}
                  />
                ) : (
                  // eslint-disable-next-line @next/next/no-img-element
                  <img
                    src={appLogoUrl}
                    alt=""
                    style={{
                      width: isTwitter ? 24 : 30,
                      height: isTwitter ? 24 : 30,
                      objectFit: 'contain',
                      opacity: 0.6,
                    }}
                  />
                )}
              </div>
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'flex-start',
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    fontSize: isTwitter ? 20 : 26,
                    color: '#ffffff',
                    fontFamily: 'monospace',
                    fontWeight: 'bold',
                  }}
                >
                  @{truncatedCreator}
                </div>
                <div
                  style={{
                    display: 'flex',
                    fontSize: isTwitter ? 11 : 14,
                    color: creatorInfo.isMember ? '#00ff00' : 'rgba(0,255,0,0.6)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 2,
                    marginTop: 2,
                  }}
                >
                  {creatorInfo.isMember ? 'MEMBER' : `${size}×${size} Grid`}
                </div>
              </div>
            </div>
          </div>
        </div>
      ),
      {
        width: imageWidth,
        height: imageHeight,
        headers: {
          'Cache-Control': 'no-cache, no-store, must-revalidate',
        },
      }
    );
  } catch (e: unknown) {
    const errorMessage = e instanceof Error ? e.message : String(e);
    const errorStack = e instanceof Error ? e.stack : '';
    console.error('[grid-share-image] Failed to generate:', errorMessage, errorStack);
    return new Response(`Failed to generate image: ${errorMessage}`, { status: 500 });
  }
}
src/app/api/share/image/library-card/route.tsx
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';

export const runtime = 'edge';
export const maxDuration = 30;

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const memberId = searchParams.get('memberId') || '???';
    const ensSubname = searchParams.get('ensSubname') || '';
    const username = searchParams.get('username') || 'member';
    const uploads = searchParams.get('uploads') || '0';
    const dataMb = searchParams.get('dataMb') || '0';
    const upvotes = searchParams.get('upvotes') || '0';

    // Build the absolute URLs
    const host = request.headers.get('host') || 'netlibrary.neynar.com';
    const protocol = host.includes('localhost') ? 'http' : 'https';
    const appLogoUrl = `${protocol}://${host}/app-logo.png?v=2`;

    // Get user's PFP from Farcaster if username provided
    const pfpUrl = `https://api.dicebear.com/7.x/identicon/svg?seed=${username}`;

    return new ImageResponse(
      (
        <div
          style={{
            height: '100%',
            width: '100%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: '#000000',
            padding: 40,
          }}
        >
          {/* Main Card - Matches the app's library card design */}
          <div
            style={{
              display: 'flex',
              flexDirection: 'column',
              width: '100%',
              maxWidth: 1000,
              borderRadius: 24,
              border: '3px solid rgba(0,255,0,0.5)',
              background: 'linear-gradient(135deg, #0a0a0a 0%, #0d1a0d 50%, #0a0a0a 100%)',
              boxShadow: '0 0 60px rgba(0,255,0,0.15)',
              overflow: 'hidden',
              position: 'relative',
            }}
          >
            {/* Corner accents */}
            <div
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: 80,
                height: 80,
                background: 'linear-gradient(135deg, rgba(0,255,0,0.2) 0%, transparent 100%)',
                display: 'flex',
              }}
            />
            <div
              style={{
                position: 'absolute',
                bottom: 0,
                right: 0,
                width: 80,
                height: 80,
                background: 'linear-gradient(-45deg, rgba(0,255,0,0.2) 0%, transparent 100%)',
                display: 'flex',
              }}
            />

            {/* Card Header */}
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                padding: '16px 32px',
                borderBottom: '1px solid rgba(0,255,0,0.3)',
                backgroundColor: 'rgba(0,255,0,0.05)',
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div
                  style={{
                    width: 12,
                    height: 12,
                    borderRadius: '50%',
                    backgroundColor: '#00ff00',
                    boxShadow: '0 0 12px #00ff00',
                    display: 'flex',
                  }}
                />
                <span
                  style={{
                    fontSize: 18,
                    fontFamily: 'monospace',
                    color: 'rgba(0,255,0,0.7)',
                    letterSpacing: 4,
                    textTransform: 'uppercase',
                  }}
                >
                  Net Protocol
                </span>
              </div>
              <span
                style={{
                  fontSize: 18,
                  fontFamily: 'monospace',
                  color: 'rgba(0,255,0,0.5)',
                }}
              >
                Onchain Library Card
              </span>
            </div>

            {/* Main Card Content */}
            <div style={{ display: 'flex', padding: 32, gap: 32 }}>
              {/* Left side - Photo */}
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <div
                  style={{
                    width: 140,
                    height: 170,
                    borderRadius: 12,
                    border: '3px solid rgba(0,255,0,0.5)',
                    overflow: 'hidden',
                    backgroundColor: '#000',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={pfpUrl}
                    alt="avatar"
                    style={{
                      width: '100%',
                      height: '100%',
                      objectFit: 'cover',
                    }}
                  />
                </div>
              </div>

              {/* Middle - Identity Info */}
              <div style={{ display: 'flex', flexDirection: 'column', flex: 1, justifyContent: 'space-between' }}>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  {/* Display Name */}
                  <span
                    style={{
                      fontSize: 48,
                      fontWeight: 'bold',
                      color: '#00ff00',
                      fontFamily: 'monospace',
                      lineHeight: 1,
                    }}
                  >
                    {username}
                  </span>
                  {/* Username handle */}
                  <span
                    style={{
                      fontSize: 28,
                      color: 'rgba(0,255,0,0.6)',
                      fontFamily: 'monospace',
                      marginTop: 4,
                    }}
                  >
                    @{username}
                  </span>

                  {/* Member badge and ENS subname */}
                  <div style={{ display: 'flex', flexDirection: 'column', marginTop: 20, gap: 4 }}>
                    <span
                      style={{
                        fontSize: 18,
                        fontWeight: 'bold',
                        color: '#00ff00',
                        fontFamily: 'monospace',
                        letterSpacing: 3,
                      }}
                    >
                      MEMBER #{memberId}
                    </span>
                    {ensSubname && (
                      <span
                        style={{
                          fontSize: 16,
                          color: 'rgba(0,255,0,0.7)',
                          fontFamily: 'monospace',
                        }}
                      >
                        {ensSubname}
                      </span>
                    )}
                  </div>
                </div>
              </div>

              {/* Right side - Logo watermark */}
              <div
                style={{
                  display: 'flex',
                  alignItems: 'flex-start',
                  justifyContent: 'center',
                  width: 160,
                  opacity: 0.3,
                }}
              >
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={appLogoUrl}
                  alt="Net Library"
                  style={{
                    width: 140,
                    height: 140,
                    objectFit: 'contain',
                  }}
                />
              </div>
            </div>

            {/* Divider with circuit pattern */}
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                padding: '0 32px',
                position: 'relative',
              }}
            >
              <div
                style={{
                  display: 'flex',
                  width: '100%',
                  height: 1,
                  backgroundColor: 'rgba(0,255,0,0.2)',
                }}
              />
              {/* Circuit dots */}
              <div
                style={{
                  position: 'absolute',
                  left: 32,
                  width: 8,
                  height: 8,
                  borderRadius: '50%',
                  backgroundColor: 'rgba(0,255,0,0.4)',
                  display: 'flex',
                }}
              />
              <div
                style={{
                  position: 'absolute',
                  right: 32,
                  width: 8,
                  height: 8,
                  borderRadius: '50%',
                  backgroundColor: 'rgba(0,255,0,0.4)',
                  display: 'flex',
                }}
              />
            </div>

            {/* Stats Grid */}
            <div
              style={{
                display: 'flex',
                padding: '24px 32px',
                gap: 16,
              }}
            >
              {/* Uploads */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flex: 1,
                  padding: 16,
                  borderRadius: 12,
                  backgroundColor: 'rgba(0,0,0,0.5)',
                  border: '1px solid rgba(0,255,0,0.2)',
                }}
              >
                <span
                  style={{
                    fontSize: 42,
                    fontWeight: 'bold',
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    lineHeight: 1,
                  }}
                >
                  {uploads}
                </span>
                <span
                  style={{
                    fontSize: 14,
                    color: 'rgba(128,128,128,1)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 2,
                    marginTop: 4,
                  }}
                >
                  Uploads
                </span>
              </div>

              {/* Data */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flex: 1,
                  padding: 16,
                  borderRadius: 12,
                  backgroundColor: 'rgba(0,0,0,0.5)',
                  border: '1px solid rgba(0,255,0,0.2)',
                }}
              >
                <span
                  style={{
                    fontSize: 42,
                    fontWeight: 'bold',
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    lineHeight: 1,
                  }}
                >
                  {dataMb}MB
                </span>
                <span
                  style={{
                    fontSize: 14,
                    color: 'rgba(128,128,128,1)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 2,
                    marginTop: 4,
                  }}
                >
                  Data
                </span>
              </div>

              {/* Upvotes */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flex: 1,
                  padding: 16,
                  borderRadius: 12,
                  backgroundColor: 'rgba(0,0,0,0.5)',
                  border: '1px solid rgba(0,255,0,0.2)',
                }}
              >
                <span
                  style={{
                    fontSize: 42,
                    fontWeight: 'bold',
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    lineHeight: 1,
                  }}
                >
                  ▲{upvotes}
                </span>
                <span
                  style={{
                    fontSize: 14,
                    color: 'rgba(128,128,128,1)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 2,
                    marginTop: 4,
                  }}
                >
                  Upvotes
                </span>
              </div>
            </div>

            {/* Card Footer */}
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                padding: '16px 32px',
                borderTop: '1px solid rgba(0,255,0,0.2)',
                backgroundColor: 'rgba(0,0,0,0.3)',
              }}
            >
              <span
                style={{
                  fontSize: 20,
                  fontFamily: 'monospace',
                  color: 'rgba(0,255,0,0.5)',
                  letterSpacing: 4,
                }}
              >
                MEMBER-{memberId}
              </span>
              <span
                style={{
                  fontSize: 14,
                  fontFamily: 'monospace',
                  color: 'rgba(0,255,0,0.3)',
                  letterSpacing: 2,
                }}
              >
                netlibrary.neynar.com
              </span>
            </div>
          </div>
        </div>
      ),
      {
        width: 1200,
        height: 800, // 3:2 aspect ratio for Farcaster
        headers: {
          'Cache-Control': 'no-cache, no-store, must-revalidate',
          'Pragma': 'no-cache',
          'Expires': '0',
        },
      }
    );
  } catch (e: unknown) {
    console.error('Failed to generate library card image:', e);
    return new Response('Failed to generate image', { status: 500 });
  }
}
src/app/api/share/image/library-card-nft/route.tsx
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';

export const runtime = 'edge';
export const maxDuration = 30;

// Library card share image - matches the in-app card design exactly
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const memberId = searchParams.get('memberId') || '???';
    const ensSubname = searchParams.get('ensSubname') || '';
    // username = Farcaster handle (e.g. "cherylfromnet") shown as @handle
    const username = searchParams.get('username') || 'member';
    // displayName = human-readable name (e.g. "Cheryl") shown as the big title
    // Falls back to username for backwards compatibility when not provided
    const displayName = searchParams.get('displayName') || username;
    const uploads = searchParams.get('uploads') || '0';
    const dataMb = searchParams.get('dataMb') || '0';
    const upvotes = searchParams.get('upvotes') || '0';
    // Accept pfpUrl as parameter for actual user PFP
    const pfpUrlParam = searchParams.get('pfpUrl');
    // Platform verification status
    const fcVerified = searchParams.get('fcVerified') === 'true';
    const baseVerified = searchParams.get('baseVerified') === 'true';
    const webVerified = searchParams.get('webVerified') === 'true';
    // Net Link status
    const hasNetLink = searchParams.get('hasNetLink') === 'true';
    const netLinkLabel = searchParams.get('netLinkLabel') || '';

    // Build the absolute URLs
    const host = request.headers.get('host') || 'netlibrary.neynar.com';
    const protocol = host.includes('localhost') ? 'http' : 'https';
    const appLogoUrl = `${protocol}://${host}/app-logo.png?v=2`;

    // Use provided PFP or fall back to dicebear
    const pfpUrl = pfpUrlParam || `https://api.dicebear.com/7.x/identicon/svg?seed=${username}`;

    return new ImageResponse(
      (
        <div
          style={{
            height: '100%',
            width: '100%',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: '#000000',
            padding: 40,
          }}
        >
          {/* Main Card - Matches the app's library card design */}
          <div
            style={{
              display: 'flex',
              flexDirection: 'column',
              width: '100%',
              maxWidth: 1000,
              borderRadius: 24,
              border: '3px solid rgba(0,255,0,0.5)',
              background: 'linear-gradient(135deg, #0a0a0a 0%, #0d1a0d 50%, #0a0a0a 100%)',
              boxShadow: '0 0 60px rgba(0,255,0,0.15)',
              overflow: 'hidden',
              position: 'relative',
            }}
          >
            {/* Corner accents */}
            <div
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: 80,
                height: 80,
                background: 'linear-gradient(135deg, rgba(0,255,0,0.2) 0%, transparent 100%)',
                display: 'flex',
              }}
            />
            <div
              style={{
                position: 'absolute',
                bottom: 0,
                right: 0,
                width: 80,
                height: 80,
                background: 'linear-gradient(-45deg, rgba(0,255,0,0.2) 0%, transparent 100%)',
                display: 'flex',
              }}
            />

            {/* Card Header */}
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                padding: '16px 32px',
                borderBottom: '1px solid rgba(0,255,0,0.3)',
                backgroundColor: 'rgba(0,255,0,0.05)',
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                <div
                  style={{
                    width: 12,
                    height: 12,
                    borderRadius: '50%',
                    backgroundColor: '#00ff00',
                    boxShadow: '0 0 12px #00ff00',
                    display: 'flex',
                  }}
                />
                <span
                  style={{
                    fontSize: 18,
                    fontFamily: 'monospace',
                    color: 'rgba(0,255,0,0.7)',
                    letterSpacing: 4,
                    textTransform: 'uppercase',
                  }}
                >
                  Net Protocol
                </span>
              </div>
              <span
                style={{
                  fontSize: 18,
                  fontFamily: 'monospace',
                  color: 'rgba(0,255,0,0.5)',
                }}
              >
                Onchain Library Card
              </span>
            </div>

            {/* Main Card Content */}
            <div style={{ display: 'flex', padding: 32, gap: 32 }}>
              {/* Left side - Photo with Net Link status */}
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                <div
                  style={{
                    width: 140,
                    height: 170,
                    borderRadius: 12,
                    border: '3px solid rgba(0,255,0,0.5)',
                    overflow: 'hidden',
                    backgroundColor: '#000',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                  }}
                >
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={pfpUrl}
                    alt="avatar"
                    style={{
                      width: '100%',
                      height: '100%',
                      objectFit: 'cover',
                    }}
                  />
                </div>
                {/* Net Link status below photo */}
                <span
                  style={{
                    marginTop: 8,
                    fontSize: 14,
                    fontFamily: 'monospace',
                    color: hasNetLink ? '#00ff00' : 'rgba(128,128,128,0.6)',
                  }}
                >
                  {hasNetLink ? `🔗 ${netLinkLabel || 'Net Link'}` : '🔗 unlinked'}
                </span>
              </div>

              {/* Middle - Identity Info */}
              <div style={{ display: 'flex', flexDirection: 'column', flex: 1, justifyContent: 'space-between' }}>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  {/* Display Name */}
                  <span
                    style={{
                      fontSize: 48,
                      fontWeight: 'bold',
                      color: '#00ff00',
                      fontFamily: 'monospace',
                      lineHeight: 1,
                    }}
                  >
                    {displayName}
                  </span>
                  {/* Username handle */}
                  <span
                    style={{
                      fontSize: 28,
                      color: 'rgba(0,255,0,0.6)',
                      fontFamily: 'monospace',
                      marginTop: 4,
                    }}
                  >
                    @{username}
                  </span>

                  {/* Member badge with platform verification */}
                  <div style={{ display: 'flex', flexDirection: 'column', marginTop: 20, gap: 8 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                      <span
                        style={{
                          fontSize: 18,
                          fontWeight: 'bold',
                          color: '#00ff00',
                          fontFamily: 'monospace',
                          letterSpacing: 3,
                        }}
                      >
                        MEMBER #{memberId}
                      </span>
                      {/* Platform verification badges */}
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <span
                          style={{
                            fontSize: 14,
                            fontFamily: 'monospace',
                            color: fcVerified ? '#a78bfa' : 'rgba(167,139,250,0.3)',
                          }}
                        >
                          FC{fcVerified ? '✓' : '✕'}
                        </span>
                        <span style={{ fontSize: 10, color: 'rgba(128,128,128,0.5)' }}>/</span>
                        <span
                          style={{
                            fontSize: 14,
                            fontFamily: 'monospace',
                            color: baseVerified ? '#60a5fa' : 'rgba(96,165,250,0.3)',
                          }}
                        >
                          Base{baseVerified ? '✓' : '✕'}
                        </span>
                        <span style={{ fontSize: 10, color: 'rgba(128,128,128,0.5)' }}>/</span>
                        <span
                          style={{
                            fontSize: 14,
                            fontFamily: 'monospace',
                            color: webVerified ? '#facc15' : 'rgba(250,204,21,0.3)',
                          }}
                        >
                          Web{webVerified ? '✓' : '✕'}
                        </span>
                      </div>
                    </div>
                    {ensSubname && (
                      <span
                        style={{
                          fontSize: 16,
                          color: 'rgba(0,255,0,0.7)',
                          fontFamily: 'monospace',
                        }}
                      >
                        {ensSubname}
                      </span>
                    )}
                  </div>
                </div>
              </div>

              {/* Right side - Logo watermark */}
              <div
                style={{
                  display: 'flex',
                  alignItems: 'flex-start',
                  justifyContent: 'center',
                  width: 160,
                  opacity: 0.3,
                }}
              >
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={appLogoUrl}
                  alt="Net Library"
                  style={{
                    width: 140,
                    height: 140,
                    objectFit: 'contain',
                  }}
                />
              </div>
            </div>

            {/* Divider with circuit pattern */}
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                padding: '0 32px',
                position: 'relative',
              }}
            >
              <div
                style={{
                  display: 'flex',
                  width: '100%',
                  height: 1,
                  backgroundColor: 'rgba(0,255,0,0.2)',
                }}
              />
              {/* Circuit dots */}
              <div
                style={{
                  position: 'absolute',
                  left: 32,
                  width: 8,
                  height: 8,
                  borderRadius: '50%',
                  backgroundColor: 'rgba(0,255,0,0.4)',
                  display: 'flex',
                }}
              />
              <div
                style={{
                  position: 'absolute',
                  right: 32,
                  width: 8,
                  height: 8,
                  borderRadius: '50%',
                  backgroundColor: 'rgba(0,255,0,0.4)',
                  display: 'flex',
                }}
              />
            </div>

            {/* Stats Grid */}
            <div
              style={{
                display: 'flex',
                padding: '24px 32px',
                gap: 16,
              }}
            >
              {/* Uploads */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flex: 1,
                  padding: 16,
                  borderRadius: 12,
                  backgroundColor: 'rgba(0,0,0,0.5)',
                  border: '1px solid rgba(0,255,0,0.2)',
                }}
              >
                <span
                  style={{
                    fontSize: 42,
                    fontWeight: 'bold',
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    lineHeight: 1,
                  }}
                >
                  {uploads}
                </span>
                <span
                  style={{
                    fontSize: 14,
                    color: 'rgba(128,128,128,1)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 2,
                    marginTop: 4,
                  }}
                >
                  Uploads
                </span>
              </div>

              {/* Data */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flex: 1,
                  padding: 16,
                  borderRadius: 12,
                  backgroundColor: 'rgba(0,0,0,0.5)',
                  border: '1px solid rgba(0,255,0,0.2)',
                }}
              >
                <span
                  style={{
                    fontSize: 42,
                    fontWeight: 'bold',
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    lineHeight: 1,
                  }}
                >
                  {dataMb}MB
                </span>
                <span
                  style={{
                    fontSize: 14,
                    color: 'rgba(128,128,128,1)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 2,
                    marginTop: 4,
                  }}
                >
                  Data
                </span>
              </div>

              {/* Upvotes */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flex: 1,
                  padding: 16,
                  borderRadius: 12,
                  backgroundColor: 'rgba(0,0,0,0.5)',
                  border: '1px solid rgba(0,255,0,0.2)',
                }}
              >
                <span
                  style={{
                    fontSize: 42,
                    fontWeight: 'bold',
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    lineHeight: 1,
                  }}
                >
                  ▲{upvotes}
                </span>
                <span
                  style={{
                    fontSize: 14,
                    color: 'rgba(128,128,128,1)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 2,
                    marginTop: 4,
                  }}
                >
                  Upvotes
                </span>
              </div>
            </div>

            {/* Card Footer */}
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                padding: '16px 32px',
                borderTop: '1px solid rgba(0,255,0,0.2)',
                backgroundColor: 'rgba(0,0,0,0.3)',
              }}
            >
              <span
                style={{
                  fontSize: 20,
                  fontFamily: 'monospace',
                  color: 'rgba(0,255,0,0.5)',
                  letterSpacing: 4,
                }}
              >
                MEMBER-{memberId}
              </span>
              <span
                style={{
                  fontSize: 14,
                  fontFamily: 'monospace',
                  color: 'rgba(0,255,0,0.3)',
                  letterSpacing: 2,
                }}
              >
                netlibrary.neynar.com
              </span>
            </div>
          </div>
        </div>
      ),
      {
        width: 1200,
        height: 800, // 3:2 aspect ratio for Farcaster
        headers: {
          'Cache-Control': 'no-cache, no-store, must-revalidate',
          'Pragma': 'no-cache',
          'Expires': '0',
        },
      }
    );
  } catch (e: unknown) {
    console.error('Failed to generate library card image:', e);
    return new Response('Failed to generate image', { status: 500 });
  }
}
src/app/api/share/image/social/route.tsx
import { ImageResponse } from "next/og";
import { NextRequest } from "next/server";

export const runtime = "edge";
export const maxDuration = 30;

// Platform display info
const PLATFORM_INFO: Record<string, {
  name: string;
  icon: string;
  color: string;
}> = {
  farcaster: { name: "Farcaster", icon: "F", color: "#8B5CF6" },
  twitter: { name: "Twitter/X", icon: "X", color: "#1DA1F2" },
  youtube: { name: "YouTube", icon: "YT", color: "#FF0000" },
  instagram: { name: "Instagram", icon: "IG", color: "#E1306C" },
  tiktok: { name: "TikTok", icon: "TT", color: "#00F2EA" },
  reddit: { name: "Reddit", icon: "R", color: "#FF4500" },
  bluesky: { name: "Bluesky", icon: "BS", color: "#0085FF" },
  threads: { name: "Threads", icon: "TH", color: "#CCCCCC" },
  linkedin: { name: "LinkedIn", icon: "LI", color: "#0077B5" },
};

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const platform = searchParams.get("platform") || "twitter";
    const author = searchParams.get("author") || "Unknown";
    const text = searchParams.get("text") || "";
    const receiptUrl = searchParams.get("receiptUrl") || "";

    // Build the absolute URL for the app logo
    const host = request.headers.get("host") || "netlibrary.neynar.com";
    const protocol = host.includes("localhost") ? "http" : "https";
    const appLogoUrl = `${protocol}://${host}/app-logo.png?v=2`;

    const platformInfo = PLATFORM_INFO[platform] || PLATFORM_INFO.twitter;
    const platformColor = platformInfo.color;
    const platformName = platformInfo.name;
    const platformIcon = platformInfo.icon;

    // Truncate text if too long
    const maxTextLength = 300;
    const displayText = text.length > maxTextLength
      ? text.slice(0, maxTextLength) + "..."
      : text;

    return new ImageResponse(
      (
        <div
          style={{
            height: "100%",
            width: "100%",
            display: "flex",
            flexDirection: "column",
            backgroundColor: "#000000",
            fontFamily: "monospace",
          }}
        >
          {/* Receipt Header - Platform + Badge */}
          <div
            style={{
              display: "flex",
              flexDirection: "row",
              alignItems: "center",
              justifyContent: "space-between",
              padding: "24px 40px",
              backgroundColor: "rgba(0,255,0,0.05)",
              borderBottom: "2px dashed rgba(0,255,0,0.3)",
            }}
          >
            {/* Platform badge */}
            <div
              style={{
                display: "flex",
                alignItems: "center",
                gap: 16,
                padding: "12px 20px",
                backgroundColor: `${platformColor}20`,
                borderRadius: 12,
                border: `2px solid ${platformColor}40`,
              }}
            >
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  width: 40,
                  height: 40,
                  borderRadius: 8,
                  backgroundColor: platformColor,
                  color: "#ffffff",
                  fontSize: 18,
                  fontWeight: "bold",
                }}
              >
                {platformIcon}
              </div>
              <span style={{ fontSize: 24, color: platformColor, fontWeight: "bold" }}>
                {platformName}
              </span>
            </div>

            {/* Archive badge */}
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                alignItems: "flex-end",
              }}
            >
              <span style={{ fontSize: 18, color: "#00ff00", letterSpacing: 3, fontWeight: "bold" }}>
                ARCHIVED
              </span>
              <span style={{ fontSize: 12, color: "rgba(0,255,0,0.5)", marginTop: 4 }}>
                PERMANENT RECEIPT
              </span>
            </div>
          </div>

          {/* Main Content Area */}
          <div
            style={{
              display: "flex",
              flex: 1,
              flexDirection: "row",
              padding: "32px 40px",
              gap: 32,
            }}
          >
            {/* Left - Receipt preview (if available) */}
            {receiptUrl && (
              <div
                style={{
                  display: "flex",
                  width: 300,
                  height: 450,
                  borderRadius: 16,
                  border: "3px solid rgba(0,255,0,0.3)",
                  backgroundColor: "#0a0a0a",
                  overflow: "hidden",
                  boxShadow: "0 10px 40px rgba(0,0,0,0.5), 0 0 30px rgba(0,255,0,0.1)",
                }}
              >
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={receiptUrl}
                  alt=""
                  style={{
                    width: "100%",
                    height: "100%",
                    objectFit: "cover",
                  }}
                />
              </div>
            )}

            {/* Right - Content info */}
            <div
              style={{
                display: "flex",
                flex: 1,
                flexDirection: "column",
                justifyContent: "center",
              }}
            >
              {/* Author info */}
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 12,
                  marginBottom: 24,
                }}
              >
                <div
                  style={{
                    display: "flex",
                    width: 56,
                    height: 56,
                    borderRadius: 28,
                    backgroundColor: "#333",
                    alignItems: "center",
                    justifyContent: "center",
                    fontSize: 28,
                    border: `3px solid ${platformColor}60`,
                  }}
                >
                  @
                </div>
                <div style={{ display: "flex", flexDirection: "column" }}>
                  <span
                    style={{
                      fontSize: 28,
                      fontWeight: "bold",
                      color: "#ffffff",
                    }}
                  >
                    @{author.length > 25 ? author.slice(0, 25) + "..." : author}
                  </span>
                  <span style={{ fontSize: 16, color: "rgba(255,255,255,0.5)", marginTop: 4 }}>
                    on {platformName}
                  </span>
                </div>
              </div>

              {/* Post text preview */}
              {displayText && (
                <div
                  style={{
                    display: "flex",
                    flex: 1,
                    backgroundColor: "rgba(0,255,0,0.03)",
                    borderRadius: 16,
                    border: "2px solid rgba(0,255,0,0.15)",
                    padding: 24,
                    maxHeight: 280,
                    overflow: "hidden",
                  }}
                >
                  <span
                    style={{
                      fontSize: 22,
                      color: "rgba(255,255,255,0.9)",
                      lineHeight: 1.5,
                      whiteSpace: "pre-wrap",
                    }}
                  >
                    {displayText}
                  </span>
                </div>
              )}
            </div>
          </div>

          {/* Footer - Branding */}
          <div
            style={{
              display: "flex",
              flexDirection: "row",
              alignItems: "center",
              justifyContent: "space-between",
              padding: "20px 40px",
              backgroundColor: "rgba(0,20,0,0.95)",
              borderTop: "2px dashed rgba(0,255,0,0.3)",
            }}
          >
            {/* Left - CTA */}
            <div style={{ display: "flex", flexDirection: "column" }}>
              <span style={{ fontSize: 16, color: "rgba(0,255,0,0.7)" }}>
                Tap to view the full archived receipt
              </span>
            </div>

            {/* Right - Net Library branding */}
            <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={appLogoUrl}
                alt="Net Library"
                style={{ width: 48, height: 48, objectFit: "contain" }}
              />
              <div style={{ display: "flex", flexDirection: "column" }}>
                <span
                  style={{
                    fontSize: 20,
                    color: "#00ff00",
                    fontWeight: "bold",
                    letterSpacing: 2,
                  }}
                >
                  NET LIBRARY
                </span>
                <span style={{ fontSize: 11, color: "rgba(0,255,0,0.5)", letterSpacing: 1 }}>
                  POWERED BY NET PROTOCOL
                </span>
              </div>
            </div>
          </div>

          {/* Receipt footer with perforated edge effect */}
          <div
            style={{
              display: "flex",
              justifyContent: "center",
              padding: "10px 0",
              backgroundColor: "rgba(0,255,0,0.05)",
              borderTop: "2px dashed rgba(0,255,0,0.4)",
            }}
          >
            <span style={{ fontSize: 11, color: "rgba(0,255,0,0.4)", letterSpacing: 3 }}>
              HYPERLINKED RECEIPT • PERMANENT ARCHIVE
            </span>
          </div>
        </div>
      ),
      {
        width: 1200,
        height: 800, // 3:2 aspect ratio for Farcaster
        headers: {
          "Cache-Control": "no-cache, no-store, must-revalidate",
        },
      }
    );
  } catch (e: unknown) {
    console.error("Failed to generate social share image:", e);
    return new Response("Failed to generate image", { status: 500 });
  }
}
src/app/api/share/image/social-twitter/route.tsx
import { ImageResponse } from "next/og";
import { NextRequest } from "next/server";

export const runtime = "edge";
export const maxDuration = 30;

// Twitter summary_large_image cards use 1.91:1 aspect ratio (1200x628)
const TWITTER_WIDTH = 1200;
const TWITTER_HEIGHT = 628;

// Platform display info
const PLATFORM_INFO: Record<string, {
  name: string;
  icon: string;
  color: string;
}> = {
  farcaster: { name: "Farcaster", icon: "F", color: "#8B5CF6" },
  twitter: { name: "Twitter/X", icon: "X", color: "#1DA1F2" },
  youtube: { name: "YouTube", icon: "YT", color: "#FF0000" },
  instagram: { name: "Instagram", icon: "IG", color: "#E1306C" },
  tiktok: { name: "TikTok", icon: "TT", color: "#00F2EA" },
  reddit: { name: "Reddit", icon: "R", color: "#FF4500" },
  bluesky: { name: "Bluesky", icon: "BS", color: "#0085FF" },
  threads: { name: "Threads", icon: "TH", color: "#CCCCCC" },
  linkedin: { name: "LinkedIn", icon: "LI", color: "#0077B5" },
};

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const platform = searchParams.get("platform") || "twitter";
    const author = searchParams.get("author") || "Unknown";
    const text = searchParams.get("text") || "";
    const receiptUrl = searchParams.get("receiptUrl") || "";

    // Build the absolute URL for the app logo
    const host = request.headers.get("host") || "netlibrary.neynar.com";
    const protocol = host.includes("localhost") ? "http" : "https";
    const appLogoUrl = `${protocol}://${host}/app-logo.png?v=2`;

    const platformInfo = PLATFORM_INFO[platform] || PLATFORM_INFO.twitter;
    const platformColor = platformInfo.color;
    const platformName = platformInfo.name;
    const platformIcon = platformInfo.icon;

    // Truncate text for Twitter's narrower format
    const maxTextLength = 180;
    const displayText = text.length > maxTextLength
      ? text.slice(0, maxTextLength) + "..."
      : text;

    return new ImageResponse(
      (
        <div
          style={{
            height: "100%",
            width: "100%",
            display: "flex",
            flexDirection: "row",
            backgroundColor: "#000000",
            fontFamily: "monospace",
          }}
        >
          {/* Left - Receipt preview */}
          <div
            style={{
              display: "flex",
              width: 350,
              height: "100%",
              alignItems: "center",
              justifyContent: "center",
              backgroundColor: "rgba(0,255,0,0.02)",
              borderRight: "2px dashed rgba(0,255,0,0.3)",
              padding: 20,
            }}
          >
            {receiptUrl ? (
              <div
                style={{
                  display: "flex",
                  width: 280,
                  height: 500,
                  borderRadius: 12,
                  border: "3px solid rgba(0,255,0,0.3)",
                  overflow: "hidden",
                  boxShadow: "0 10px 40px rgba(0,0,0,0.5)",
                }}
              >
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={receiptUrl}
                  alt=""
                  style={{
                    width: "100%",
                    height: "100%",
                    objectFit: "cover",
                  }}
                />
              </div>
            ) : (
              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  justifyContent: "center",
                  width: 280,
                  height: 400,
                  borderRadius: 12,
                  border: "3px dashed rgba(0,255,0,0.3)",
                  backgroundColor: "rgba(0,255,0,0.05)",
                }}
              >
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={appLogoUrl}
                  alt="Net Library"
                  style={{ width: 80, height: 80, opacity: 0.5 }}
                />
                <span style={{ fontSize: 14, color: "rgba(0,255,0,0.5)", marginTop: 16 }}>
                  Social Receipt
                </span>
              </div>
            )}
          </div>

          {/* Right - Content info */}
          <div
            style={{
              display: "flex",
              flex: 1,
              flexDirection: "column",
              justifyContent: "space-between",
              padding: "30px 40px",
            }}
          >
            {/* Top - Platform + Author */}
            <div style={{ display: "flex", flexDirection: "column" }}>
              {/* Platform badge */}
              <div
                style={{
                  display: "flex",
                  alignItems: "center",
                  gap: 12,
                  padding: "10px 16px",
                  backgroundColor: `${platformColor}20`,
                  borderRadius: 10,
                  border: `2px solid ${platformColor}40`,
                  width: "fit-content",
                  marginBottom: 20,
                }}
              >
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                    width: 32,
                    height: 32,
                    borderRadius: 6,
                    backgroundColor: platformColor,
                    color: "#ffffff",
                    fontSize: 14,
                    fontWeight: "bold",
                  }}
                >
                  {platformIcon}
                </div>
                <span style={{ fontSize: 18, color: platformColor, fontWeight: "bold" }}>
                  {platformName}
                </span>
              </div>

              {/* Author */}
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                <div
                  style={{
                    display: "flex",
                    width: 48,
                    height: 48,
                    borderRadius: 24,
                    backgroundColor: "#333",
                    alignItems: "center",
                    justifyContent: "center",
                    fontSize: 24,
                    border: `3px solid ${platformColor}60`,
                  }}
                >
                  @
                </div>
                <span style={{ fontSize: 24, fontWeight: "bold", color: "#ffffff" }}>
                  @{author.length > 20 ? author.slice(0, 20) + "..." : author}
                </span>
              </div>

              {/* Text preview */}
              {displayText && (
                <div
                  style={{
                    display: "flex",
                    marginTop: 20,
                    padding: 20,
                    backgroundColor: "rgba(0,255,0,0.03)",
                    borderRadius: 12,
                    border: "2px solid rgba(0,255,0,0.15)",
                    maxHeight: 200,
                    overflow: "hidden",
                  }}
                >
                  <span
                    style={{
                      fontSize: 18,
                      color: "rgba(255,255,255,0.85)",
                      lineHeight: 1.4,
                    }}
                  >
                    {displayText}
                  </span>
                </div>
              )}
            </div>

            {/* Bottom - Branding */}
            <div
              style={{
                display: "flex",
                alignItems: "center",
                justifyContent: "space-between",
                borderTop: "2px dashed rgba(0,255,0,0.3)",
                paddingTop: 20,
              }}
            >
              <span
                style={{
                  fontSize: 12,
                  color: "rgba(0,255,0,0.5)",
                  letterSpacing: 2,
                }}
              >
                ARCHIVED ON NET LIBRARY
              </span>
              <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                {/* eslint-disable-next-line @next/next/no-img-element */}
                <img
                  src={appLogoUrl}
                  alt="Net Library"
                  style={{ width: 36, height: 36, objectFit: "contain" }}
                />
                <div style={{ display: "flex", flexDirection: "column" }}>
                  <span
                    style={{
                      fontSize: 16,
                      color: "#00ff00",
                      fontWeight: "bold",
                      letterSpacing: 1,
                    }}
                  >
                    NET LIBRARY
                  </span>
                  <span style={{ fontSize: 9, color: "rgba(0,255,0,0.5)" }}>
                    POWERED BY NET PROTOCOL
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      ),
      {
        width: TWITTER_WIDTH,
        height: TWITTER_HEIGHT,
        headers: {
          "Cache-Control": "no-cache, no-store, must-revalidate",
        },
      }
    );
  } catch (e: unknown) {
    console.error("Failed to generate social Twitter share image:", e);
    return new Response("Failed to generate image", { status: 500 });
  }
}
src/app/api/share/image/stack/route.tsx
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';

export const runtime = 'edge';
export const maxDuration = 30; // Increase timeout for image generation

// Stack share image - shows stack name, item count, and preview
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const name = searchParams.get('name') || 'Untitled Stack';
    const itemCount = parseInt(searchParams.get('itemCount') || '0', 10);
    const ownerUsername = searchParams.get('owner') || 'anon';
    const description = searchParams.get('description') || '';

    // Build the absolute URL for the app logo
    const host = request.headers.get('host') || 'netlibrary.neynar.com';
    const protocol = host.includes('localhost') ? 'http' : 'https';
    const appLogoUrl = `${protocol}://${host}/app-logo.png?v=2`;

    // Determine font sizes based on title length for responsive layout
    const titleLength = name.length;
    const titleFontSize = titleLength > 35 ? 48 : titleLength > 25 ? 56 : 64;
    const truncatedName = name.length > 50 ? name.slice(0, 47) + '...' : name;
    const truncatedDesc = description ? (description.length > 100 ? description.slice(0, 97) + '...' : description) : '';
    const truncatedOwner = ownerUsername.length > 15 ? ownerUsername.slice(0, 12) + '...' : ownerUsername;

    return new ImageResponse(
      (
        <div
          style={{
            height: '100%',
            width: '100%',
            display: 'flex',
            flexDirection: 'column',
            backgroundColor: '#000000',
            padding: '50px 50px 120px 50px', // Extra bottom padding for footer
          }}
        >
          {/* Main content area - fixed height to prevent overflow */}
          <div
            style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              flex: 1,
              gap: 20,
            }}
          >
            {/* Stack name - responsive size */}
            <div
              style={{
                display: 'flex',
                fontSize: titleFontSize,
                fontWeight: 'bold',
                color: '#00ff00',
                fontFamily: 'monospace',
                textAlign: 'center',
                lineHeight: 1.2,
                textShadow: '0 0 30px rgba(0,255,0,0.4)',
                maxWidth: 1100,
              }}
            >
              {truncatedName}
            </div>

            {/* Description */}
            {truncatedDesc && (
              <div
                style={{
                  display: 'flex',
                  fontSize: 26,
                  color: 'rgba(255,255,255,0.7)',
                  fontFamily: 'monospace',
                  textAlign: 'center',
                  maxWidth: 1000,
                  lineHeight: 1.3,
                }}
              >
                {truncatedDesc}
              </div>
            )}

            {/* Stats row */}
            <div
              style={{
                display: 'flex',
                flexDirection: 'row',
                alignItems: 'center',
                gap: 50,
                marginTop: 24,
              }}
            >
              {/* Item count */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    fontSize: 72,
                    fontWeight: 'bold',
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    textShadow: '0 0 20px rgba(0,255,0,0.3)',
                  }}
                >
                  {itemCount}
                </div>
                <div
                  style={{
                    display: 'flex',
                    fontSize: 20,
                    color: 'rgba(0,255,0,0.6)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 3,
                  }}
                >
                  {itemCount === 1 ? 'Item' : 'Items'}
                </div>
              </div>

              {/* Divider */}
              <div
                style={{
                  display: 'flex',
                  width: 2,
                  height: 80,
                  backgroundColor: 'rgba(0,255,0,0.3)',
                }}
              />

              {/* Curator */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    fontSize: 32,
                    color: 'rgba(255,255,255,0.9)',
                    fontFamily: 'monospace',
                    fontWeight: 'bold',
                  }}
                >
                  @{truncatedOwner}
                </div>
                <div
                  style={{
                    display: 'flex',
                    fontSize: 18,
                    color: 'rgba(0,255,0,0.5)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 3,
                    marginTop: 4,
                  }}
                >
                  Curator
                </div>
              </div>
            </div>
          </div>

          {/* Bottom branding - fixed position, simplified */}
          <div
            style={{
              display: 'flex',
              flexDirection: 'row',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 16,
              position: 'absolute',
              bottom: 40,
              left: 0,
              right: 0,
            }}
          >
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img
              src={appLogoUrl}
              alt="Net Library"
              style={{
                width: 44,
                height: 44,
                objectFit: 'contain',
              }}
            />
            <div
              style={{
                display: 'flex',
                fontSize: 22,
                color: '#00ff00',
                fontFamily: 'monospace',
                fontWeight: 'bold',
                letterSpacing: 4,
              }}
            >
              NET LIBRARY
            </div>
          </div>
        </div>
      ),
      {
        width: 1200,
        height: 800, // 3:2 aspect ratio for Farcaster
        headers: {
          'Cache-Control': 'no-cache, no-store, must-revalidate',
        },
      }
    );
  } catch (e: unknown) {
    console.error('Failed to generate stack share image:', e);
    return new Response('Failed to generate image', { status: 500 });
  }
}
src/app/api/share/image/stats/route.tsx
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';

export const runtime = 'edge';
export const maxDuration = 30;

// Stats share image - displays global Net Library statistics
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const items = searchParams.get('items') || '0';
    const stacks = searchParams.get('stacks') || '0';
    const grids = searchParams.get('grids') || '0';
    const data = searchParams.get('data') || '0.0';
    const members = searchParams.get('members') || '0';
    const contributors = searchParams.get('contributors') || '0';
    const upvotes = searchParams.get('upvotes') || '0';

    // Build the absolute URL for the app logo
    const host = request.headers.get('host') || 'netlibrary.neynar.com';
    const protocol = host.includes('localhost') ? 'http' : 'https';
    const appLogoUrl = `${protocol}://${host}/app-logo.png?v=2`;

    return new ImageResponse(
      (
        <div
          style={{
            height: '100%',
            width: '100%',
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: '#000000',
            backgroundImage: 'linear-gradient(135deg, #0a0a0a 0%, #001a00 50%, #0a0a0a 100%)',
            position: 'relative',
          }}
        >
          {/* Scanline effect overlay */}
          <div
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              backgroundImage: 'repeating-linear-gradient(0deg, transparent 0px, transparent 2px, rgba(0,0,0,0.1) 2px, rgba(0,0,0,0.1) 4px)',
              opacity: 0.3,
              display: 'flex',
            }}
          />

          {/* Green glow effects in corners */}
          <div
            style={{
              position: 'absolute',
              top: 0,
              left: 0,
              width: 300,
              height: 300,
              background: 'radial-gradient(circle, rgba(0,255,0,0.15) 0%, transparent 70%)',
              display: 'flex',
            }}
          />
          <div
            style={{
              position: 'absolute',
              bottom: 0,
              right: 0,
              width: 300,
              height: 300,
              background: 'radial-gradient(circle, rgba(0,255,0,0.15) 0%, transparent 70%)',
              display: 'flex',
            }}
          />

          {/* Header with app branding */}
          <div
            style={{
              position: 'absolute',
              top: 40,
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              gap: 8,
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
              {/* eslint-disable-next-line @next/next/no-img-element */}
              <img
                src={appLogoUrl}
                alt="Net Library"
                style={{
                  width: 48,
                  height: 48,
                  objectFit: 'contain',
                }}
              />
              <div
                style={{
                  display: 'flex',
                  fontSize: 32,
                  fontWeight: 'bold',
                  color: '#00ff00',
                  fontFamily: 'monospace',
                  letterSpacing: 4,
                }}
              >
                NET LIBRARY
              </div>
            </div>
            <div
              style={{
                display: 'flex',
                fontSize: 16,
                color: 'rgba(0,255,0,0.6)',
                fontFamily: 'monospace',
                letterSpacing: 2,
              }}
            >
              Real-time Onchain Data
            </div>
          </div>

          {/* Main content - Stats Grid */}
          <div
            style={{
              display: 'flex',
              flexDirection: 'column',
              alignItems: 'center',
              justifyContent: 'center',
              padding: '60px',
              marginTop: 40,
            }}
          >
            {/* Title */}
            <div
              style={{
                display: 'flex',
                fontSize: 36,
                fontWeight: 'bold',
                color: '#00ff00',
                fontFamily: 'monospace',
                letterSpacing: 2,
                marginBottom: 48,
                textShadow: '0 0 20px rgba(0,255,0,0.5)',
              }}
            >
              TOTAL NET LIBRARY STATS
            </div>

            {/* Stats Grid - Row 1: Items, Stacks, Grids, Data */}
            <div
              style={{
                display: 'flex',
                gap: 60,
                marginBottom: 48,
              }}
            >
              {/* Items */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: 8,
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    fontSize: 48,
                    fontWeight: 'bold',
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    textShadow: '0 0 20px rgba(0,255,0,0.4)',
                  }}
                >
                  {items}
                </div>
                <div
                  style={{
                    display: 'flex',
                    fontSize: 14,
                    color: 'rgba(255,255,255,0.6)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 1,
                  }}
                >
                  Items
                </div>
              </div>

              {/* Stacks */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: 8,
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    fontSize: 48,
                    fontWeight: 'bold',
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    textShadow: '0 0 20px rgba(0,255,0,0.4)',
                  }}
                >
                  {stacks}
                </div>
                <div
                  style={{
                    display: 'flex',
                    fontSize: 14,
                    color: 'rgba(255,255,255,0.6)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 1,
                  }}
                >
                  Stacks
                </div>
              </div>

              {/* Grids */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: 8,
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    fontSize: 48,
                    fontWeight: 'bold',
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    textShadow: '0 0 20px rgba(0,255,0,0.4)',
                  }}
                >
                  {grids}
                </div>
                <div
                  style={{
                    display: 'flex',
                    fontSize: 14,
                    color: 'rgba(255,255,255,0.6)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 1,
                  }}
                >
                  Grids
                </div>
              </div>

              {/* Data Stored */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: 8,
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    fontSize: 48,
                    fontWeight: 'bold',
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    textShadow: '0 0 20px rgba(0,255,0,0.4)',
                  }}
                >
                  {data}
                </div>
                <div
                  style={{
                    display: 'flex',
                    fontSize: 14,
                    color: 'rgba(255,255,255,0.6)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 1,
                  }}
                >
                  Data (MB)
                </div>
              </div>
            </div>

            {/* Stats Grid - Row 2 */}
            <div
              style={{
                display: 'flex',
                gap: 80,
              }}
            >
              {/* Members */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: 8,
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    fontSize: 56,
                    fontWeight: 'bold',
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    textShadow: '0 0 20px rgba(0,255,0,0.4)',
                  }}
                >
                  {members}
                </div>
                <div
                  style={{
                    display: 'flex',
                    fontSize: 16,
                    color: 'rgba(255,255,255,0.6)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 1,
                  }}
                >
                  Members
                </div>
              </div>

              {/* Contributors */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: 8,
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    fontSize: 56,
                    fontWeight: 'bold',
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    textShadow: '0 0 20px rgba(0,255,0,0.4)',
                  }}
                >
                  {contributors}
                </div>
                <div
                  style={{
                    display: 'flex',
                    fontSize: 16,
                    color: 'rgba(255,255,255,0.6)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 1,
                  }}
                >
                  Contributors
                </div>
              </div>

              {/* Upvotes */}
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  gap: 8,
                }}
              >
                <div
                  style={{
                    display: 'flex',
                    fontSize: 56,
                    fontWeight: 'bold',
                    color: '#00ff00',
                    fontFamily: 'monospace',
                    textShadow: '0 0 20px rgba(0,255,0,0.4)',
                  }}
                >
                  {upvotes}
                </div>
                <div
                  style={{
                    display: 'flex',
                    fontSize: 16,
                    color: 'rgba(255,255,255,0.6)',
                    fontFamily: 'monospace',
                    textTransform: 'uppercase',
                    letterSpacing: 1,
                  }}
                >
                  Upvotes
                </div>
              </div>
            </div>
          </div>

          {/* Footer */}
          <div
            style={{
              position: 'absolute',
              bottom: 30,
              display: 'flex',
              fontSize: 14,
              color: 'rgba(0,255,0,0.5)',
              fontFamily: 'monospace',
              letterSpacing: 2,
            }}
          >
            Decentralized Onchain Knowledge
          </div>
        </div>
      ),
      {
        width: 1200,
        height: 800, // 3:2 aspect ratio for Farcaster
        headers: {
          'Cache-Control': 'no-cache, no-store, must-revalidate',
          'Pragma': 'no-cache',
          'Expires': '0',
        },
      }
    );
  } catch (e: unknown) {
    console.error('Failed to generate stats image:', e);
    return new Response('Failed to generate image', { status: 500 });
  }
}
src/app/share/achievement/page.tsx
import { Metadata } from "next";
import { headers } from "next/headers";
import { RedirectToHome } from "@/app/share/components/redirect-to-home";

// Force dynamic rendering - headers() requires request context
export const dynamic = "force-dynamic";

type Props = {
  searchParams: Promise<{
    name?: string;
    emoji?: string;
    rarity?: string;
    username?: string;
    pfpUrl?: string;
    source?: string; // "base" or "farcaster" - which app version to open
    t?: string;
  }>;
};

export async function generateMetadata({ searchParams }: Props): Promise<Metadata> {
  const params = await searchParams;
  const name = params.name || "Achievement";
  const emoji = params.emoji || "🏅";
  const rarity = params.rarity || "common";
  const username = params.username || "";
  const pfpUrl = params.pfpUrl || "";
  const cacheBuster = params.t || String(Date.now());

  const headersList = await headers();
  const host = headersList.get("host") || "netlibrary.neynar.com";
  const protocol = host.includes("localhost") ? "http" : "https";
  const baseUrl = `${protocol}://${host}`;

  const imageParams = new URLSearchParams({
    name,
    emoji,
    rarity,
    t: cacheBuster,
  });
  // Only add user params if they have values
  if (username) imageParams.set("username", username);
  if (pfpUrl) imageParams.set("pfpUrl", pfpUrl);

  const imageUrl = `${baseUrl}/api/share/image/achievement?${imageParams.toString()}`;

  const metaTitle = username
    ? `${name} by @${username}`
    : `${name} Achievement`;
  const metaDescription = `${rarity.charAt(0).toUpperCase() + rarity.slice(1)} achievement on Net Library`;

  return {
    title: metaTitle,
    description: metaDescription,
    openGraph: {
      type: "website",
      siteName: "Net Library",
      title: metaTitle,
      description: metaDescription,
      images: [
        {
          url: imageUrl,
          width: 1200,
          height: 800, // 3:2 aspect ratio for Farcaster
          alt: metaTitle,
          type: "image/png",
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title: metaTitle,
      description: metaDescription,
      images: [imageUrl],
    },
    other: {
      // Farcaster Mini App embed format
      "fc:miniapp": JSON.stringify({
        version: "next",
        imageUrl: imageUrl,
        button: {
          title: "View Now",
          action: {
            type: "launch_miniapp",
            name: "Net Library",
            url: `${baseUrl}/?tab=library`,
          },
        },
      }),
    },
  };
}

export default async function AchievementSharePage({ searchParams }: Props) {
  const params = await searchParams;
  const name = params.name || "Achievement";
  const emoji = params.emoji || "🏅";
  const rarity = params.rarity || "common";
  const username = params.username || "";
  const source = params.source || "farcaster";

  // Deep link to profile tab where achievements are displayed, with source for correct app version
  const deepLinkPath = `/?tab=library&source=${source}`;

  return (
    <div style={{
      backgroundColor: "#000",
      color: "#00ff00",
      fontFamily: "monospace",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      minHeight: "100vh",
      textAlign: "center"
    }}>
      <div>
        <div style={{ fontSize: "48px", marginBottom: "16px" }}>{emoji}</div>
        <h1 style={{ fontSize: "24px", marginBottom: "8px" }}>{name}</h1>
        {username && <p style={{ color: "#fff", fontSize: "14px", marginBottom: "4px" }}>@{username}</p>}
        <p style={{ color: "#888", textTransform: "uppercase", fontSize: "12px" }}>{rarity}</p>
        <p style={{ color: "#666", fontSize: "14px", marginTop: "24px" }}>Redirecting to Net Library...</p>
      </div>
      <RedirectToHome targetPath={deepLinkPath} />
    </div>
  );
}
src/app/share/book/[key]/page.tsx
import { Metadata } from "next";
import { headers } from "next/headers";
import { RedirectToHome } from "@/app/share/components/redirect-to-home";
import { getBookInfoByContentKey } from "@/lib/cover-art-cache";
import { resolveShareableCoverUrl } from "@/lib/cover-url-resolver";

// Get the appropriate CTA button title based on media type
function getButtonTitle(mediaType?: string): string {
  switch (mediaType) {
    case "audio":
      return "Listen Now";
    case "video":
      return "Watch Now";
    case "image":
      return "View Now";
    default:
      return "Read Now";
  }
}

// Get the appropriate description based on media type
function getDescription(mediaType?: string, title?: string, author?: string): string {
  const itemTitle = title || "this";
  switch (mediaType) {
    case "audio":
      return `Listen to "${itemTitle}" by ${author || "Unknown"} on Net Library`;
    case "video":
      return `Watch "${itemTitle}" by ${author || "Unknown"} on Net Library`;
    case "image":
      return `View "${itemTitle}" by ${author || "Unknown"} on Net Library`;
    default:
      return `Read "${itemTitle}" by ${author || "Unknown"} on Net Library`;
  }
}

// Detect media type from filename/title extension (fallback for legacy items without mediaType)
function detectMediaTypeFromTitle(title: string): string | undefined {
  const lowerTitle = title.toLowerCase();

  // Audio extensions
  if (/\.(mp3|wav|ogg|flac|m4a|aac|wma)$/.test(lowerTitle)) {
    return "audio";
  }

  // Video extensions
  if (/\.(mp4|webm|mov|avi|mkv|m4v|wmv)$/.test(lowerTitle)) {
    return "video";
  }

  // Image extensions
  if (/\.(png|jpg|jpeg|gif|webp|svg|bmp|ico)$/.test(lowerTitle)) {
    return "image";
  }

  // PDF
  if (/\.pdf$/.test(lowerTitle)) {
    return "pdf";
  }

  // Text
  if (/\.(txt|md|markdown)$/.test(lowerTitle)) {
    return "text";
  }

  return undefined;
}

// Force dynamic rendering to ensure fresh OG metadata for each request
export const dynamic = "force-dynamic";
export const revalidate = 0;

type Props = {
  params: Promise<{
    key: string;
  }>;
  searchParams: Promise<{
    title?: string;
    author?: string;
    cover?: string;
    source?: string; // "base" or "farcaster" - which app version to open
  }>;
};

export async function generateMetadata({ params, searchParams }: Props): Promise<Metadata> {
  const { key } = await params;
  const queryParams = await searchParams;
  const contentKey = decodeURIComponent(key);

  // Get the host from headers to build absolute URL
  const headersList = await headers();
  const host = headersList.get("host") || "netlibrary.neynar.com";
  const protocol = host.includes("localhost") ? "http" : "https";
  const baseUrl = `${protocol}://${host}`;

  // First, check if we have query params (fastest, most reliable)
  let title = queryParams.title ? decodeURIComponent(queryParams.title) : "";
  let author = queryParams.author ? decodeURIComponent(queryParams.author) : "";
  let coverUrl = queryParams.cover ? decodeURIComponent(queryParams.cover) : "";
  let mediaType: string | undefined;

  // If we don't have query params, try to look up from local KV cache (direct DB access, no HTTP)
  if (!title || !author || !coverUrl) {
    console.log(`[share/book] Looking up contentKey: "${contentKey.slice(0, 20)}..."`);
    const bookInfo = await getBookInfoByContentKey(contentKey);
    if (bookInfo) {
      console.log(`[share/book] Found: "${bookInfo.title}" by "${bookInfo.author}", coverUrl: ${bookInfo.coverUrl ? (bookInfo.coverUrl.startsWith("data:") ? "base64" : "hosted") : "missing"}, mediaType: ${bookInfo.mediaType || "unknown"}`);
      if (!title) title = bookInfo.title;
      if (!author) author = bookInfo.author;
      mediaType = bookInfo.mediaType;
      // Use the cover resolver to handle base64 → hosted URL conversion
      if (!coverUrl && bookInfo.coverUrl) {
        coverUrl = await resolveShareableCoverUrl(contentKey, bookInfo.coverUrl, host);
      }
    } else {
      console.log(`[share/book] No entry found for contentKey: "${contentKey.slice(0, 20)}..."`);
    }
  }

  // Fallback values if nothing found
  if (!title) title = "Untitled";
  if (!author) author = "Unknown";

  // If no mediaType from DB, try to detect from title/filename extension
  if (!mediaType && title) {
    mediaType = detectMediaTypeFromTitle(title);
    if (mediaType) {
      console.log(`[share/book] Detected mediaType from title: ${mediaType}`);
    }
  }

  // Build the OG image URL - only include coverUrl if it's valid
  const imageParams = new URLSearchParams({
    title,
    author,
    t: String(Date.now()), // Cache buster
  });
  if (coverUrl) {
    imageParams.set("coverUrl", coverUrl);
    console.log(`[share/book] Using coverUrl for OG image: ${coverUrl.slice(0, 60)}...`);
  } else {
    console.log(`[share/book] No coverUrl available - OG image will use placeholder`);
  }
  const imageUrl = `${baseUrl}/api/share/image/book?${imageParams.toString()}`;

  // Twitter requires 1.91:1 aspect ratio (1200x628), so use dedicated Twitter image route
  const twitterImageUrl = `${baseUrl}/api/share/image/book-twitter?${imageParams.toString()}`;
  console.log(`[share/book] Twitter image URL: ${twitterImageUrl.slice(0, 100)}...`);

  // Deep link URL to the mini app with book parameter
  const appUrl = `${baseUrl}/?book=${encodeURIComponent(contentKey)}`;

  const metaTitle = `${title} by ${author}`;
  const description = getDescription(mediaType, title, author);

  return {
    title: metaTitle,
    description,
    openGraph: {
      type: "website",
      siteName: "Net Library",
      title: metaTitle,
      description,
      images: [
        {
          url: imageUrl,
          width: 1200,
          height: 800, // 3:2 aspect ratio for Farcaster
          alt: metaTitle,
          type: "image/png",
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title: metaTitle,
      description,
      images: [twitterImageUrl],
    },
    other: {
      // Farcaster Mini App embed format
      "fc:miniapp": JSON.stringify({
        version: "next",
        imageUrl: imageUrl,
        button: {
          title: getButtonTitle(mediaType),
          action: {
            type: "launch_miniapp",
            name: "Net Library",
            url: appUrl,
          },
        },
      }),
    },
  };
}

export default async function BookSharePage({ params }: Props) {
  const { key } = await params;
  const contentKey = decodeURIComponent(key);

  // Look up book info from KV cache for display
  let title = "Book";
  let author = "Unknown";
  const bookInfo = await getBookInfoByContentKey(contentKey);
  if (bookInfo) {
    title = bookInfo.title;
    author = bookInfo.author;
  }

  // Deep link to open this specific book
  const deepLinkPath = `/?book=${encodeURIComponent(contentKey)}`;

  // Render a page with metadata that redirects client-side
  // This allows crawlers (X/Twitter, Farcaster) to read the OG metadata
  return (
    <div style={{
      backgroundColor: "#000",
      color: "#00ff00",
      fontFamily: "monospace",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      minHeight: "100vh",
      textAlign: "center"
    }}>
      <div>
        <h1 style={{ fontSize: "24px", marginBottom: "8px" }}>{title}</h1>
        <p style={{ color: "#888" }}>by {author}</p>
        <p style={{ color: "#666", fontSize: "14px", marginTop: "24px" }}>Redirecting to Net Library...</p>
      </div>
      <RedirectToHome targetPath={deepLinkPath} />
    </div>
  );
}
src/app/share/book/page.tsx
import { Metadata } from "next";
import { headers } from "next/headers";
import { RedirectToHome } from "@/app/share/components/redirect-to-home";

// Force dynamic rendering - headers() requires request context
export const dynamic = "force-dynamic";

// LEGACY: This page handles old share links with query params
// New shares use /share/book/[key] with contentKey-based lookup
type Props = {
  searchParams: Promise<{
    title?: string;
    author?: string;
    t?: string; // Cache buster timestamp
  }>;
};

export async function generateMetadata({ searchParams }: Props): Promise<Metadata> {
  const params = await searchParams;
  const title = params.title || "Untitled";
  const author = params.author || "Unknown";
  const cacheBuster = params.t || String(Date.now());

  // Get the host from headers to build absolute URL
  const headersList = await headers();
  const host = headersList.get("host") || "netlibrary.neynar.com";
  const protocol = host.includes("localhost") ? "http" : "https";
  const baseUrl = `${protocol}://${host}`;

  // Build the image URL - only title and author, no coverUrl (was causing huge URLs)
  const imageParams = new URLSearchParams({
    title,
    author,
    t: cacheBuster,
  });

  const imageUrl = `${baseUrl}/api/share/image/book?${imageParams.toString()}`;

  const metaTitle = `${title} by ${author}`;
  const description = `Check out "${title}" by ${author} on Net Library - Decentralized onchain media powered by Net Protocol`;

  return {
    title: metaTitle,
    description,
    openGraph: {
      type: "website",
      siteName: "Net Library",
      title: metaTitle,
      description,
      images: [
        {
          url: imageUrl,
          width: 1200,
          height: 800, // 3:2 aspect ratio for Farcaster
          alt: metaTitle,
          type: "image/png",
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title: metaTitle,
      description,
      images: [imageUrl],
    },
    other: {
      // Farcaster Mini App embed format
      "fc:miniapp": JSON.stringify({
        version: "next",
        imageUrl: imageUrl,
        button: {
          title: "Read Now",
          action: {
            type: "launch_miniapp",
            name: "Net Library",
            url: baseUrl,
          },
        },
      }),
    },
  };
}

export default async function BookSharePage({ searchParams }: Props) {
  const params = await searchParams;
  const title = params.title || "Book";
  const author = params.author || "Unknown";

  return (
    <div style={{
      backgroundColor: "#000",
      color: "#00ff00",
      fontFamily: "monospace",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      minHeight: "100vh",
      textAlign: "center"
    }}>
      <div>
        <h1 style={{ fontSize: "24px", marginBottom: "8px" }}>{title}</h1>
        <p style={{ color: "#888" }}>by {author}</p>
        <p style={{ color: "#666", fontSize: "14px", marginTop: "24px" }}>Redirecting to Net Library...</p>
      </div>
      <RedirectToHome />
    </div>
  );
}
src/app/share/components/redirect-to-home.tsx
"use client";

import { useEffect } from "react";
import { useRouter } from "next/navigation";

interface RedirectToHomeProps {
  /** Optional path to redirect to (e.g., "/?book=abc" or "/?stack=123") */
  targetPath?: string;
}

/**
 * Client-side redirect to home page or a specific deep link path.
 * Used in share pages to allow crawlers (X/Twitter, Farcaster) to read OG metadata
 * before redirecting users to the main app.
 */
export function RedirectToHome({ targetPath = "/" }: RedirectToHomeProps) {
  const router = useRouter();

  useEffect(() => {
    // Small delay to ensure metadata is readable by crawlers
    const timeout = setTimeout(() => {
      router.replace(targetPath);
    }, 100);

    return () => clearTimeout(timeout);
  }, [router, targetPath]);

  return null;
}
src/app/share/grid/[id]/page.tsx
/* eslint-disable @neynar/no-process-env */
import { Metadata } from "next";
import { headers } from "next/headers";
import { RedirectToHome } from "@/app/share/components/redirect-to-home";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { Grid, GridCell, GridCells } from "@/lib/net-protocol";

// Force dynamic rendering to ensure fresh OG metadata for each request
export const dynamic = "force-dynamic";
export const revalidate = 0;

type Props = {
  params: Promise<{
    id: string;
  }>;
  searchParams: Promise<{
    source?: string; // "base" or "farcaster" - which app version to open
  }>;
};

// Helper to get KV value
async function getKV<T>(key: string): Promise<T | null> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, key)).limit(1);
    if (!result[0]?.value) return null;
    return JSON.parse(result[0].value) as T;
  } catch {
    return null;
  }
}

// Helper to fetch grid from KV
async function getGrid(gridId: string): Promise<Grid | null> {
  return getKV<Grid>(`grid:${gridId}`);
}

// Helper to fetch grid cells from KV
async function getGridCells(gridId: string): Promise<GridCell[]> {
  const gridCells = await getKV<GridCells>(`grid-cells:${gridId}`);
  return gridCells?.cells || [];
}

// Member registry entry type
interface MemberEntry {
  memberId: number;
  address: string;
  username?: string;
  fid?: number;
  ensSubname?: string;
  joinedAt?: number;
}

interface MemberRegistry {
  members: MemberEntry[];
}

// Resolve creator info (username, pfp, member status) from member registry
async function resolveCreatorInfo(creatorAddress: string): Promise<{
  username: string;
  pfpUrl?: string;
  isMember: boolean;
}> {
  try {
    // Look up in member registry (it's an array of members)
    const registry = await getKV<MemberRegistry>("member-registry");
    const members = registry?.members || [];

    const memberInfo = members.find(
      m => m.address?.toLowerCase() === creatorAddress.toLowerCase()
    );

    if (memberInfo) {
      // Found member - try to get pfp from Neynar if we have FID
      let pfpUrl: string | undefined;

      if (memberInfo.fid) {
        try {
          // Call Neynar API directly (server-side) - relative URLs don't work for Twitter crawler
          const neynarApiKey = process.env.NEYNAR_API_KEY;
          if (neynarApiKey) {
            const response = await fetch(
              `https://api.neynar.com/v2/farcaster/user/bulk?fids=${memberInfo.fid}`,
              {
                headers: { 'api_key': neynarApiKey },
                next: { revalidate: 3600 }, // Cache for 1 hour
              }
            );
            if (response.ok) {
              const data = await response.json();
              const user = data.users?.[0];
              if (user?.pfp_url) {
                pfpUrl = user.pfp_url;
              }
            }
          }
        } catch {
          // Ignore Neynar errors, continue without pfp
        }
      }

      return {
        username: memberInfo.username || creatorAddress.slice(0, 8),
        pfpUrl,
        isMember: true,
      };
    }

    // Not a member, return address truncated
    return {
      username: creatorAddress.slice(0, 8),
      isMember: false,
    };
  } catch {
    return {
      username: creatorAddress.slice(0, 8),
      isMember: false,
    };
  }
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { id } = await params;
  const gridId = decodeURIComponent(id);

  // Get the host from headers to build absolute URL (same pattern as working share pages)
  const headersList = await headers();
  const host = headersList.get("host") || "netlibrary.neynar.com";
  const protocol = host.includes("localhost") ? "http" : "https";
  const baseUrl = `${protocol}://${host}`;

  // Fetch grid data - we pass this to the image route via query params
  // This avoids database access in edge runtime which can fail in production
  const grid = await getGrid(gridId);
  const cells = await getGridCells(gridId);

  const name = grid?.name || "Untitled Grid";
  const subtitle = grid?.subtitle || "";
  const size = grid?.size || 5;
  const cellCount = cells.length;

  // Resolve creator info from member registry
  const creatorInfo = grid?.creator
    ? await resolveCreatorInfo(grid.creator)
    : { username: "anon", isMember: false };
  const creatorUsername = creatorInfo.username;

  // Build compact cells data for image route
  // Format: "row,col,coverUrl;row,col,coverUrl" (semicolon-separated cells)
  const displaySize = Math.min(size, 5);
  const cellsForImage = cells
    .filter(c => c.row < displaySize && c.col < displaySize)
    .slice(0, 9) // Max 9 cells to keep URL reasonable
    .map(c => {
      // Use coverUrl if available, or cdnUrl as fallback for images
      const url = c.coverUrl || (c.mediaType === 'image' || c.mediaType === 'gif' ? c.cdnUrl : '');
      return `${c.row},${c.col},${encodeURIComponent(url || '')}`;
    })
    .join(';');

  // Build image URL params - pass data to avoid DB access in edge runtime
  const imageParams = new URLSearchParams({
    name,
    size: String(size),
    creator: creatorUsername,
    isMember: String(creatorInfo.isMember),
    t: String(Date.now()), // Cache buster
  });
  if (subtitle) imageParams.set('subtitle', subtitle);
  if (cellsForImage) imageParams.set('cells', cellsForImage);
  if (creatorInfo.pfpUrl) imageParams.set('pfp', creatorInfo.pfpUrl);

  const farcasterImageUrl = `${baseUrl}/api/share/image/grid?${imageParams.toString()}&format=farcaster`;
  const twitterImageUrl = `${baseUrl}/api/share/image/grid?${imageParams.toString()}&format=twitter`;

  // Deep link URL to the mini app with grid parameter
  const appUrl = `${baseUrl}/?grid=${encodeURIComponent(gridId)}`;

  const metaTitle = `${name} by @${creatorUsername}`;
  const metaDescription = subtitle
    ? `${subtitle} • ${size}×${size} grid with ${cellCount} items on Net Library`
    : `${size}×${size} grid with ${cellCount} items on Net Library`;

  return {
    title: metaTitle,
    description: metaDescription,
    openGraph: {
      type: "website",
      siteName: "Net Library",
      title: metaTitle,
      description: metaDescription,
      images: [
        {
          url: farcasterImageUrl,
          width: 1200,
          height: 800, // Farcaster 3:2 aspect ratio
          alt: metaTitle,
          type: "image/png",
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title: metaTitle,
      description: metaDescription,
      images: [twitterImageUrl], // Simple string format (same as working share pages)
    },
    other: {
      // Farcaster Mini App embed format
      "fc:miniapp": JSON.stringify({
        version: "next",
        imageUrl: farcasterImageUrl,
        button: {
          title: "Explore Grid",
          action: {
            type: "launch_miniapp",
            name: "Net Library",
            url: appUrl,
          },
        },
      }),
    },
  };
}

export default async function GridSharePage({ params, searchParams }: Props) {
  const { id } = await params;
  const queryParams = await searchParams;
  const gridId = decodeURIComponent(id);
  const source = queryParams.source || "farcaster";

  // Fetch grid for display
  const grid = await getGrid(gridId);
  const cells = await getGridCells(gridId);

  const name = grid?.name || "Untitled Grid";
  const subtitle = grid?.subtitle || "";
  const size = grid?.size || 5;
  const cellCount = cells.length;

  // Deep link to open this specific grid with source for correct app version
  const deepLinkPath = `/?grid=${encodeURIComponent(gridId)}&source=${source}`;

  // Render a page with metadata that redirects client-side
  // This allows crawlers (X/Twitter, Farcaster) to read the OG metadata
  return (
    <div style={{
      backgroundColor: "#000",
      color: "#00ff00",
      fontFamily: "monospace",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      minHeight: "100vh",
      textAlign: "center",
      flexDirection: "column",
      gap: "16px",
    }}>
      <div style={{ fontSize: "48px" }}>⬜</div>
      <h1 style={{ fontSize: "24px", marginBottom: "4px" }}>{name}</h1>
      {subtitle && <p style={{ color: "#aaa", fontSize: "16px", marginTop: "-8px" }}>{subtitle}</p>}
      <p style={{ color: "#888" }}>{size}×{size} grid • {cellCount} items</p>
      <p style={{ color: "#666", fontSize: "14px", marginTop: "8px" }}>Redirecting to Net Library...</p>
      <RedirectToHome targetPath={deepLinkPath} />
    </div>
  );
}
src/app/share/library-card/page.tsx
import { Metadata } from "next";
import { headers } from "next/headers";
import { RedirectToHome } from "@/app/share/components/redirect-to-home";

// Force dynamic rendering - headers() requires request context
export const dynamic = "force-dynamic";

type Props = {
  searchParams: Promise<{
    memberId?: string;
    ensSubname?: string;
    username?: string;    // Farcaster handle (e.g. "cherylfromnet") — shown as @handle
    displayName?: string; // Human-readable name (e.g. "Cheryl") — shown as big title
    uploads?: string;
    dataMb?: string;
    upvotes?: string;
    pfpUrl?: string; // User's profile picture URL
    source?: string; // "base" or "farcaster" - which app version to open
    t?: string; // Cache buster timestamp
    // Platform verification status
    fcVerified?: string;
    baseVerified?: string;
    webVerified?: string;
    // Net Link status
    hasNetLink?: string;
    netLinkLabel?: string;
  }>;
};

export async function generateMetadata({ searchParams }: Props): Promise<Metadata> {
  const params = await searchParams;
  const memberId = params.memberId || "???";
  const username = params.username || "member";
  const displayName = params.displayName || username; // Fall back to username for backwards compat
  const uploads = params.uploads || "0";
  const dataMb = params.dataMb || "0";
  const upvotes = params.upvotes || "0";
  const ensSubname = params.ensSubname || "";
  const pfpUrl = params.pfpUrl || "";
  // Platform verification status
  const fcVerified = params.fcVerified || "false";
  const baseVerified = params.baseVerified || "false";
  const webVerified = params.webVerified || "false";
  // Net Link status
  const hasNetLink = params.hasNetLink || "false";
  const netLinkLabel = params.netLinkLabel || "";
  // Use provided timestamp or generate new one for cache busting
  const cacheBuster = params.t || String(Date.now());

  // Get the host from headers to build absolute URL
  const headersList = await headers();
  const host = headersList.get("host") || "netlibrary.neynar.com";
  const protocol = host.includes("localhost") ? "http" : "https";
  const baseUrl = `${protocol}://${host}`;

  // Build the image URL with all params - MUST be absolute for Farcaster
  // Include cache buster to ensure Farcaster fetches fresh image
  const imageParams = new URLSearchParams({
    memberId,
    ensSubname,
    username,       // Farcaster handle shown as @handle
    displayName,    // Human-readable name shown as big title
    uploads,
    dataMb,
    upvotes,
    fcVerified,
    baseVerified,
    webVerified,
    hasNetLink,
    netLinkLabel,
    t: cacheBuster, // Cache buster for fresh images
  });
  // Add PFP URL if provided to show user's actual photo
  if (pfpUrl) {
    imageParams.set("pfpUrl", pfpUrl);
  }

  // Use absolute URL for the OG image so Farcaster can fetch it
  const imageUrl = `${baseUrl}/api/share/image/library-card-nft?${imageParams.toString()}`;

  // Clean title and description for sharing
  const title = `${displayName}'s Library Card`;
  const description = `@${username} · Member #${memberId} on Net Library`;

  return {
    // Override parent metadata completely
    title,
    description,
    // OpenGraph - explicitly set all fields to override parent layout
    openGraph: {
      type: "website",
      siteName: "Net Library",
      title,
      description,
      images: [
        {
          url: imageUrl,
          width: 1200,
          height: 800, // 3:2 aspect ratio for Farcaster
          alt: title,
          type: "image/png",
        },
      ],
    },
    // Twitter/X card
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: [imageUrl],
    },
    other: {
      // Farcaster Mini App embed format
      "fc:miniapp": JSON.stringify({
        version: "next",
        imageUrl: imageUrl,
        button: {
          title: "View Now",
          action: {
            type: "launch_miniapp",
            name: "Net Library",
            url: `${baseUrl}/?tab=library&member=${memberId}`,
          },
        },
      }),
    },
  };
}

export default async function LibraryCardSharePage({ searchParams }: Props) {
  const params = await searchParams;
  const username = params.username || "member";
  const displayName = params.displayName || username;
  const memberId = params.memberId || "???";
  const source = params.source || "farcaster";

  // Deep link to open profile tab with member context and source for correct app version
  const deepLinkPath = `/?tab=library&member=${memberId}&source=${source}`;

  // Render a page with metadata that redirects client-side
  // This allows crawlers (X/Twitter, Farcaster) to read the OG metadata
  // before the user is redirected to the main app
  return (
    <div style={{
      backgroundColor: "#000",
      color: "#00ff00",
      fontFamily: "monospace",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      minHeight: "100vh",
      textAlign: "center"
    }}>
      <div>
        <h1 style={{ fontSize: "24px", marginBottom: "16px" }}>{displayName}&apos;s Library Card #{memberId}</h1>
        <p style={{ color: "#888" }}>@{username}</p>
        <p style={{ color: "#666", fontSize: "14px", marginTop: "24px" }}>Redirecting to Net Library...</p>
      </div>
      <RedirectToHome targetPath={deepLinkPath} />
    </div>
  );
}
src/app/share/social/[key]/page.tsx
import { Metadata } from "next";
import { headers } from "next/headers";
import { RedirectToHome } from "@/app/share/components/redirect-to-home";
import { getBookInfoByContentKey } from "@/lib/cover-art-cache";

// Platform display names
const PLATFORM_NAMES: Record<string, string> = {
  farcaster: "Farcaster",
  twitter: "Twitter/X",
  youtube: "YouTube",
  instagram: "Instagram",
  tiktok: "TikTok",
  reddit: "Reddit",
  bluesky: "Bluesky",
  threads: "Threads",
  linkedin: "LinkedIn",
};

// Force dynamic rendering to ensure fresh OG metadata for each request
export const dynamic = "force-dynamic";
export const revalidate = 0;

type Props = {
  params: Promise<{
    key: string;
  }>;
  searchParams: Promise<{
    source?: string; // "base" or "farcaster" - which app version to open
  }>;
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { key } = await params;
  const contentKey = decodeURIComponent(key);

  // Get the host from headers to build absolute URL
  const headersList = await headers();
  const host = headersList.get("host") || "netlibrary.neynar.com";
  const protocol = host.includes("localhost") ? "http" : "https";
  const baseUrl = `${protocol}://${host}`;

  // Look up content info from local KV cache
  const contentInfo = await getBookInfoByContentKey(contentKey);

  // Extract social receipt metadata
  const isSocialReceipt = contentInfo?.isSocialReceipt || false;
  const platform = contentInfo?.socialPlatform || "twitter";
  const platformName = PLATFORM_NAMES[platform] || "Social";
  const socialAuthor = contentInfo?.socialAuthor || "Unknown";
  const socialText = contentInfo?.socialText || "";
  const originalUrl = contentInfo?.originalUrl || "";
  const coverUrl = contentInfo?.coverUrl || "";

  // Build title and description
  const title = isSocialReceipt
    ? `@${socialAuthor} on ${platformName} - Net Library`
    : contentInfo?.title || "Social Post - Net Library";

  const description = isSocialReceipt
    ? socialText.slice(0, 200) + (socialText.length > 200 ? "..." : "")
    : "Archived social post on Net Library";

  // Build the OG image URL - use the social-specific share image
  const imageParams = new URLSearchParams({
    platform,
    author: socialAuthor,
    text: socialText.slice(0, 400), // Limit text length
    t: String(Date.now()), // Cache buster
  });
  if (coverUrl) {
    imageParams.set("receiptUrl", coverUrl);
  }
  if (originalUrl) {
    imageParams.set("originalUrl", originalUrl);
  }
  const imageUrl = `${baseUrl}/api/share/image/social?${imageParams.toString()}`;

  // Twitter requires 1.91:1 aspect ratio (1200x628), so use dedicated Twitter image route
  const twitterImageUrl = `${baseUrl}/api/share/image/social-twitter?${imageParams.toString()}`;

  // Deep link URL to the mini app with book parameter (receipts are stored as regular content)
  const appUrl = `${baseUrl}/?book=${encodeURIComponent(contentKey)}`;

  return {
    title,
    description,
    openGraph: {
      type: "website",
      siteName: "Net Library",
      title,
      description,
      images: [
        {
          url: imageUrl,
          width: 1200,
          height: 800, // 3:2 aspect ratio for Farcaster
          alt: title,
          type: "image/png",
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: [twitterImageUrl],
    },
    other: {
      // Farcaster Mini App embed format
      "fc:miniapp": JSON.stringify({
        version: "next",
        imageUrl: imageUrl,
        button: {
          title: "View Now",
          action: {
            type: "launch_miniapp",
            name: "Net Library",
            url: appUrl,
          },
        },
      }),
    },
  };
}

export default async function SocialSharePage({ params }: Props) {
  const { key } = await params;
  const contentKey = decodeURIComponent(key);

  // Look up content info from KV cache
  const contentInfo = await getBookInfoByContentKey(contentKey);

  const platform = contentInfo?.socialPlatform || "social";
  const platformName = PLATFORM_NAMES[platform] || "Social";
  const socialAuthor = contentInfo?.socialAuthor || "Unknown";

  // Deep link to open this content
  const deepLinkPath = `/?book=${encodeURIComponent(contentKey)}`;

  // Render a page with metadata that redirects client-side
  return (
    <div style={{
      backgroundColor: "#000",
      color: "#00ff00",
      fontFamily: "monospace",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      minHeight: "100vh",
      textAlign: "center"
    }}>
      <div>
        <h1 style={{ fontSize: "24px", marginBottom: "8px" }}>
          @{socialAuthor} on {platformName}
        </h1>
        <p style={{ color: "#00ff00", fontSize: "14px", marginTop: "16px" }}>
          Archived on Net Library
        </p>
        <p style={{ color: "#666", fontSize: "14px", marginTop: "24px" }}>
          Redirecting...
        </p>
      </div>
      <RedirectToHome targetPath={deepLinkPath} />
    </div>
  );
}
src/app/share/stack/[id]/page.tsx
import { Metadata } from "next";
import { headers } from "next/headers";
import { RedirectToHome } from "@/app/share/components/redirect-to-home";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { Stack } from "@/features/app/types";

// Force dynamic rendering to ensure fresh OG metadata for each request
export const dynamic = "force-dynamic";
export const revalidate = 0;

type Props = {
  params: Promise<{
    id: string;
  }>;
  searchParams: Promise<{
    source?: string; // "base" or "farcaster" - which app version to open
  }>;
};

// Helper to fetch stack from KV
async function getStack(stackId: string): Promise<Stack | null> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, `stack:${stackId}`)).limit(1);
    if (!result[0]?.value) return null;
    return JSON.parse(result[0].value) as Stack;
  } catch (error) {
    console.error(`[share/stack] Error fetching stack ${stackId}:`, error);
    return null;
  }
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { id } = await params;
  const stackId = decodeURIComponent(id);

  // Get the host from headers to build absolute URL
  const headersList = await headers();
  const host = headersList.get("host") || "netlibrary.neynar.com";
  const protocol = host.includes("localhost") ? "http" : "https";
  const baseUrl = `${protocol}://${host}`;

  // Fetch stack data
  const stack = await getStack(stackId);

  const name = stack?.name || "Curated Stack";
  const itemCount = stack?.itemCount || 0;
  const ownerUsername = stack?.ownerUsername || "anon";
  const description = stack?.description || "";

  // Build the OG image URL
  const imageParams = new URLSearchParams({
    name,
    itemCount: String(itemCount),
    owner: ownerUsername,
    t: String(Date.now()), // Cache buster
  });
  if (description) {
    imageParams.set("description", description);
  }
  const imageUrl = `${baseUrl}/api/share/image/stack?${imageParams.toString()}`;

  // Deep link URL to the mini app with stack parameter
  const appUrl = `${baseUrl}/?stack=${encodeURIComponent(stackId)}`;

  const metaTitle = `${name} by @${ownerUsername}`;
  const metaDescription = description || `${itemCount} items curated on Net Library`;

  return {
    title: metaTitle,
    description: metaDescription,
    openGraph: {
      type: "website",
      siteName: "Net Library",
      title: metaTitle,
      description: metaDescription,
      images: [
        {
          url: imageUrl,
          width: 1200,
          height: 800, // 3:2 aspect ratio for Farcaster
          alt: metaTitle,
          type: "image/png",
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title: metaTitle,
      description: metaDescription,
      images: [imageUrl],
    },
    other: {
      // Farcaster Mini App embed format
      "fc:miniapp": JSON.stringify({
        version: "next",
        imageUrl: imageUrl,
        button: {
          title: "Explore Now",
          action: {
            type: "launch_miniapp",
            name: "Net Library",
            url: appUrl,
          },
        },
      }),
    },
  };
}

export default async function StackSharePage({ params, searchParams }: Props) {
  const { id } = await params;
  const queryParams = await searchParams;
  const stackId = decodeURIComponent(id);
  const source = queryParams.source || "farcaster";

  // Fetch stack for display
  const stack = await getStack(stackId);
  const name = stack?.name || "Curated Stack";
  const itemCount = stack?.itemCount || 0;
  const ownerUsername = stack?.ownerUsername || "anon";

  // Deep link to open this specific stack with source for correct app version
  const deepLinkPath = `/?stack=${encodeURIComponent(stackId)}&source=${source}`;

  // Render a page with metadata that redirects client-side
  // This allows crawlers (X/Twitter, Farcaster) to read the OG metadata
  return (
    <div style={{
      backgroundColor: "#000",
      color: "#00ff00",
      fontFamily: "monospace",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      minHeight: "100vh",
      textAlign: "center",
      flexDirection: "column",
      gap: "16px",
    }}>
      <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#00ff00" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20" />
        <path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z" />
      </svg>
      <h1 style={{ fontSize: "24px", marginBottom: "4px" }}>{name}</h1>
      <p style={{ color: "#888" }}>{itemCount} items by @{ownerUsername}</p>
      <p style={{ color: "#666", fontSize: "14px", marginTop: "8px" }}>Redirecting to Net Library...</p>
      <RedirectToHome targetPath={deepLinkPath} />
    </div>
  );
}
src/app/share/stats/page.tsx
import { Metadata } from "next";
import { headers } from "next/headers";
import { RedirectToHome } from "@/app/share/components/redirect-to-home";

// Force dynamic rendering - headers() requires request context
export const dynamic = "force-dynamic";

type Props = {
  searchParams: Promise<{
    items?: string;
    stacks?: string;
    grids?: string;
    data?: string;
    members?: string;
    contributors?: string;
    upvotes?: string;
    t?: string;
  }>;
};

export async function generateMetadata({ searchParams }: Props): Promise<Metadata> {
  const params = await searchParams;
  const items = params.items || "0";
  const stacks = params.stacks || "0";
  const grids = params.grids || "0";
  const data = params.data || "0.0";
  const members = params.members || "0";
  const contributors = params.contributors || "0";
  const upvotes = params.upvotes || "0";
  const cacheBuster = params.t || String(Date.now());

  const headersList = await headers();
  const host = headersList.get("host") || "netlibrary.neynar.com";
  const protocol = host.includes("localhost") ? "http" : "https";
  const baseUrl = `${protocol}://${host}`;

  const imageParams = new URLSearchParams({
    items,
    stacks,
    grids,
    data,
    members,
    contributors,
    upvotes,
    t: cacheBuster,
  });

  const imageUrl = `${baseUrl}/api/share/image/stats?${imageParams.toString()}`;

  const metaTitle = "Net Library Stats";
  const metaDescription = `${items} items, ${stacks} stacks, ${grids} grids, ${data} MB data stored, ${members} members, ${contributors} contributors, ${upvotes} upvotes - Real-time onchain data`;

  return {
    title: metaTitle,
    description: metaDescription,
    openGraph: {
      type: "website",
      siteName: "Net Library",
      title: metaTitle,
      description: metaDescription,
      images: [
        {
          url: imageUrl,
          width: 1200,
          height: 800, // 3:2 aspect ratio for Farcaster
          alt: metaTitle,
          type: "image/png",
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title: metaTitle,
      description: metaDescription,
      images: [imageUrl],
    },
    other: {
      // Farcaster Mini App embed format
      "fc:miniapp": JSON.stringify({
        version: "next",
        imageUrl: imageUrl,
        button: {
          title: "Explore Now",
          action: {
            type: "launch_miniapp",
            name: "Net Library",
            url: `${baseUrl}/?tab=info`,
          },
        },
      }),
    },
  };
}

export default async function StatsSharePage({ searchParams }: Props) {
  const params = await searchParams;
  const items = params.items || "0";
  const stacks = params.stacks || "0";
  const grids = params.grids || "0";
  const data = params.data || "0.0";

  // Deep link to info tab where stats are displayed
  const deepLinkPath = "/?tab=info";

  return (
    <div style={{
      backgroundColor: "#000",
      color: "#00ff00",
      fontFamily: "monospace",
      display: "flex",
      alignItems: "center",
      justifyContent: "center",
      minHeight: "100vh",
      textAlign: "center"
    }}>
      <div>
        <div style={{ marginBottom: "16px", display: "flex", justifyContent: "center" }}>
          <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#00ff00" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <line x1="18" y1="20" x2="18" y2="10" />
            <line x1="12" y1="20" x2="12" y2="4" />
            <line x1="6" y1="20" x2="6" y2="14" />
          </svg>
        </div>
        <h1 style={{ fontSize: "24px", marginBottom: "8px", letterSpacing: "2px" }}>NET LIBRARY STATS</h1>
        <p style={{ color: "#fff", fontSize: "14px", marginBottom: "4px" }}>{items} items • {stacks} stacks • {grids} grids • {data} MB</p>
        <p style={{ color: "#888", fontSize: "12px", marginTop: "8px" }}>Real-time Onchain Data</p>
        <p style={{ color: "#666", fontSize: "14px", marginTop: "24px" }}>Redirecting to Net Library...</p>
      </div>
      <RedirectToHome targetPath={deepLinkPath} />
    </div>
  );
}

📁 Other Files (74)

src/actions/add-changelog-entry.ts
"use server";

import { kvGet, kvSet } from "@/neynar-db-sdk";

const CHANGELOG_KEY = "app-changelog";

interface ChangeEntry {
  type: "feature" | "fix" | "improvement" | "breaking" | "docs" | "internal";
  category: "ui" | "api" | "database" | "achievements" | "uploads" | "social" | "membership" | "other";
  title: string;
  description: string;
  technical?: string;
}

interface ChangelogEntry {
  version: string;
  publishedAt: number;
  changes: ChangeEntry[];
  summary: string;
}

interface ChangelogIndex {
  entries: ChangelogEntry[];
  currentVersion: string;
  lastUpdated: number;
}

function incrementVersion(version: string, type: "major" | "minor" | "patch"): string {
  const [major, minor, patch] = version.split(".").map(Number);
  switch (type) {
    case "major":
      return `${major + 1}.0.0`;
    case "minor":
      return `${major}.${minor + 1}.0`;
    case "patch":
    default:
      return `${major}.${minor}.${patch + 1}`;
  }
}

export async function addChangelogEntry(
  changes: ChangeEntry[],
  summary: string,
  versionType: "major" | "minor" | "patch" = "patch"
): Promise<{ success: boolean; version?: string; error?: string }> {
  try {
    // Fetch existing changelog
    const existing = await kvGet(CHANGELOG_KEY);
    const changelog: ChangelogIndex = existing
      ? JSON.parse(existing)
      : { entries: [], currentVersion: "1.0.0", lastUpdated: Date.now() };

    // Determine new version
    const newVersion = incrementVersion(changelog.currentVersion, versionType);

    // Create new entry
    const newEntry: ChangelogEntry = {
      version: newVersion,
      publishedAt: Date.now(),
      changes,
      summary,
    };

    // Add to beginning of entries
    changelog.entries.unshift(newEntry);
    changelog.currentVersion = newVersion;
    changelog.lastUpdated = Date.now();

    // Keep last 100 entries
    if (changelog.entries.length > 100) {
      changelog.entries = changelog.entries.slice(0, 100);
    }

    // Save
    await kvSet(CHANGELOG_KEY, JSON.stringify(changelog));

    console.log(`[changelog] Added version ${newVersion} with ${changes.length} changes`);

    return { success: true, version: newVersion };
  } catch (error) {
    console.error("[changelog] addChangelogEntry error:", error);
    return { success: false, error: error instanceof Error ? error.message : "Failed to add entry" };
  }
}

// Add the documentation update entry
export async function addDocsUpdateChangelog() {
  const changes: ChangeEntry[] = [
    {
      type: "docs",
      category: "other",
      title: "Overview Page Updates",
      description: "Renamed 'Browse & Discover' to 'Stacks & Discovery', updated 'Upload Media' to 'Streamlined Uploads' with x402 relay info, added Grids feature section, added Social Receipts feature section",
      technical: "Updated net-library-overview.html with new feature sections for Grids (3×3 to 10×10 visual boards, mini-map, colored borders, archive export) and Social Receipts (Farcaster/X import, permanent archiving)",
    },
    {
      type: "feature",
      category: "other",
      title: "Grids Documentation",
      description: "Added comprehensive documentation for the new Grids feature - visual boards from 3×3 to 10×10 with mini-map navigation",
      technical: "Documented grid creation, colored borders, drag-to-place interface, archive export functionality",
    },
    {
      type: "feature",
      category: "social",
      title: "Social Receipts Documentation",
      description: "Added complete documentation for Social Receipts - import and archive posts from Farcaster and X/Twitter",
      technical: "Added to net-library-specs.html: importing workflow, receipt display (feed/detail views), verification badges, share & embed, use cases (accountability, research, personal, legal), related files list",
    },
    {
      type: "docs",
      category: "api",
      title: "Code Documentation Updates",
      description: "Updated source files API to include Social Receipt components, updated relay upload hooks to v2, added relay-upload-utils.ts",
      technical: "Updated net-library-docs.html with Social Receipt components/files, v2 relay hooks, and utility files",
    },
    {
      type: "improvement",
      category: "membership",
      title: "Member Download ZIP Updated",
      description: "Member download package now includes all latest files including Grids and Social Receipts code",
    },
  ];

  return addChangelogEntry(
    changes,
    "Documentation overhaul: Updated all three docs pages with Grids and Social Receipts features, streamlined uploads, and code API updates",
    "minor"
  );
}

// v1.41.4 - Safari/iOS/Base App data URL fix
export async function addDataUrlFixChangelog() {
  const changes: ChangeEntry[] = [
    {
      type: "fix",
      category: "uploads",
      title: "Fixed 'Load failed' error on Base App",
      description: "Social receipt archives and image uploads now work correctly on Base App (Safari/iOS/WKWebView). Previously, users would see 'Load failed' when archiving social posts.",
      technical: "Replaced fetch() on data: URLs with manual base64 decoding. Safari/iOS/WKWebView rejects fetch requests to data URLs due to WebKit security policies.",
    },
    {
      type: "feature",
      category: "uploads",
      title: "New Data URL Utilities",
      description: "Added data-url-utils.ts with safe utilities for converting data URLs to blobs without using fetch().",
      technical: "dataUrlToBlob(), safeDataUrlToBlob(), dataUrlToFile() - manual base64 decoding that works across all platforms",
    },
    {
      type: "docs",
      category: "uploads",
      title: "Upload System Documentation Updated",
      description: "Added documentation about the Safari/iOS data URL fetch bug and the recommended safe patterns to avoid it.",
      technical: "Updated UPLOAD-SYSTEM.md with new 'Safari/iOS/Base App: Data URL Fetch Bug' section and added data-url-utils.ts to Key Files Reference",
    },
  ];

  return addChangelogEntry(
    changes,
    "Fixed 'Load failed' error when archiving social posts on Base App - Safari/iOS data URL compatibility fix",
    "patch"
  );
}

// v1.41.5 - Social receipt improvements and CDN URL fix
export async function addSocialReceiptImprovementsChangelog() {
  const changes: ChangeEntry[] = [
    {
      type: "improvement",
      category: "social",
      title: "Removed unreliable engagement stats from social receipts",
      description: "Social archive receipts no longer display likes, retweets, replies, or view counts. These stats from public APIs are often inaccurate or missing.",
      technical: "Removed stats from social-receipt-upload.tsx preview and /api/social/receipt/route.tsx Satori image generation. Receipt now shows only content: author, text, images, timestamp.",
    },
    {
      type: "improvement",
      category: "social",
      title: "Updated social receipt image layout",
      description: "Receipt image redesigned: header shows 'ARCHIVED' centered, footer shows platform badge with timestamp on left and Net Library branding on right.",
      technical: "Updated receipt/route.tsx Satori layout - moved platform icon/label from header to footer, added timestamp below platform badge.",
    },
    {
      type: "fix",
      category: "uploads",
      title: "Fixed CDN URL storage for new uploads",
      description: "New uploads now correctly store the CDN URL in discovery entries. Previously, uploaded content could show a '?' error icon when viewing.",
      technical: "Added cdnUrl to createDiscoveryEntry() call in use-relay-upload-v2.ts and use-relay-batch-upload-v2.ts. CDN URL now uses correct /storage/load/ format instead of deprecated /content/ format.",
    },
    {
      type: "fix",
      category: "uploads",
      title: "Safari/iOS receipt upload fix",
      description: "Receipt API now always returns data URL instead of cover URL, fixing 'Load failed' errors on Base App when archiving social posts.",
      technical: "Modified /api/social/receipt/route.tsx to return dataUrl regardless of cover storage success. Cover storage is now fire-and-forget.",
    },
  ];

  return addChangelogEntry(
    changes,
    "Social receipts improved: removed unreliable stats, updated layout, fixed CDN URLs and Safari compatibility",
    "patch"
  );
}

// v1.42.2 - Cover upload storage fix
export async function addCoverUploadFixChangelog() {
  const changes: ChangeEntry[] = [
    {
      type: "fix",
      category: "uploads",
      title: "Fixed cover image uploads",
      description: "Cover images for social receipts and other uploads now reliably store and display. Previously, covers would fail to upload silently.",
      technical: "Migrated /api/upload-cover from Vercel Blob (which required BLOB_READ_WRITE_TOKEN) to KV database storage (/api/covers/[key]). This ensures covers always work without external dependencies.",
    },
    {
      type: "improvement",
      category: "uploads",
      title: "Cover storage uses KV database",
      description: "All cover images are now stored in the same KV database as other app data, improving reliability and simplifying infrastructure.",
      technical: "upload-cover/route.ts now uses db/kv instead of @vercel/blob. Covers are stored with 'cover:' prefix and served via /api/covers/[key] endpoint.",
    },
  ];

  return addChangelogEntry(
    changes,
    "Fixed cover image uploads - now uses reliable KV storage instead of external blob service",
    "patch"
  );
}

// v1.43.0 - Filesystem mode, stacks UX, and upvote improvements
export async function addFilesystemStacksChangelog() {
  const changes: ChangeEntry[] = [
    {
      type: "feature",
      category: "uploads",
      title: "ZIP Import for Filesystem Stacks",
      description: "Import entire ZIP archives into filesystem-mode stacks. Features drag-drop upload, extraction preview with file tree, compressed vs uncompressed size display, and selective file exclusion before upload.",
      technical: "New zip-import-modal.tsx component using JSZip for browser-side extraction. Handles common root folder stripping, sequential upload with progress tracking.",
    },
    {
      type: "improvement",
      category: "ui",
      title: "Stack card item counts now exclude hidden items",
      description: "Stack cards in All Items, All Stacks, and My Stacks subtabs now show accurate visible item count, excluding any hidden items.",
      technical: "Added visibleItemCount to Stack type. StackCard component uses visibleItemCount when available, falling back to itemCount.",
    },
    {
      type: "improvement",
      category: "ui",
      title: "Total Net Library Stats excludes hidden items",
      description: "The stats card on the Info tab now uses local discovery context (already filtered) instead of external leaderboard data for accurate item counts.",
      technical: "Changed globalStats.totalBooks to entries.length in leaderboard-tab.tsx stats card.",
    },
    {
      type: "feature",
      category: "ui",
      title: "Inline upvote buttons for stacks and grids",
      description: "Upvote counts on stack and grid lists are now clickable buttons. Single-click to upvote directly from the list without opening detail view.",
      technical: "Added inline mode to UpvoteButton component. Applied to StackCard in browse-tab.tsx and stack/grid lists in leaderboard-tab.tsx.",
    },
    {
      type: "improvement",
      category: "ui",
      title: "Consistent '+ New Stack' button labels",
      description: "All create stack buttons across subtabs now consistently say '+ New Stack' instead of varying labels.",
    },
    {
      type: "improvement",
      category: "ui",
      title: "Create stack button added to All Items subtab",
      description: "The '+ New Stack' button is now available on the All Items subtab alongside the search bar.",
    },
    {
      type: "improvement",
      category: "ui",
      title: "Replaced emojis with SVG icons",
      description: "Replaced box emoji in Batch Upload header with PackageIcon. Replaced emojis in Code Docs page accordion headers (Hooks, Recent Updates, Architecture Notes) with SVG icons.",
      technical: "Updated multi-file-upload.tsx to use PackageIcon. Updated net-library-docs.html accordion headers with inline SVGs.",
    },
  ];

  return addChangelogEntry(
    changes,
    "Filesystem stacks: ZIP import, hidden item fixes, inline upvoting, consistent UI labels, emoji-to-icon cleanup",
    "minor"
  );
}

// v1.44.0 - Filesystem upload wiring and bug fixes
export async function addFilesystemWiringChangelog() {
  const changes: ChangeEntry[] = [
    {
      type: "feature",
      category: "uploads",
      title: "Filesystem uploads now fully wired to relay",
      description: "Folder upload, ZIP import, and GitHub import modals now upload files onchain via the relay system. Files are stored on Net Protocol and linked to filesystem stacks with proper path metadata.",
      technical: "handleFsUploadFile in stack-detail.tsx uses useRelayUploadV2 hook to upload files, then calls /api/stacks with action 'add-fs-item' to add filesystem metadata (path, fileName, fileSize, mimeType).",
    },
    {
      type: "feature",
      category: "uploads",
      title: "GitHub import tracks source repository and commit",
      description: "When importing from GitHub, the stack now stores the source repository URL and commit SHA for provenance tracking.",
      technical: "handleSetSourceMeta callback sets sourceUrl, sourceType, and sourceCommit on the stack via update-metadata action. GitHubImportModal fetches actual commit SHA from GitHub API.",
    },
    {
      type: "fix",
      category: "ui",
      title: "Fixed '+ New Stack' button on All Stacks tab",
      description: "The create stack button on the All Stacks subtab now correctly opens the create stack modal instead of switching to My Stacks tab.",
      technical: "Changed onClick from setActiveSubNav('my-stacks') to setShowCreateStackModal(true) in browse-tab.tsx.",
    },
    {
      type: "improvement",
      category: "uploads",
      title: "Stack limit check before upload",
      description: "Filesystem uploads now check if the stack has room before starting the upload, preventing users from paying for uploads that would fail due to stack limits.",
      technical: "handleFsUploadFile checks items.length against stack limit (20 or unlimited) before calling uploadFile().",
    },
    {
      type: "improvement",
      category: "api",
      title: "Path sanitization for filesystem items",
      description: "File paths in filesystem stacks are now sanitized to ensure consistent format - always starting with / and no double slashes.",
      technical: "add-fs-item action in /api/stacks/route.ts sanitizes path with cleanPath before storing.",
    },
    {
      type: "docs",
      category: "other",
      title: "Code docs updated with filesystem stack files",
      description: "Source files API now includes filesystem stack components: folder-upload-modal, zip-import-modal, github-import-modal, folder-tree-view, types-filesystem, and github-tree API.",
    },
  ];

  return addChangelogEntry(
    changes,
    "Filesystem stacks fully wired: relay upload integration, GitHub source tracking, stack limit checks, path sanitization, bug fixes",
    "minor"
  );
}

// v1.45.0 - Attribution fix, UI improvements, +New Item button
export async function addAttributionAndUIFixesChangelog() {
  const changes: ChangeEntry[] = [
    {
      type: "fix",
      category: "ui",
      title: "Fixed uploader attribution in stack detail view",
      description: "Items viewed via stacks now correctly show the actual uploader's username and profile picture, not the relay backend wallet address.",
      technical: "Updated itemToBook() in stack-detail.tsx to prefer uploaderUsername/uploaderAddress/uploaderPfpUrl over operator. Added uploader fields to entryMap type.",
    },
    {
      type: "feature",
      category: "ui",
      title: "Added '+New Item' button to browse feed",
      description: "Quick upload button added next to search bar on All Items view. Click to navigate directly to the Upload tab.",
      technical: "Added button with UploadIcon that dispatches 'navigate-to-tab' event with 'upload' detail.",
    },
    {
      type: "improvement",
      category: "ui",
      title: "Filesystem stacks have distinct border styling",
      description: "Stack cards for filesystem stacks now have a more prominent neon green border to visually distinguish them from standard stacks.",
      technical: "StackCard in browse-tab.tsx checks stack.isFileSystem and applies border-[#00ff00]/40 (vs /20 for standard stacks).",
    },
    {
      type: "fix",
      category: "ui",
      title: "Fixed all cyan/teal colors in filesystem features",
      description: "Replaced all cyan accent colors with neon green (#00ff00) across filesystem stack UI: info bar, import buttons, empty state, source type badge.",
      technical: "Updated stack-detail.tsx: filesystem badge, info bar stats, source URL link, import buttons (Add Folder, GitHub, Import ZIP), empty tree state icon.",
    },
    {
      type: "improvement",
      category: "ui",
      title: "Replaced emojis with icons in filesystem buttons",
      description: "Import buttons now use proper SVG icons instead of emoji characters for consistent visual style.",
      technical: "Replaced 🐙 with GlobeIcon, 📦 with PackageIcon in stack-detail.tsx filesystem import buttons.",
    },
    {
      type: "improvement",
      category: "ui",
      title: "Actions dropdown menu for filesystem stacks",
      description: "Consolidated multiple action buttons into a single 'Actions' dropdown menu for cleaner UI. Shows import options for filesystem stacks and edit option for all owner-managed stacks.",
      technical: "Replaced inline buttons with MoreIcon dropdown in stack-detail.tsx. Menu shows Add Folder, Import from GitHub, Import ZIP for filesystem stacks, plus Edit Stack for all stacks.",
    },
    {
      type: "fix",
      category: "ui",
      title: "Fixed user uploads filter to check uploaderAddress",
      description: "The 'Add to Stack' modal now correctly finds user's uploads by checking uploaderAddress first, then operator as fallback.",
      technical: "Updated userUploadsNotInStack filter in stack-detail.tsx to prefer uploaderAddress over operator for relay uploads.",
    },
  ];

  return addChangelogEntry(
    changes,
    "Attribution fix (Farcaster identity), Actions dropdown, +New Item button, filesystem stack borders",
    "minor"
  );
}
src/app/embed/card/[address]/library-card-widget.tsx
"use client";

import Image from "next/image";
import { BadgeCheck } from "lucide-react";
import type { MemberEntry } from "@/lib/net-protocol";
import { EmbedFooter } from "@/app/embed/components/embed-footer";

interface LibraryCardWidgetProps {
  address: string;
  stats: {
    member: MemberEntry | null;
    uploads: number;
    totalBytes: number;
    stackCount: number;
    gridCount: number;
    rank: number | null;
    pfpUrl: string | null;
    agentName: string | null; // Fresh name from agent record
    farcasterHandle?: string | null; // True Farcaster handle from Neynar (e.g. "cherylfromnet")
    erc8004Verified?: boolean; // ERC-8004 Base Identity Registry verified
  };
}

function formatBytes(bytes: number): string {
  if (bytes === 0) return "0";
  const mb = bytes / (1024 * 1024);
  return mb.toFixed(1);
}

function truncateAddress(address: string): string {
  return `${address.slice(0, 6)}...${address.slice(-4)}`;
}

export function LibraryCardWidget({ address, stats }: LibraryCardWidgetProps) {
  const { member, uploads, totalBytes, stackCount, gridCount, rank, pfpUrl, agentName, farcasterHandle, erc8004Verified } = stats;
  const profileUrl = `https://netlibrary.app/user/${address}`;

  // Use fresh agent name if available, fallback to member.username (display name)
  const displayName = agentName || member?.username || `Member ${member?.memberId}`;
  // Resolved Farcaster handle (e.g. "cherylfromnet") — separate from display name
  const resolvedHandle = farcasterHandle || member?.farcasterUsername || member?.username;

  // Non-member card
  if (!member) {
    return (
      <div className="min-h-screen flex items-center justify-center p-2">
        <div className="w-full max-w-sm">
          <div className="relative overflow-hidden rounded-xl border border-gray-700 bg-gradient-to-br from-[#0a0a0a] via-[#111] to-[#0a0a0a]">
            <a
              href={profileUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="block p-4 hover:bg-white/5 transition-colors"
            >
              <div className="flex items-center gap-3">
                <div className="w-12 h-12 rounded-full bg-gray-800 flex items-center justify-center">
                  <span className="text-xl">👤</span>
                </div>
                <div className="flex-1 min-w-0">
                  <div className="text-sm font-mono text-gray-400">
                    {truncateAddress(address)}
                  </div>
                  <div className="text-[10px] font-mono text-gray-600 uppercase">
                    Non-member
                  </div>
                </div>
              </div>

              {/* Stats */}
              {uploads > 0 && (
                <div className="grid grid-cols-2 gap-2 mt-3 pt-3 border-t border-gray-800">
                  <div className="text-center">
                    <div className="text-lg font-mono font-bold text-gray-400">{uploads}</div>
                    <div className="text-[9px] font-mono text-gray-600 uppercase">Uploads</div>
                  </div>
                  <div className="text-center">
                    <div className="text-lg font-mono font-bold text-gray-400">{formatBytes(totalBytes)}</div>
                    <div className="text-[9px] font-mono text-gray-600 uppercase">MB</div>
                  </div>
                </div>
              )}
            </a>
            <EmbedFooter />
          </div>
        </div>
      </div>
    );
  }

  // Member card - styled like the full library card
  return (
    <div className="min-h-screen flex items-center justify-center p-2">
      <div className="w-full max-w-sm">
        <a
          href={profileUrl}
          target="_blank"
          rel="noopener noreferrer"
          className="block"
        >
          <div className="relative overflow-hidden rounded-xl border-2 border-[#00ff00]/50 bg-gradient-to-br from-[#0a0a0a] via-[#0d1a0d] to-[#0a0a0a] shadow-[0_0_30px_rgba(0,255,0,0.15)] hover:shadow-[0_0_40px_rgba(0,255,0,0.25)] transition-shadow">
            {/* Scanline effect overlay */}
            <div className="absolute inset-0 bg-[linear-gradient(transparent_50%,rgba(0,0,0,0.1)_50%)] bg-[length:100%_4px] pointer-events-none opacity-30" />

            {/* Glowing corner accents */}
            <div className="absolute top-0 left-0 w-16 h-16 bg-gradient-to-br from-[#00ff00]/20 to-transparent" />
            <div className="absolute bottom-0 right-0 w-16 h-16 bg-gradient-to-tl from-[#00ff00]/20 to-transparent" />

            {/* Card Header */}
            <div className="relative px-4 py-2 border-b border-[#00ff00]/30 bg-[#00ff00]/5">
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <div className="w-2 h-2 rounded-full bg-[#00ff00] animate-pulse shadow-[0_0_8px_#00ff00]" />
                  <span className="text-[10px] font-mono text-[#00ff00]/70 tracking-[0.2em] uppercase">Net Protocol</span>
                </div>
                <span className="text-[10px] font-mono text-[#00ff00]">
                  Member #{member.memberId}
                </span>
              </div>
            </div>

            {/* Main Card Content */}
            <div className="relative p-4">
              {/* Top Section - Photo & Identity */}
              <div className="flex gap-4">
                {/* Photo with frame - orange ring if ERC-8004 verified */}
                <div className="relative">
                  <div className={`w-16 h-20 rounded-lg border-2 overflow-hidden bg-black shadow-[inset_0_0_20px_rgba(0,255,0,0.1)] ${
                    erc8004Verified ? "border-orange-500 ring-2 ring-orange-500" : "border-[#00ff00]/50"
                  }`}>
                    {pfpUrl ? (
                      <Image
                        src={pfpUrl}
                        alt={displayName}
                        width={64}
                        height={80}
                        className="w-full h-full object-cover"
                        unoptimized
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center bg-[#00ff00]/10">
                        <span className="text-[#00ff00] font-mono text-xl font-bold">
                          {member.memberId}
                        </span>
                      </div>
                    )}
                  </div>
                  {/* Holographic shine effect */}
                  <div className="absolute inset-0 rounded-lg bg-gradient-to-br from-white/10 via-transparent to-transparent pointer-events-none" />
                </div>

                {/* Identity Info */}
                <div className="flex-1 min-w-0">
                  <div className="text-[#00ff00] font-mono font-bold text-base leading-tight truncate">
                    {displayName}
                  </div>
                  {resolvedHandle && (
                    <div className="text-[#00ff00]/60 font-mono text-xs truncate">
                      @{resolvedHandle}
                    </div>
                  )}
                  <div className="mt-2 flex items-center gap-2">
                    <span className="text-[9px] font-mono font-bold tracking-wider text-[#00ff00]">
                      MEMBER
                    </span>
                    {member.isAgent && (
                      <span className="inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded bg-purple-500/20 border border-purple-500/30">
                        <span className="text-[7px] font-mono text-purple-400 font-bold">AGENT</span>
                        {erc8004Verified && (
                          <BadgeCheck className="w-3 h-3 text-orange-500" />
                        )}
                      </span>
                    )}
                    {rank && rank <= 100 && (
                      <span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-[#00ff00]/20 border border-[#00ff00]/30">
                        <span className="text-[7px]">🏆</span>
                        <span className="text-[7px] font-mono text-[#00ff00] font-bold">#{rank}</span>
                      </span>
                    )}
                  </div>
                  {member.ensSubname && (
                    <div className="text-[9px] font-mono text-[#00ff00]/70 mt-1 truncate">
                      {member.ensSubname}
                    </div>
                  )}
                </div>

                {/* Net Library Crest */}
                <div className="w-12 flex-shrink-0 opacity-30" style={{ mixBlendMode: 'screen' }}>
                  <Image
                    src="/app-logo.png"
                    alt="Net Library"
                    width={48}
                    height={48}
                    className="w-full h-auto"
                  />
                </div>
              </div>

              {/* Wallet Address */}
              <div className="mt-2">
                <span className="text-[8px] font-mono text-gray-500 tracking-wider truncate block">
                  {member.address}
                </span>
              </div>

              {/* Divider with circuit pattern */}
              <div className="relative h-px bg-[#00ff00]/20 my-3">
                <div className="absolute left-0 top-1/2 -translate-y-1/2 w-1.5 h-1.5 rounded-full bg-[#00ff00]/40" />
                <div className="absolute right-0 top-1/2 -translate-y-1/2 w-1.5 h-1.5 rounded-full bg-[#00ff00]/40" />
                <div className="absolute left-1/3 top-1/2 -translate-y-1/2 w-1 h-1 rounded-full bg-[#00ff00]/30" />
                <div className="absolute left-2/3 top-1/2 -translate-y-1/2 w-1 h-1 rounded-full bg-[#00ff00]/30" />
              </div>

              {/* Stats Grid */}
              <div className="grid grid-cols-4 gap-1.5">
                <div className="flex flex-col items-center justify-center p-1.5 rounded-lg bg-black/50 border border-[#00ff00]/20">
                  <div className="text-base font-bold text-[#00ff00] font-mono leading-none">
                    {stackCount}
                  </div>
                  <div className="text-[7px] text-gray-500 font-mono uppercase tracking-wider">Stacks</div>
                </div>
                <div className="flex flex-col items-center justify-center p-1.5 rounded-lg bg-black/50 border border-[#00ff00]/20">
                  <div className="text-base font-bold text-[#00ff00] font-mono leading-none">
                    {gridCount}
                  </div>
                  <div className="text-[7px] text-gray-500 font-mono uppercase tracking-wider">Grids</div>
                </div>
                <div className="flex flex-col items-center justify-center p-1.5 rounded-lg bg-black/50 border border-[#00ff00]/20">
                  <div className="text-base font-bold text-[#00ff00] font-mono leading-none">
                    {uploads}
                  </div>
                  <div className="text-[7px] text-gray-500 font-mono uppercase tracking-wider">Uploads</div>
                </div>
                <div className="flex flex-col items-center justify-center p-1.5 rounded-lg bg-black/50 border border-[#00ff00]/20">
                  <div className="text-base font-bold text-[#00ff00] font-mono leading-none">
                    {formatBytes(totalBytes)}
                  </div>
                  <div className="text-[7px] text-gray-500 font-mono uppercase tracking-wider">MB</div>
                </div>
              </div>
            </div>
          </div>
        </a>
        <EmbedFooter />
      </div>
    </div>
  );
}
src/app/embed/card/[address]/page.tsx
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry, MemberRegistry, MemberEntry } from "@/lib/net-protocol";
import { LibraryCardWidget } from "@/app/embed/card/[address]/library-card-widget";

interface RegisteredAgent {
  id: string;
  name: string;
  apiKey: string;
  permissions: string[];
  createdAt: number;
  fid?: number;
  address?: string;
  pfpUrl?: string;
  isActive?: boolean;
}

interface MemberStats {
  member: MemberEntry | null;
  uploads: number;
  totalBytes: number;
  stackCount: number;
  gridCount: number;
  rank: number | null;
  pfpUrl: string | null;
  agentName: string | null; // Fresh name from agent record
  farcasterHandle: string | null; // True Farcaster handle from Neynar (e.g. "cherylfromnet")
}

// Fetch member and stats from database
async function fetchMemberStats(address: string): Promise<MemberStats> {
  const normalizedAddress = address.toLowerCase();

  try {
    // Fetch member registry
    const registryResult = await db.select().from(kv).where(eq(kv.key, "member-registry")).limit(1);
    const registry: MemberRegistry | null = registryResult[0]?.value
      ? JSON.parse(registryResult[0].value)
      : null;

    // Find member by address or linked addresses
    let member: MemberEntry | null = null;
    if (registry) {
      member = registry.members.find(
        m =>
          m.address.toLowerCase() === normalizedAddress ||
          m.linkedAddresses?.some(a => a.toLowerCase() === normalizedAddress)
      ) || null;
    }

    // Fetch discovery index for upload stats
    const discoveryResult = await db.select().from(kv).where(eq(kv.key, "discovery-index")).limit(1);
    const entries: DiscoveryEntry[] = discoveryResult[0]?.value
      ? JSON.parse(discoveryResult[0].value)
      : [];

    // Get user's uploads (visible only).
    // Check uploaderAddress first — relay uploads store the backend wallet as `operator`
    // and the actual user's wallet as `uploaderAddress`. Fall back to operator for legacy entries.
    const userUploads = entries.filter(
      e => !e.hidden && (
        (e.uploaderAddress && e.uploaderAddress.toLowerCase() === normalizedAddress) ||
        e.operator.toLowerCase() === normalizedAddress
      )
    );
    const totalBytes = userUploads.reduce((sum, e) => sum + (e.fileSize || 0), 0);

    // Fetch stacks for this user
    const userStacksResult = await db.select().from(kv).where(eq(kv.key, `user-stacks:${normalizedAddress}`)).limit(1);
    const stackIds: string[] = userStacksResult[0]?.value
      ? JSON.parse(userStacksResult[0].value)
      : [];

    // Fetch grids for this user
    const userGridsResult = await db.select().from(kv).where(eq(kv.key, `user-grids:${normalizedAddress}`)).limit(1);
    const gridIds: string[] = userGridsResult[0]?.value
      ? JSON.parse(userGridsResult[0].value)
      : [];

    // Calculate rank from leaderboard
    const leaderboardResult = await db.select().from(kv).where(eq(kv.key, "leaderboard-index")).limit(1);
    let rank: number | null = null;
    if (leaderboardResult[0]?.value) {
      const leaderboard = JSON.parse(leaderboardResult[0].value);
      const sortedEntries = (leaderboard.entries || []).sort(
        (a: { totalUploads: number }, b: { totalUploads: number }) => b.totalUploads - a.totalUploads
      );
      const userRankIndex = sortedEntries.findIndex(
        (e: { address: string }) => e.address.toLowerCase() === normalizedAddress
      );
      if (userRankIndex !== -1) {
        rank = userRankIndex + 1;
      }
    }

    // If member is an agent, fetch fresh agent data for name and PFP
    let agentName: string | null = null;
    let agentPfpUrl: string | null = null;

    if (member?.isAgent && member.agentId) {
      try {
        const agentResult = await db.select().from(kv).where(eq(kv.key, `api-agent:${member.agentId}`)).limit(1);
        if (agentResult[0]?.value) {
          const agent: RegisteredAgent = JSON.parse(agentResult[0].value);
          // Use agent's current name and PFP (fresh, not cached)
          if (agent.name) agentName = agent.name;
          if (agent.pfpUrl) agentPfpUrl = agent.pfpUrl;
        }
      } catch {
        // Ignore - will use member data as fallback
      }
    }

    // Get PFP priority: agent pfpUrl > customPfpUrl > Neynar lookup > dicebear
    let pfpUrl: string | null = agentPfpUrl || member?.customPfpUrl || null;
    // True Farcaster handle from Neynar (e.g. "cherylfromnet"), distinct from member.username
    let farcasterHandle: string | null = member?.farcasterUsername || null;
    if (member?.fid) {
      // Fetch PFP and Farcaster handle from Neynar API
      try {
        const neynarResponse = await fetch(
          `https://api.neynar.com/v2/farcaster/user/bulk?fids=${member.fid}`,
          {
            headers: {
              // eslint-disable-next-line @neynar/no-process-env
              "x-api-key": process.env.NEYNAR_API_KEY || "",
            },
          }
        );
        if (neynarResponse.ok) {
          const neynarData = await neynarResponse.json();
          const neynarUser = neynarData.users?.[0];
          if (!pfpUrl && neynarUser?.pfp_url) pfpUrl = neynarUser.pfp_url;
          // Capture real Farcaster handle (username from Neynar is always the handle)
          if (neynarUser?.username) farcasterHandle = neynarUser.username;
        }
      } catch {
        // Ignore - will use fallback
      }
    }
    // Fallback to dicebear
    if (!pfpUrl) {
      pfpUrl = `https://api.dicebear.com/7.x/identicon/svg?seed=${normalizedAddress}`;
    }

    return {
      member,
      uploads: userUploads.length,
      totalBytes,
      stackCount: stackIds.length,
      gridCount: gridIds.length,
      rank,
      pfpUrl,
      agentName,
      farcasterHandle,
    };
  } catch (error) {
    console.error("Failed to fetch member stats:", error);
    return {
      member: null,
      uploads: 0,
      totalBytes: 0,
      stackCount: 0,
      gridCount: 0,
      rank: null,
      pfpUrl: `https://api.dicebear.com/7.x/identicon/svg?seed=${address.toLowerCase()}`,
      agentName: null,
      farcasterHandle: null,
    };
  }
}

export default async function LibraryCardEmbedPage({
  params,
}: {
  params: Promise<{ address: string }>;
}) {
  const { address } = await params;
  const stats = await fetchMemberStats(address);

  return <LibraryCardWidget address={address} stats={stats} />;
}
src/app/embed/feed/feed-widget.tsx
"use client";

import Image from "next/image";
import type { DiscoveryEntry } from "@/lib/net-protocol";
import { EmbedFooter } from "@/app/embed/components/embed-footer";

interface FeedWidgetProps {
  items: DiscoveryEntry[];
  uploaderUsername?: string | null;
}

function formatDate(timestamp?: number): string {
  if (!timestamp) return "";
  const date = new Date(timestamp);
  return date.toLocaleDateString("en-US", { month: "short", day: "numeric" });
}

function truncateText(text: string, maxLength: number): string {
  if (text.length <= maxLength) return text;
  return text.slice(0, maxLength - 3) + "...";
}

// Capitalize first letter of username
function capitalizeFirst(str: string): string {
  if (!str) return str;
  return str.charAt(0).toUpperCase() + str.slice(1);
}

export function FeedWidget({ items, uploaderUsername }: FeedWidgetProps) {
  // Build title - "Username's Net Library Feed" or just "Net Library"
  // Capitalize the username for better appearance
  const displayUsername = uploaderUsername ? capitalizeFirst(uploaderUsername) : null;
  const headerTitle = displayUsername
    ? `${displayUsername}'s Net Library Feed`
    : "Net Library";
  if (items.length === 0) {
    return (
      <div className="min-h-screen flex items-center justify-center p-2">
        <div className="w-full max-w-md rounded-xl border border-[#00ff00]/30 bg-[#0d0d0d] overflow-hidden shadow-[0_0_20px_rgba(0,255,0,0.1)]">
          <div className="p-8 text-center">
            <div className="text-3xl mb-2">📚</div>
            <div className="text-sm font-mono text-gray-400">No items found</div>
          </div>
          <EmbedFooter />
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen flex items-center justify-center p-2">
      <div className="w-full max-w-md rounded-xl border border-[#00ff00]/30 bg-[#0d0d0d] overflow-hidden shadow-[0_0_20px_rgba(0,255,0,0.1)]">
        {/* Header */}
        <div className="px-4 py-3 border-b border-[#00ff00]/20 flex items-center justify-between">
          <div className="flex items-center gap-2">
            <span className="text-lg">📚</span>
            <span className="text-sm font-mono text-[#00ff00]">{headerTitle}</span>
          </div>
          <span className="text-[10px] font-mono text-gray-500">
            {items.length} item{items.length !== 1 ? "s" : ""}
          </span>
        </div>

        {/* Feed List */}
        <div className="max-h-[320px] overflow-y-auto">
          {items.map((item, index) => (
            <a
              key={item.contentKey}
              href={`https://netlibrary.app/item/${item.contentKey}`}
              target="_blank"
              rel="noopener noreferrer"
              className={`flex items-center gap-3 px-4 py-3 hover:bg-[#00ff00]/5 transition-colors ${
                index !== items.length - 1 ? "border-b border-gray-800/50" : ""
              }`}
            >
              {/* Cover Thumbnail */}
              <div className="w-10 h-14 rounded bg-gray-800 flex-shrink-0 overflow-hidden">
                {item.coverUrl ? (
                  <Image
                    src={item.coverUrl}
                    alt={item.title}
                    width={40}
                    height={56}
                    className="w-full h-full object-cover"
                  />
                ) : (
                  <div className="w-full h-full flex items-center justify-center text-lg">
                    📖
                  </div>
                )}
              </div>

              {/* Info */}
              <div className="flex-1 min-w-0">
                <div className="text-sm font-mono text-white truncate">
                  {truncateText(item.title, 35)}
                </div>
                {item.author && (
                  <div className="text-[10px] font-mono text-gray-500 truncate">
                    {truncateText(item.author, 30)}
                  </div>
                )}
                <div className="flex items-center gap-2 mt-1">
                  {item.categories?.[0] && (
                    <span className="text-[9px] font-mono px-1.5 py-0.5 rounded bg-[#00ff00]/10 text-[#00ff00]">
                      {item.categories[0]}
                    </span>
                  )}
                  {item.uploadedAt && (
                    <span className="text-[9px] font-mono text-gray-600">
                      {formatDate(item.uploadedAt)}
                    </span>
                  )}
                </div>
              </div>

              {/* Arrow */}
              <div className="text-gray-600 text-xs">→</div>
            </a>
          ))}
        </div>

        {/* Footer */}
        <EmbedFooter />
      </div>
    </div>
  );
}
src/app/embed/feed/page.tsx
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry, MemberRegistry } from "@/lib/net-protocol";
import { FeedWidget } from "@/app/embed/feed/feed-widget";

// Fetch feed items from database
async function fetchFeedItems(params: {
  category?: string;
  uploader?: string;
  limit?: number;
}) {
  try {
    const discoveryResult = await db.select().from(kv).where(eq(kv.key, "discovery-index")).limit(1);
    let entries: DiscoveryEntry[] = discoveryResult[0]?.value
      ? JSON.parse(discoveryResult[0].value)
      : [];

    // Filter out hidden entries
    entries = entries.filter(e => !e.hidden);

    // Apply filters
    if (params.category) {
      entries = entries.filter(e =>
        e.categories?.some(c => c.toLowerCase() === params.category?.toLowerCase())
      );
    }

    if (params.uploader) {
      const uploaderAddr = params.uploader.toLowerCase();
      entries = entries.filter(e =>
        (e.uploaderAddress && e.uploaderAddress.toLowerCase() === uploaderAddr) ||
        e.operator.toLowerCase() === uploaderAddr
      );
    }

    // Sort by most recent
    entries.sort((a, b) => (b.uploadedAt || 0) - (a.uploadedAt || 0));

    // Limit results
    const limit = params.limit || 10;
    entries = entries.slice(0, limit);

    return entries;
  } catch (error) {
    console.error("Failed to fetch feed:", error);
    return [];
  }
}

// Get username for an address from member registry
async function getUploaderUsername(address: string): Promise<string | null> {
  try {
    const registryResult = await db.select().from(kv).where(eq(kv.key, "member-registry")).limit(1);
    if (!registryResult[0]?.value) return null;

    const registry: MemberRegistry = JSON.parse(registryResult[0].value);
    const normalizedAddress = address.toLowerCase();

    const member = registry.members.find(
      m => m.address.toLowerCase() === normalizedAddress ||
           m.linkedAddresses?.some(a => a.toLowerCase() === normalizedAddress)
    );

    // Return display name (customUsername first, then username, then null)
    return member?.customUsername || member?.username || null;
  } catch {
    return null;
  }
}

export default async function FeedEmbedPage({
  searchParams,
}: {
  searchParams: Promise<{ category?: string; uploader?: string; limit?: string }>;
}) {
  const params = await searchParams;
  const items = await fetchFeedItems({
    category: params.category,
    uploader: params.uploader,
    limit: params.limit ? parseInt(params.limit, 10) : 10,
  });

  // Get username if filtering by uploader
  let uploaderUsername: string | null = null;
  if (params.uploader) {
    uploaderUsername = await getUploaderUsername(params.uploader);
  }

  return <FeedWidget items={items} uploaderUsername={uploaderUsername} />;
}
src/app/embed/grid/[gridId]/grid-widget.tsx
"use client";

import Image from "next/image";
import { EmbedFooter } from "@/app/embed/components/embed-footer";
import type { GridWithStats, GridCell } from "@/lib/net-protocol";

interface GridWidgetProps {
  grid: GridWithStats | null;
  cells: GridCell[];
}

export function GridWidget({ grid, cells }: GridWidgetProps) {
  if (!grid) {
    return (
      <div className="min-h-screen flex items-center justify-center p-4">
        <div className="w-full max-w-md rounded-xl border border-[#1a1a1a] bg-[#0d0d0d] overflow-hidden">
          <div className="p-6 text-center">
            <div className="text-4xl mb-4">?</div>
            <p className="text-gray-400 font-mono text-sm">Grid not found</p>
          </div>
          <EmbedFooter />
        </div>
      </div>
    );
  }

  // Create a map of cells by position
  const cellMap = new Map<string, GridCell>();
  cells.forEach((cell) => {
    cellMap.set(`${cell.row}-${cell.col}`, cell);
  });

  // Calculate display size - show up to 5x5 preview
  const displaySize = Math.min(grid.size, 5);
  const cellSize = 48; // Each cell is 48x48 pixels
  const gap = 2;

  return (
    <div className="min-h-screen flex items-center justify-center p-2">
      <div className="w-full max-w-md rounded-xl border border-[#00ff00]/30 bg-[#0d0d0d] overflow-hidden shadow-[0_0_20px_rgba(0,255,0,0.1)]">
        {/* Header */}
        <div className="px-4 py-3 border-b border-[#00ff00]/20">
          <div className="flex items-center justify-between">
            <div className="flex-1 min-w-0">
              <h2 className="text-sm font-mono text-[#00ff00] font-bold truncate">
                {grid.name}
              </h2>
              {grid.subtitle && (
                <p className="text-[11px] font-mono text-gray-400 mt-0.5 truncate">
                  {grid.subtitle}
                </p>
              )}
              <p className="text-[10px] font-mono text-gray-500 mt-0.5">
                {grid.size}x{grid.size} Grid
              </p>
            </div>
            <div className="flex items-center gap-3 shrink-0 ml-3">
              <div className="text-center">
                <div className="text-sm font-mono font-bold text-[#00ff00]">
                  {grid.cellCount}
                </div>
                <div className="text-[8px] font-mono text-gray-500">filled</div>
              </div>
              <div className="text-center">
                <div className="text-sm font-mono font-bold text-[#00ff00]">
                  {grid.upvoteCount}
                </div>
                <div className="text-[8px] font-mono text-gray-500">upvotes</div>
              </div>
            </div>
          </div>
        </div>

        {/* Grid Preview */}
        <div className="p-4 flex justify-center">
          <div
            className="rounded-lg overflow-hidden bg-black p-1"
            style={{
              display: "grid",
              gridTemplateColumns: `repeat(${displaySize}, ${cellSize}px)`,
              gridTemplateRows: `repeat(${displaySize}, ${cellSize}px)`,
              gap: `${gap}px`,
            }}
          >
            {Array.from({ length: displaySize * displaySize }).map((_, index) => {
              const row = Math.floor(index / displaySize);
              const col = index % displaySize;
              const cell = cellMap.get(`${row}-${col}`);

              if (cell) {
                const isVideo = cell.contentType?.startsWith("video/");
                // Build display URL - use coverUrl from discovery index (already has working URLs)
                let displayUrl = '';
                if (cell.coverUrl) {
                  // Use the coverUrl directly - these are stored from when content was indexed
                  displayUrl = cell.coverUrl;
                } else if (cell.cdnUrl) {
                  // Fallback to cdnUrl
                  displayUrl = cell.cdnUrl;
                }
                // Build video URL using media proxy if we have operator/contentKey
                let videoUrl = '';
                if (cell.operator && cell.contentKey) {
                  videoUrl = `/api/media/${cell.operator}/${cell.contentKey}`;
                } else if (cell.cdnUrl) {
                  videoUrl = cell.cdnUrl;
                }

                return (
                  <div
                    key={`${row}-${col}`}
                    className="rounded-sm overflow-hidden bg-[#111] border border-[#00ff00]/20"
                    style={{ width: cellSize, height: cellSize }}
                  >
                    {isVideo && videoUrl ? (
                      <video
                        src={videoUrl}
                        className="w-full h-full object-cover"
                        muted
                        loop
                        playsInline
                        autoPlay
                      />
                    ) : displayUrl ? (
                      <Image
                        src={displayUrl}
                        alt={cell.title || "Grid cell"}
                        width={cellSize}
                        height={cellSize}
                        className="w-full h-full object-cover"
                        unoptimized
                      />
                    ) : (
                      <div className="w-full h-full flex items-center justify-center text-[#00ff00]/30 text-lg">
                        +
                      </div>
                    )}
                  </div>
                );
              }

              // Empty cell
              return (
                <div
                  key={`${row}-${col}`}
                  className="rounded-sm bg-[#111] border border-[#1a1a1a] flex items-center justify-center"
                  style={{ width: cellSize, height: cellSize }}
                >
                  <span className="text-[#00ff00]/20 text-lg">+</span>
                </div>
              );
            })}
          </div>
        </div>

        {/* Stats Row - only show preview note for large grids */}
        {grid.size > 5 && (
          <div className="px-4 pb-3 flex justify-center">
            <div className="text-xs font-mono text-gray-500">
              Showing 5x5 preview
            </div>
          </div>
        )}

        {/* Footer */}
        <EmbedFooter />
      </div>
    </div>
  );
}
src/app/embed/grid/[gridId]/page.tsx
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { Grid, GridCell, GridCells, GridWithStats } from "@/lib/net-protocol";
import { GridWidget } from "@/app/embed/grid/[gridId]/grid-widget";

// Helper to get KV value
async function getKV<T>(key: string): Promise<T | null> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, key)).limit(1);
    if (!result[0]?.value) return null;
    return JSON.parse(result[0].value) as T;
  } catch {
    return null;
  }
}

// Discovery entry type
interface DiscoveryEntry {
  contentKey?: string;
  operator?: string;
  cdnUrl?: string;
  coverUrl?: string;
  title?: string;
}

// Extract content key from various CDN URL formats
function extractContentKey(url: string): string | null {
  if (!url) return null;
  const normalized = url.toLowerCase().trim();

  // Format: direct 0x... key in URL
  const hexMatch = normalized.match(/(0x[a-f0-9]{64})/i);
  if (hexMatch) return hexMatch[1];

  // Format: storedon.net/content/{key}
  const contentMatch = normalized.match(/storedon\.net\/content\/([^/?#]+)/);
  if (contentMatch) return contentMatch[1];

  // Format: storedon.net/net/{chainId}/storage/raw/{operator}/{key}
  const storageMatch = normalized.match(/storedon\.net\/net\/\d+\/storage\/(?:raw|load)\/[^/]+\/([^/?#]+)/);
  if (storageMatch) return storageMatch[1];

  // Format: storedon.net/net/{chainId}/chunked-storage/file/{operator}/{key}
  const chunkedMatch = normalized.match(/storedon\.net\/net\/\d+\/chunked-storage\/(?:file|raw)\/[^/]+\/([^/?#]+)/);
  if (chunkedMatch) return chunkedMatch[1];

  return null;
}

// Check if two URLs refer to same content
function urlsMatch(url1: string, url2: string): boolean {
  if (!url1 || !url2) return false;
  const key1 = extractContentKey(url1);
  const key2 = extractContentKey(url2);
  if (key1 && key2 && key1.toLowerCase() === key2.toLowerCase()) return true;

  // Direct URL comparison
  const n1 = url1.toLowerCase().trim();
  const n2 = url2.toLowerCase().trim();
  return n1 === n2 || n1.includes(n2) || n2.includes(n1);
}

// Enrich cells with cover URLs and contentKeys from discovery index
async function enrichCellsWithCovers(cells: GridCell[]): Promise<GridCell[]> {
  if (!cells || cells.length === 0) return [];

  try {
    const discoveryIndex = await getKV<DiscoveryEntry[]>("discovery-index") || [];

    return cells.map(cell => {
      // If cell already has coverUrl, no need to enrich
      if (cell.coverUrl) return cell;

      if (!cell.cdnUrl) return cell;

      // Try to extract contentKey from cdnUrl
      const contentKey = cell.contentKey || extractContentKey(cell.cdnUrl);

      // Find matching entry - try multiple strategies
      let matchingEntry: DiscoveryEntry | undefined;

      // 1. Exact contentKey match (most reliable)
      if (contentKey) {
        matchingEntry = discoveryIndex.find(entry =>
          entry.contentKey?.toLowerCase() === contentKey.toLowerCase()
        );
      }

      // 2. URL matching (handles different URL formats for same content)
      if (!matchingEntry) {
        matchingEntry = discoveryIndex.find(entry => {
          if (entry.cdnUrl && urlsMatch(entry.cdnUrl, cell.cdnUrl)) return true;
          if (entry.contentKey && cell.cdnUrl.toLowerCase().includes(entry.contentKey.toLowerCase())) return true;
          return false;
        });
      }

      const enriched = { ...cell };

      if (contentKey && !enriched.contentKey) {
        enriched.contentKey = contentKey;
      }

      if (matchingEntry?.coverUrl) {
        enriched.coverUrl = matchingEntry.coverUrl;
      }

      if (matchingEntry?.contentKey && !enriched.contentKey) {
        enriched.contentKey = matchingEntry.contentKey;
      }

      if (matchingEntry?.operator && !enriched.operator) {
        enriched.operator = matchingEntry.operator;
      }

      return enriched;
    });
  } catch {
    return cells;
  }
}

// Fetch grid with cells
async function fetchGrid(gridId: string): Promise<{
  grid: GridWithStats | null;
  cells: GridCells["cells"];
}> {
  try {
    const grid = await getKV<Grid>(`grid:${gridId}`);
    if (!grid || grid.deleted || grid.visibility === "hidden") {
      return { grid: null, cells: [] };
    }

    const gridCells = await getKV<GridCells>(`grid-cells:${gridId}`);
    const rawCells = gridCells?.cells || [];

    // Enrich cells with cover URLs from discovery
    const cells = await enrichCellsWithCovers(rawCells);

    // Build GridWithStats
    const gridSize = grid.size || 3;
    const gridWithStats: GridWithStats = {
      ...grid,
      cellCount: cells.length,
      totalCells: gridSize * gridSize,
      upvoteCount: 0, // Would need to fetch from contract for real count
      previewCells: cells.slice(0, 9),
    };

    return { grid: gridWithStats, cells };
  } catch (error) {
    console.error("Failed to fetch grid:", error);
    return { grid: null, cells: [] };
  }
}

export default async function GridEmbedPage({
  params,
}: {
  params: Promise<{ gridId: string }>;
}) {
  const { gridId } = await params;
  const { grid, cells } = await fetchGrid(gridId);

  return <GridWidget grid={grid} cells={cells} />;
}
src/app/embed/item/[contentKey]/item-widget.tsx
"use client";

import Image from "next/image";
import type { DiscoveryEntry } from "@/lib/net-protocol";
import { EmbedFooter } from "@/app/embed/components/embed-footer";

interface ItemWidgetProps {
  item: DiscoveryEntry | null;
}

function formatBytes(bytes: number): string {
  if (bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
}

export function ItemWidget({ item }: ItemWidgetProps) {
  if (!item) {
    return (
      <div className="min-h-screen flex items-center justify-center p-2">
        <div className="w-full max-w-md rounded-xl border border-[#00ff00]/30 bg-[#0d0d0d] overflow-hidden shadow-[0_0_20px_rgba(0,255,0,0.1)]">
          <div className="p-8 text-center">
            <div className="text-3xl mb-2">📖</div>
            <div className="text-sm font-mono text-gray-400">Item not found</div>
          </div>
          <EmbedFooter />
        </div>
      </div>
    );
  }

  const itemUrl = `https://netlibrary.app/item/${item.contentKey}`;

  return (
    <div className="min-h-screen flex items-center justify-center p-2">
      <div className="w-full max-w-md rounded-xl border border-[#00ff00]/30 bg-[#0d0d0d] overflow-hidden shadow-[0_0_20px_rgba(0,255,0,0.1)]">
        <a
          href={itemUrl}
          target="_blank"
          rel="noopener noreferrer"
          className="block p-4 hover:bg-[#00ff00]/5 transition-colors"
        >
          <div className="flex gap-4">
            {/* Cover */}
            <div className="w-20 h-28 rounded-lg bg-gray-800 flex-shrink-0 overflow-hidden shadow-lg">
              {item.coverUrl ? (
                <Image
                  src={item.coverUrl}
                  alt={item.title}
                  width={80}
                  height={112}
                  className="w-full h-full object-cover"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center text-3xl">
                  📖
                </div>
              )}
            </div>

            {/* Info */}
            <div className="flex-1 min-w-0">
              <h2 className="text-base font-mono font-bold text-white leading-tight">
                {item.title}
              </h2>
              {item.author && (
                <p className="text-xs font-mono text-gray-400 mt-1">
                  by {item.author}
                </p>
              )}

              {/* Categories */}
              {item.categories && item.categories.length > 0 && (
                <div className="flex flex-wrap gap-1 mt-2">
                  {item.categories.slice(0, 3).map(cat => (
                    <span
                      key={cat}
                      className="text-[9px] font-mono px-1.5 py-0.5 rounded bg-[#00ff00]/10 text-[#00ff00]"
                    >
                      {cat}
                    </span>
                  ))}
                </div>
              )}

              {/* Meta */}
              <div className="flex items-center gap-3 mt-3 text-[10px] font-mono text-gray-500">
                {item.fileSize && (
                  <span>{formatBytes(item.fileSize)}</span>
                )}
                {item.storageType && (
                  <span className="uppercase">{item.storageType}</span>
                )}
              </div>

              {/* View CTA */}
              <div className="mt-3 inline-flex items-center gap-1 text-xs font-mono text-[#00ff00]">
                <span>View on Net Library</span>
                <span>→</span>
              </div>
            </div>
          </div>
        </a>

        {/* Footer */}
        <EmbedFooter />
      </div>
    </div>
  );
}
src/app/embed/item/[contentKey]/page.tsx
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry } from "@/lib/net-protocol";
import { ItemWidget } from "@/app/embed/item/[contentKey]/item-widget";

// Fetch single item from database
async function fetchItem(contentKey: string): Promise<DiscoveryEntry | null> {
  try {
    const discoveryResult = await db.select().from(kv).where(eq(kv.key, "discovery-index")).limit(1);
    const entries: DiscoveryEntry[] = discoveryResult[0]?.value
      ? JSON.parse(discoveryResult[0].value)
      : [];

    const item = entries.find(e => e.contentKey === contentKey && !e.hidden);
    return item || null;
  } catch (error) {
    console.error("Failed to fetch item:", error);
    return null;
  }
}

export default async function ItemEmbedPage({
  params,
}: {
  params: Promise<{ contentKey: string }>;
}) {
  const { contentKey } = await params;
  const item = await fetchItem(contentKey);

  return <ItemWidget item={item} />;
}
src/app/embed/layout.tsx
import { Metadata } from "next";

export const metadata: Metadata = {
  title: "Net Library Embed",
  description: "Embeddable Net Library widget",
};

// Force dynamic rendering for all embed pages — they query the DB at request time
// and the root layout's wagmi/Farcaster providers can't prerender in build workers
export const dynamic = "force-dynamic";

// Embed layout - minimal wrapper for embeddable widgets
// These pages are designed to be used in iframes on external sites
export default function EmbedLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <div className="bg-[#0a0a0a] text-white min-h-screen">
      {children}
    </div>
  );
}
src/app/embed/stack/[stackId]/page.tsx
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry } from "@/lib/net-protocol";
import type { Stack, StackItem } from "@/features/app/types";
import { StackWidget } from "@/app/embed/stack/[stackId]/stack-widget";

// Helper to get KV value
async function getKV<T>(key: string): Promise<T | null> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, key)).limit(1);
    if (!result[0]?.value) return null;
    return JSON.parse(result[0].value) as T;
  } catch {
    return null;
  }
}

// Fetch stack with items
async function fetchStack(stackId: string) {
  try {
    // Fetch stack metadata
    const stack = await getKV<Stack>(`stack:${stackId}`);
    if (!stack || stack.isPrivate) {
      return { stack: null, items: [], entries: [] };
    }

    // Fetch stack items
    const items = await getKV<StackItem[]>(`stack-items:${stackId}`) || [];

    // Fetch discovery index for item details
    const discoveryResult = await db.select().from(kv).where(eq(kv.key, "discovery-index")).limit(1);
    const allEntries: DiscoveryEntry[] = discoveryResult[0]?.value
      ? JSON.parse(discoveryResult[0].value)
      : [];

    // Map items to their discovery entries
    const entryMap = new Map(allEntries.map(e => [e.contentKey, e]));
    const entries = items
      .map(item => entryMap.get(item.contentKey))
      .filter((e): e is DiscoveryEntry => e !== undefined && !e.hidden);

    return { stack, items, entries };
  } catch (error) {
    console.error("Failed to fetch stack:", error);
    return { stack: null, items: [], entries: [] };
  }
}

export default async function StackEmbedPage({
  params,
}: {
  params: Promise<{ stackId: string }>;
}) {
  const { stackId } = await params;
  const { stack, entries } = await fetchStack(stackId);

  return <StackWidget stack={stack} entries={entries} />;
}
src/app/embed/stack/[stackId]/stack-widget.tsx
"use client";

import Image from "next/image";
import type { DiscoveryEntry } from "@/lib/net-protocol";
import type { Stack } from "@/features/app/types";
import { EmbedFooter } from "@/app/embed/components/embed-footer";

interface StackWidgetProps {
  stack: Stack | null;
  entries: DiscoveryEntry[];
}

function truncateText(text: string, maxLength: number): string {
  if (text.length <= maxLength) return text;
  return text.slice(0, maxLength - 3) + "...";
}

export function StackWidget({ stack, entries }: StackWidgetProps) {
  if (!stack) {
    return (
      <div className="min-h-screen flex items-center justify-center p-2">
        <div className="w-full max-w-md rounded-xl border border-[#00ff00]/30 bg-[#0d0d0d] overflow-hidden shadow-[0_0_20px_rgba(0,255,0,0.1)]">
          <div className="p-8 text-center">
            <div className="text-3xl mb-2">📑</div>
            <div className="text-sm font-mono text-gray-400">Stack not found or is private</div>
          </div>
          <EmbedFooter />
        </div>
      </div>
    );
  }

  const stackUrl = `https://netlibrary.app/stack/${stack.id}`;

  return (
    <div className="min-h-screen flex items-center justify-center p-2">
      <div className="w-full max-w-md rounded-xl border border-[#00ff00]/30 bg-[#0d0d0d] overflow-hidden shadow-[0_0_20px_rgba(0,255,0,0.1)]">
        {/* Stack Header */}
        <a
          href={stackUrl}
          target="_blank"
          rel="noopener noreferrer"
          className="block p-4 border-b border-[#00ff00]/20 hover:bg-[#00ff00]/5 transition-colors"
        >
          <div className="flex items-start gap-3">
            {/* Stack Info */}
            <div className="flex-1 min-w-0">
              <h2 className="text-base font-mono font-bold text-white leading-tight">
                {stack.name}
              </h2>
              {stack.description && (
                <p className="text-[11px] font-mono text-gray-400 mt-1 line-clamp-2">
                  {stack.description}
                </p>
              )}
              <div className="flex items-center gap-3 mt-2">
                {/* Creator */}
                <div className="flex items-center gap-1">
                  {stack.ownerPfpUrl ? (
                    <Image
                      src={stack.ownerPfpUrl}
                      alt={stack.ownerUsername || "Creator"}
                      width={14}
                      height={14}
                      className="rounded-full"
                    />
                  ) : (
                    <span className="text-xs">👤</span>
                  )}
                  <span className="text-[10px] font-mono text-gray-500">
                    {stack.ownerUsername || `${stack.owner.slice(0, 6)}...`}
                  </span>
                </div>
                {/* Item count */}
                <span className="text-[10px] font-mono text-[#00ff00]">
                  {stack.itemCount || entries.length} item{(stack.itemCount || entries.length) !== 1 ? "s" : ""}
                </span>
              </div>
            </div>

            {/* Arrow */}
            <div className="text-gray-600 text-xs">→</div>
          </div>
        </a>

        {/* Stack Items Preview */}
        {entries.length > 0 && (
          <div className="max-h-[240px] overflow-y-auto">
            {entries.slice(0, 5).map((item, index) => (
              <a
                key={item.contentKey}
                href={`https://netlibrary.app/item/${item.contentKey}`}
                target="_blank"
                rel="noopener noreferrer"
                className={`flex items-center gap-3 px-4 py-2.5 hover:bg-[#00ff00]/5 transition-colors ${
                  index !== Math.min(entries.length - 1, 4) ? "border-b border-gray-800/50" : ""
                }`}
              >
                {/* Cover */}
                <div className="w-8 h-11 rounded bg-gray-800 flex-shrink-0 overflow-hidden">
                  {item.coverUrl ? (
                    <Image
                      src={item.coverUrl}
                      alt={item.title}
                      width={32}
                      height={44}
                      className="w-full h-full object-cover"
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-sm">
                      📖
                    </div>
                  )}
                </div>

                {/* Info */}
                <div className="flex-1 min-w-0">
                  <div className="text-xs font-mono text-white truncate">
                    {truncateText(item.title, 30)}
                  </div>
                  {item.author && (
                    <div className="text-[9px] font-mono text-gray-500 truncate">
                      {truncateText(item.author, 25)}
                    </div>
                  )}
                </div>
              </a>
            ))}

            {/* More items indicator */}
            {entries.length > 5 && (
              <a
                href={stackUrl}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center justify-center py-3 text-xs font-mono text-[#00ff00] hover:bg-[#00ff00]/5 transition-colors"
              >
                +{entries.length - 5} more items →
              </a>
            )}
          </div>
        )}

        {/* Empty state */}
        {entries.length === 0 && (
          <div className="p-6 text-center">
            <div className="text-2xl mb-2 opacity-50">📭</div>
            <div className="text-xs font-mono text-gray-500">This stack is empty</div>
          </div>
        )}

        {/* Footer */}
        <EmbedFooter />
      </div>
    </div>
  );
}
src/app/embed/stats/page.tsx
/* eslint-disable @neynar/no-process-env */
import { StatsWidget } from "@/app/embed/stats/stats-widget";

// Fetch stats from the shared API (same source as main app)
async function fetchGlobalStats() {
  try {
    // Use absolute URL for server-side fetch
    const baseUrl = process.env.NEXT_PUBLIC_URL || process.env.VERCEL_URL
      ? `https://${process.env.VERCEL_URL}`
      : "http://localhost:3021";

    const response = await fetch(`${baseUrl}/api/stats`, {
      next: { revalidate: 60 }, // Cache for 60 seconds
    });

    if (!response.ok) {
      throw new Error(`Stats API returned ${response.status}`);
    }

    const data = await response.json();

    if (data.success && data.stats) {
      return data.stats;
    }

    throw new Error("Invalid stats response");
  } catch (error) {
    console.error("Failed to fetch stats from API:", error);
    // Return zeros on error
    return {
      totalItems: 0,
      totalStacks: 0,
      totalGrids: 0,
      totalBytes: 0,
      totalMembers: 0,
      uniqueUploaders: 0,
      totalUpvotes: 0,
    };
  }
}

export default async function StatsEmbedPage() {
  const stats = await fetchGlobalStats();

  return <StatsWidget stats={stats} />;
}
src/app/embed/stats/stats-widget.tsx
"use client";

import { EmbedFooter } from "@/app/embed/components/embed-footer";

interface StatsWidgetProps {
  stats: {
    totalItems: number;
    totalStacks: number;
    totalGrids?: number;
    totalBytes: number;
    totalMembers: number;
    uniqueUploaders: number;
    totalUpvotes: number;
  };
}

export function StatsWidget({ stats }: StatsWidgetProps) {
  const dataMB = (stats.totalBytes / (1024 * 1024)).toFixed(1);

  return (
    <div className="min-h-screen flex items-center justify-center p-2">
      <div className="w-full max-w-md rounded-xl border border-[#00ff00]/30 bg-[#0d0d0d] overflow-hidden shadow-[0_0_20px_rgba(0,255,0,0.1)]">
        {/* Header */}
        <div className="px-4 py-3 border-b border-[#00ff00]/20 flex items-center justify-center">
          <span className="text-sm font-mono text-[#00ff00] font-bold">Net Library Stats</span>
        </div>

        {/* Stats Grid - 2 rows of 3 */}
        <div className="p-4 space-y-4">
          {/* Row 1: Items, Stacks, Grids, Data Stored */}
          <div className="grid grid-cols-4 gap-3">
            <div className="text-center">
              <div className="text-xl font-mono font-bold text-[#00ff00]">
                {stats.totalItems.toLocaleString()}
              </div>
              <div className="text-[9px] font-mono text-gray-400">Items</div>
            </div>
            <div className="text-center">
              <div className="text-xl font-mono font-bold text-[#00ff00]">
                {stats.totalStacks.toLocaleString()}
              </div>
              <div className="text-[9px] font-mono text-gray-400">Stacks</div>
            </div>
            <div className="text-center">
              <div className="text-xl font-mono font-bold text-[#00ff00]">
                {(stats.totalGrids || 0).toLocaleString()}
              </div>
              <div className="text-[9px] font-mono text-gray-400">Grids</div>
            </div>
            <div className="text-center">
              <div className="text-xl font-mono font-bold text-[#00ff00]">
                {dataMB}
              </div>
              <div className="text-[9px] font-mono text-gray-400">MB</div>
            </div>
          </div>

          {/* Row 2: Members, Contributors, Upvotes */}
          <div className="grid grid-cols-3 gap-4">
            <div className="text-center">
              <div className="text-2xl font-mono font-bold text-[#00ff00]">
                {stats.totalMembers.toLocaleString()}
              </div>
              <div className="text-[10px] font-mono text-gray-400">Members</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-mono font-bold text-[#00ff00]">
                {stats.uniqueUploaders.toLocaleString()}
              </div>
              <div className="text-[10px] font-mono text-gray-400">Contributors</div>
            </div>
            <div className="text-center">
              <div className="text-2xl font-mono font-bold text-[#00ff00]">
                {stats.totalUpvotes.toLocaleString()}
              </div>
              <div className="text-[10px] font-mono text-gray-400">Upvotes</div>
            </div>
          </div>
        </div>

        {/* Footer */}
        <EmbedFooter />
      </div>
    </div>
  );
}
src/app/embed/user/[address]/page.tsx
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry, MemberRegistry, MemberEntry } from "@/lib/net-protocol";
import { UserWidget } from "@/app/embed/user/[address]/user-widget";

interface UserStats {
  address: string;
  member: MemberEntry | null;
  uploads: DiscoveryEntry[];
  uploadCount: number;
  totalBytes: number;
  pfpUrl: string | null;
  displayName: string;
}

// Fetch user stats from database
async function fetchUserStats(address: string): Promise<UserStats> {
  const normalizedAddress = address.toLowerCase();

  try {
    // Fetch discovery index for user's uploads
    const discoveryResult = await db.select().from(kv).where(eq(kv.key, "discovery-index")).limit(1);
    const entries: DiscoveryEntry[] = discoveryResult[0]?.value
      ? JSON.parse(discoveryResult[0].value)
      : [];

    // Get user's uploads (visible only).
    // Check uploaderAddress first — relay uploads store the backend wallet as `operator`
    // and the actual user's wallet as `uploaderAddress`. Fall back to operator for legacy entries.
    const userUploads = entries.filter(
      e => !e.hidden && (
        (e.uploaderAddress && e.uploaderAddress.toLowerCase() === normalizedAddress) ||
        e.operator.toLowerCase() === normalizedAddress
      )
    );
    const totalBytes = userUploads.reduce((sum, e) => sum + (e.fileSize || 0), 0);

    // Fetch member registry
    const registryResult = await db.select().from(kv).where(eq(kv.key, "member-registry")).limit(1);
    const registry: MemberRegistry | null = registryResult[0]?.value
      ? JSON.parse(registryResult[0].value)
      : null;

    // Find member by address or linked addresses
    let member: MemberEntry | null = null;
    if (registry) {
      member = registry.members.find(
        m =>
          m.address.toLowerCase() === normalizedAddress ||
          m.linkedAddresses?.some(a => a.toLowerCase() === normalizedAddress)
      ) || null;
    }

    // Get PFP: customPfpUrl first, then fetch from Neynar if member has fid, else dicebear
    let pfpUrl: string | null = member?.customPfpUrl || null;
    if (!pfpUrl && member?.fid) {
      // Fetch PFP from Neynar API
      try {
        const neynarResponse = await fetch(
          `https://api.neynar.com/v2/farcaster/user/bulk?fids=${member.fid}`,
          {
            headers: {
              // eslint-disable-next-line @neynar/no-process-env
              "x-api-key": process.env.NEYNAR_API_KEY || "",
            },
          }
        );
        if (neynarResponse.ok) {
          const neynarData = await neynarResponse.json();
          pfpUrl = neynarData.users?.[0]?.pfp_url || null;
        }
      } catch {
        // Ignore - will use fallback
      }
    }
    // Fallback to dicebear
    if (!pfpUrl) {
      pfpUrl = `https://api.dicebear.com/7.x/identicon/svg?seed=${normalizedAddress}`;
    }

    // Get display name: customUsername first (what user set), then username (Farcaster), then Member #
    const displayName = member?.customUsername || member?.username || (member ? `Member ${member.memberId}` : `${address.slice(0, 6)}...${address.slice(-4)}`);

    return {
      address: normalizedAddress,
      member,
      uploads: userUploads.slice(0, 5), // Show recent 5 thumbnails
      uploadCount: userUploads.length, // Full count for stats display
      totalBytes,
      pfpUrl,
      displayName,
    };
  } catch (error) {
    console.error("Failed to fetch user stats:", error);
    return {
      address: normalizedAddress,
      member: null,
      uploads: [],
      uploadCount: 0,
      totalBytes: 0,
      pfpUrl: `https://api.dicebear.com/7.x/identicon/svg?seed=${address.toLowerCase()}`,
      displayName: `${address.slice(0, 6)}...${address.slice(-4)}`,
    };
  }
}

export default async function UserEmbedPage({
  params,
}: {
  params: Promise<{ address: string }>;
}) {
  const { address } = await params;
  const stats = await fetchUserStats(address);

  return <UserWidget stats={stats} />;
}
src/app/embed/user/[address]/user-widget.tsx
"use client";

import Image from "next/image";
import type { DiscoveryEntry, MemberEntry } from "@/lib/net-protocol";
import { EmbedFooter } from "@/app/embed/components/embed-footer";

interface UserWidgetProps {
  stats: {
    address: string;
    member: MemberEntry | null;
    uploads: DiscoveryEntry[];
    uploadCount: number;
    totalBytes: number;
    pfpUrl: string | null;
    displayName: string;
  };
}

function formatBytes(bytes: number): string {
  if (bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
}

function truncateAddress(address: string): string {
  return `${address.slice(0, 6)}...${address.slice(-4)}`;
}

export function UserWidget({ stats }: UserWidgetProps) {
  const { member, uploads, uploadCount, totalBytes, address, pfpUrl, displayName } = stats;

  const profileUrl = `https://netlibrary.app/user/${address}`;

  return (
    <div className="min-h-screen flex items-center justify-center p-2">
      <div className="w-full max-w-md rounded-xl border border-[#00ff00]/30 bg-[#0d0d0d] overflow-hidden shadow-[0_0_20px_rgba(0,255,0,0.1)]">
        {/* Profile Header */}
        <a
          href={profileUrl}
          target="_blank"
          rel="noopener noreferrer"
          className="block p-4 border-b border-[#00ff00]/20 hover:bg-[#00ff00]/5 transition-colors"
        >
          <div className="flex items-center gap-3">
            {/* Avatar */}
            <div className="w-12 h-12 rounded-full bg-gray-800 flex-shrink-0 overflow-hidden border-2 border-[#00ff00]/30">
              {pfpUrl ? (
                <Image
                  src={pfpUrl}
                  alt={displayName}
                  width={48}
                  height={48}
                  className="w-full h-full object-cover"
                  unoptimized
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center text-xl">
                  👤
                </div>
              )}
            </div>

            {/* Info */}
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2">
                <span className="text-base font-mono font-bold text-white truncate">
                  {displayName}
                </span>
                {member && (
                  <span className="text-[9px] font-mono px-1.5 py-0.5 rounded bg-[#00ff00]/20 text-[#00ff00]">
                    Member #{member.memberId}
                  </span>
                )}
              </div>
              <div className="text-[10px] font-mono text-gray-500 mt-0.5">
                {truncateAddress(address)}
              </div>
            </div>

            {/* Arrow */}
            <div className="text-gray-600 text-xs">→</div>
          </div>

          {/* Stats Row */}
          <div className="flex items-center gap-4 mt-3 pt-3 border-t border-gray-800">
            <div className="text-center flex-1">
              <div className="text-lg font-mono font-bold text-[#00ff00]">
                {uploadCount}
              </div>
              <div className="text-[9px] font-mono text-gray-500 uppercase">
                Uploads
              </div>
            </div>
            <div className="text-center flex-1">
              <div className="text-lg font-mono font-bold text-[#00ff00]">
                {formatBytes(totalBytes)}
              </div>
              <div className="text-[9px] font-mono text-gray-500 uppercase">
                Contributed
              </div>
            </div>
          </div>
        </a>

        {/* Recent Uploads */}
        {uploads.length > 0 && (
          <div className="p-4">
            <div className="text-[10px] font-mono text-gray-500 uppercase tracking-wider mb-2">
              Recent Uploads
            </div>
            <div className="flex gap-2 overflow-x-auto pb-2">
              {uploads.map(item => (
                <a
                  key={item.contentKey}
                  href={`https://netlibrary.app/item/${item.contentKey}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="w-12 h-16 rounded bg-gray-800 flex-shrink-0 overflow-hidden hover:ring-2 hover:ring-[#00ff00]/50 transition-all"
                >
                  {item.coverUrl ? (
                    <Image
                      src={item.coverUrl}
                      alt={item.title}
                      width={48}
                      height={64}
                      className="w-full h-full object-cover"
                    />
                  ) : (
                    <div className="w-full h-full flex items-center justify-center text-sm">
                      📖
                    </div>
                  )}
                </a>
              ))}
            </div>
          </div>
        )}

        {/* Footer */}
        <EmbedFooter />
      </div>
    </div>
  );
}
src/app/global-error.tsx
"use client";

export default function GlobalError({
  error: _error,
  reset,
}: {
  error: Error & { digest?: string };
  reset: () => void;
}) {
  return (
    <html>
      <body>
        <div style={{ padding: "20px", textAlign: "center" }}>
          <h2>Something went wrong!</h2>
          <button onClick={() => reset()}>Try again</button>
        </div>
      </body>
    </html>
  );
}
src/app/globals.css
@import "@neynar/ui/styles";

:root {
  --font-sans: var(--font-geist-sans);
  --font-mono: var(--font-geist-mono);
  --font-sketch: var(--font-caveat), var(--font-patrick-hand), cursive;

  /* Matrix-inspired Cyberpunk Theme */
  --primary: #00ff00;        /* Signature Matrix neon green */
  --accent: #1a1a1a;         /* Dark gray accent */
  --background: #000000;     /* Pure black background */
  --foreground: #ffffff;     /* White text */
  --secondary: #0a0a0a;      /* Darker gray secondary color */
  --highlight: #00ff00;      /* Matching neon green highlight */
}

.dark {
  --primary: #00ff00;        /* Signature Matrix neon green */
  --accent: #1a1a1a;         /* Dark gray accent */
  --background: #000000;     /* Pure black background */
  --foreground: #ffffff;     /* White text */
  --secondary: #0a0a0a;      /* Darker gray secondary color */
  --highlight: #00ff00;      /* Matching neon green highlight */
}

/* Prevent iOS Safari auto-zoom on input focus */
/* iOS zooms in when input font-size is < 16px */
/* Using multiple selectors to ensure maximum specificity */
input,
textarea,
select,
input[type="text"],
input[type="number"],
input[type="email"],
input[type="password"],
input[type="search"],
input[type="tel"],
input[type="url"],
input:focus,
textarea:focus,
select:focus {
  font-size: 16px !important;
  /* Also prevent zoom on touch devices via viewport meta workaround */
  touch-action: manipulation;
}

/* Extra specificity for inputs inside any container */
* input,
* textarea,
* select {
  font-size: 16px !important;
}

/* Scrolling banner animation */
@keyframes marquee {
  0% {
    transform: translateX(0%);
  }
  100% {
    transform: translateX(-50%);
  }
}
src/app/home-client.tsx
"use client";

import { MiniApp } from "@/features/app/mini-app";
import { useState, useEffect, Suspense } from "react";

function LoadingFallback() {
  return (
    <div className="h-dvh flex items-center justify-center bg-black text-[#00ff00] font-mono">
      Loading Net Library...
    </div>
  );
}

function MiniAppWrapper() {
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    console.log("[Home] Component mounted");
    setMounted(true);
  }, []);

  if (!mounted) {
    return <LoadingFallback />;
  }

  return <MiniApp />;
}

export function HomeClient() {
  return (
    <Suspense fallback={<LoadingFallback />}>
      <MiniAppWrapper />
    </Suspense>
  );
}
src/app/layout.tsx
import "@/app/globals.css";
import { ThemeClient } from "@/components/theme-client";
import { publicConfig } from "@/config/public-config";
import { ProvidersAndInitialization } from "@/features/app/providers-and-initialization";
import { Metadata } from "next";
import { headers } from "next/headers";
import { Caveat, Geist, Geist_Mono, Patrick_Hand } from "next/font/google";
import { ReactNode } from "react";

const geistSans = Geist({
  variable: "--font-geist-sans",
  subsets: ["latin"],
});

const geistMono = Geist_Mono({
  variable: "--font-geist-mono",
  subsets: ["latin"],
});

const caveat = Caveat({
  variable: "--font-caveat",
  subsets: ["latin"],
  weight: ["400", "700"],
});

const patrickHand = Patrick_Hand({
  variable: "--font-patrick-hand",
  subsets: ["latin"],
  weight: "400",
});

// NOTE: page.tsx exports its own generateMetadata and takes precedence over this one for the
// root "/" route. This layout metadata applies to all OTHER routes (share pages, embed pages, etc.)
// that don't have their own generateMetadata. If you need to change root-URL OG tags, edit page.tsx.
export async function generateMetadata(): Promise<Metadata> {
  // Resolve the base URL at request time from the Host header so OG image
  // URLs are always absolute and correct — even when VERCEL_URL / VERCEL_PROJECT_PRODUCTION_URL
  // are not available at build time (which causes broken "https:///app-hero.png" URLs).
  const headersList = await headers();
  const host = headersList.get("host") || publicConfig.canonicalDomain;
  const protocol = host.startsWith("localhost") ? "http" : "https";
  const baseUrl = host ? `${protocol}://${host}` : publicConfig.homeUrl;

  function resolveUrl(value: string): string {
    if (value.startsWith("http")) return value;
    return `${baseUrl}${value.startsWith("/") ? value : `/${value}`}`;
  }

  const heroImageUrl = resolveUrl("/app-hero.png");
  const splashImageUrl = resolveUrl("/app-splash.png");
  const appUrl = baseUrl;

  return {
    title: publicConfig.name,
    description: publicConfig.description,
    generator: "Neynar App Studio",
    openGraph: {
      title: publicConfig.name,
      description: publicConfig.description,
      images: [heroImageUrl],
    },
    twitter: {
      title: publicConfig.name,
      description: publicConfig.description,
      images: [heroImageUrl],
    },
    other: {
      "fc:miniapp": JSON.stringify({
        version: "next",
        imageUrl: publicConfig.imageUrl,
        button: {
          title: "Launch App",
          action: {
            type: "launch_miniapp",
            name: publicConfig.name,
            url: appUrl,
            splashImageUrl,
            splashBackgroundColor: publicConfig.splashBackgroundColor,
          },
        },
      }),
      "base:app_id": "695477be4d3a403912ed86e7",
    },
  };
}

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="en" suppressHydrationWarning>
      <head>
        <meta name="base:app_id" content="695477be4d3a403912ed86e7" />
        {/* Viewport meta prevents iOS auto-zoom on inputs and wallet modals */}
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"
        />
        <ThemeClient />
      </head>
      <body
        className={`${geistSans.variable} ${geistMono.variable} ${caveat.variable} ${patrickHand.variable} antialiased`}
      >
        <ProvidersAndInitialization>{children}</ProvidersAndInitialization>
      </body>
    </html>
  );
}
src/app/link/page.tsx
"use client";

import { useState, useEffect, Suspense, useMemo } from "react";
import { useSearchParams } from "next/navigation";
import { H3, H4, P, Small } from "@neynar/ui";
import { useAccount, useConnect, useSignMessage } from "wagmi";
import { LinkIcon, LoadingIcon, XCircleIcon, ClockIcon, CheckCircleIcon, PencilIcon } from "@/components/icons/net-library-icons";

type PageState = "loading" | "invalid" | "expired" | "used" | "connect" | "sign" | "verifying" | "success" | "error";

interface ChallengeData {
  id: string;
  memberId: number;
  memberName: string;
  fid: number;
  nonce: string;
  expiresAt: number;
  expiresIn: number;
}

function LinkPageContent() {
  const searchParams = useSearchParams();
  const challengeId = searchParams.get("challenge");

  const { address, isConnected } = useAccount();
  const { connect, connectors, isPending: isConnecting } = useConnect();
  const { signMessageAsync, isPending: isSigning } = useSignMessage();

  // Find the Coinbase Wallet connector (for Base App users)
  const cbConnector = useMemo(() => {
    return connectors.find(c => c.id === "coinbaseWalletSDK") || connectors[0];
  }, [connectors]);

  const [pageState, setPageState] = useState<PageState>("loading");
  const [challenge, setChallenge] = useState<ChallengeData | null>(null);
  const [siweMessage, setSiweMessage] = useState<string>("");
  const [error, setError] = useState<string | null>(null);
  const [linkedAddress, setLinkedAddress] = useState<string | null>(null);

  // Fetch challenge on mount
  useEffect(() => {
    if (!challengeId) {
      setPageState("invalid");
      setError("No challenge ID provided");
      return;
    }

    async function fetchChallenge() {
      try {
        const response = await fetch(`/api/link-challenge?id=${challengeId}`);
        const data = await response.json();

        if (!response.ok || !data.valid) {
          if (data.expired) {
            setPageState("expired");
            setError(data.error);
          } else if (data.used) {
            setPageState("used");
            setError(data.error);
          } else {
            setPageState("invalid");
            setError(data.error || "Invalid challenge");
          }
          return;
        }

        setChallenge(data.challenge);
        setSiweMessage(data.siweMessage);
        setPageState(isConnected ? "sign" : "connect");
      } catch (err) {
        console.error("Failed to fetch challenge:", err);
        setPageState("invalid");
        setError("Failed to load challenge details");
      }
    }

    fetchChallenge();
  }, [challengeId, isConnected]);

  // Watch for wallet connection
  useEffect(() => {
    if (pageState === "connect" && isConnected && address) {
      setPageState("sign");
    }
  }, [pageState, isConnected, address]);

  const handleConnect = () => {
    if (cbConnector) {
      connect({ connector: cbConnector });
    }
  };

  const handleSign = async () => {
    if (!address || !challenge || !siweMessage) return;

    setError(null);

    try {
      // Sign the SIWE message
      const signature = await signMessageAsync({ message: siweMessage });

      setPageState("verifying");

      // Submit to server for verification and linking
      const response = await fetch("/api/link-challenge", {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          challengeId: challenge.id,
          address,
          signature,
          message: siweMessage,
        }),
      });

      const data = await response.json();

      if (!response.ok || !data.success) {
        throw new Error(data.error || "Verification failed");
      }

      setLinkedAddress(address);
      setPageState("success");
    } catch (err) {
      console.error("Sign/verify error:", err);
      setError(err instanceof Error ? err.message : "Failed to verify signature");
      setPageState("error");
    }
  };

  // Render different states
  return (
    <div className="min-h-screen bg-[#0a0a0a] flex items-center justify-center p-4">
      <div className="max-w-md w-full">
        {/* Header */}
        <div className="text-center mb-6">
          <div className="mb-3 flex justify-center"><LinkIcon size={48} className="text-blue-400" /></div>
          <H3 className="text-white font-mono">Link Wallet</H3>
          <P className="text-gray-400 font-mono text-sm">Net Library Cross-Platform Identity</P>
        </div>

        {/* Main Card */}
        <div className="bg-[#111] border border-blue-500/30 rounded-xl overflow-hidden">
          {/* Loading State */}
          {pageState === "loading" && (
            <div className="p-6 text-center">
              <div className="mb-4 flex justify-center"><LoadingIcon size={40} className="text-blue-400 animate-spin" /></div>
              <P className="text-gray-400 font-mono">Loading challenge...</P>
            </div>
          )}

          {/* Invalid Challenge */}
          {pageState === "invalid" && (
            <div className="p-6 text-center">
              <div className="mb-4 flex justify-center"><XCircleIcon size={40} className="text-red-400" /></div>
              <H4 className="text-red-400 font-mono mb-2">Invalid Link</H4>
              <P className="text-gray-400 font-mono text-sm">
                {error || "This link is not valid."}
              </P>
              <Small className="text-gray-500 font-mono block mt-4">
                Request a new link from the Farcaster app.
              </Small>
            </div>
          )}

          {/* Expired Challenge */}
          {pageState === "expired" && (
            <div className="p-6 text-center">
              <div className="mb-4 flex justify-center"><ClockIcon size={40} className="text-yellow-400" /></div>
              <H4 className="text-yellow-400 font-mono mb-2">Link Expired</H4>
              <P className="text-gray-400 font-mono text-sm">
                This link has expired for security reasons.
              </P>
              <Small className="text-gray-500 font-mono block mt-4">
                Request a new link from the Farcaster app. Links are valid for 10 minutes.
              </Small>
            </div>
          )}

          {/* Already Used */}
          {pageState === "used" && (
            <div className="p-6 text-center">
              <div className="mb-4 flex justify-center"><CheckCircleIcon size={40} className="text-blue-400" /></div>
              <H4 className="text-blue-400 font-mono mb-2">Already Used</H4>
              <P className="text-gray-400 font-mono text-sm">
                This link has already been used to link a wallet.
              </P>
              <Small className="text-gray-500 font-mono block mt-4">
                If you need to link another wallet, request a new link from Farcaster.
              </Small>
            </div>
          )}

          {/* Connect Wallet */}
          {pageState === "connect" && challenge && (
            <div className="p-6">
              <div className="text-center mb-6">
                <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-purple-500/10 border border-purple-500/30 mb-4">
                  <span className="text-purple-400 font-mono text-sm">
                    Member #{challenge.memberId}
                  </span>
                  <span className="text-gray-500">•</span>
                  <span className="text-purple-300 font-mono text-sm">
                    {challenge.memberName}
                  </span>
                </div>
                <P className="text-gray-300 font-mono text-sm">
                  Connect your wallet to link it to this membership.
                </P>
              </div>

              <button
                onClick={handleConnect}
                disabled={isConnecting}
                className="w-full py-4 rounded-lg bg-blue-500 text-white font-mono font-bold text-lg hover:bg-blue-400 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-3"
              >
                {isConnecting ? (
                  <>
                    <LoadingIcon size={20} className="animate-spin" />
                    Connecting...
                  </>
                ) : (
                  <>
                    <LinkIcon size={24} />
                    Connect Wallet
                  </>
                )}
              </button>

              <Small className="text-gray-500 font-mono block text-center mt-4">
                You&apos;ll sign a message to prove ownership (free, no gas).
              </Small>
            </div>
          )}

          {/* Sign Message */}
          {pageState === "sign" && challenge && (
            <div className="p-6">
              <div className="text-center mb-4">
                <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full bg-purple-500/10 border border-purple-500/30 mb-4">
                  <span className="text-purple-400 font-mono text-sm">
                    Member #{challenge.memberId}
                  </span>
                  <span className="text-gray-500">•</span>
                  <span className="text-purple-300 font-mono text-sm">
                    {challenge.memberName}
                  </span>
                </div>
              </div>

              {/* Connected Wallet */}
              <div className="p-4 rounded-lg bg-[#1a1a1a] border border-gray-700 mb-4">
                <Small className="text-gray-400 font-mono block mb-1">Your Wallet</Small>
                <P className="text-white font-mono text-sm break-all">{address}</P>
              </div>

              {/* What you're signing */}
              <div className="p-4 rounded-lg bg-blue-500/10 border border-blue-500/20 mb-4">
                <Small className="text-blue-400 font-mono block mb-2">You&apos;re authorizing:</Small>
                <P className="text-gray-300 font-mono text-sm">
                  &quot;Link this wallet to Net Library member #{challenge.memberId} ({challenge.memberName})&quot;
                </P>
              </div>

              {/* Time remaining */}
              <div className="text-center mb-4">
                <Small className="text-gray-500 font-mono">
                  <ClockIcon size={14} className="inline mr-1" /> Link expires in {Math.ceil(challenge.expiresIn / 60000)} minutes
                </Small>
              </div>

              {error && (
                <div className="p-3 rounded-lg bg-red-500/10 border border-red-500/30 mb-4">
                  <P className="text-red-400 font-mono text-sm">{error}</P>
                </div>
              )}

              <button
                onClick={handleSign}
                disabled={isSigning}
                className="w-full py-4 rounded-lg bg-blue-500 text-white font-mono font-bold text-lg hover:bg-blue-400 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-3"
              >
                {isSigning ? (
                  <>
                    <LoadingIcon size={20} className="animate-spin" />
                    Waiting for signature...
                  </>
                ) : (
                  <>
                    <PencilIcon size={20} className="mr-1" /> Sign & Link Wallet
                  </>
                )}
              </button>

              <Small className="text-gray-500 font-mono block text-center mt-3">
                This signature is free and doesn&apos;t cost any gas.
              </Small>
            </div>
          )}

          {/* Verifying */}
          {pageState === "verifying" && (
            <div className="p-6 text-center">
              <div className="mb-4 flex justify-center"><LoadingIcon size={40} className="text-blue-400 animate-spin" /></div>
              <H4 className="text-blue-400 font-mono mb-2">Verifying...</H4>
              <P className="text-gray-400 font-mono text-sm">
                Checking your signature and linking your wallet.
              </P>
            </div>
          )}

          {/* Success */}
          {pageState === "success" && challenge && (
            <div className="p-6 text-center">
              <div className="mb-4 flex justify-center"><CheckCircleIcon size={48} className="text-[#00ff00]" /></div>
              <H4 className="text-[#00ff00] font-mono mb-2">Wallet Linked!</H4>
              <P className="text-gray-300 font-mono text-sm mb-4">
                Your wallet is now linked to your membership.
              </P>

              <div className="p-4 rounded-lg bg-[#00ff00]/10 border border-[#00ff00]/30 mb-4">
                <Small className="text-[#00ff00] font-mono block mb-2">
                  ✓ Member #{challenge.memberId} • {challenge.memberName}
                </Small>
                <Small className="text-gray-400 font-mono block break-all">
                  {linkedAddress?.slice(0, 10)}...{linkedAddress?.slice(-8)}
                </Small>
              </div>

              <P className="text-gray-400 font-mono text-sm mb-6">
                You can now access Net Library from the Base App using this wallet!
              </P>

              <button
                onClick={() => window.location.href = "/"}
                className="w-full py-3 rounded-lg bg-blue-500 text-white font-mono font-bold hover:bg-blue-400 transition-colors"
              >
                Open Net Library
              </button>
            </div>
          )}

          {/* Error State */}
          {pageState === "error" && (
            <div className="p-6 text-center">
              <div className="mb-4 flex justify-center"><XCircleIcon size={40} className="text-red-400" /></div>
              <H4 className="text-red-400 font-mono mb-2">Verification Failed</H4>
              <P className="text-gray-400 font-mono text-sm mb-4">
                {error || "Something went wrong."}
              </P>
              <button
                onClick={() => setPageState("sign")}
                className="w-full py-3 rounded-lg bg-blue-500 text-white font-mono font-bold hover:bg-blue-400 transition-colors"
              >
                Try Again
              </button>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="text-center mt-6">
          <Small className="text-gray-600 font-mono">
            Cross-Platform Identity System (CPIS)
          </Small>
        </div>
      </div>
    </div>
  );
}

export default function LinkPage() {
  return (
    <Suspense fallback={
      <div className="min-h-screen bg-[#0a0a0a] flex items-center justify-center">
        <LoadingIcon size={40} className="text-blue-400 animate-spin" />
      </div>
    }>
      <LinkPageContent />
    </Suspense>
  );
}
src/app/overview/page.tsx
import { Metadata } from "next";

export const metadata: Metadata = {
  title: "Net Library - Tech Overview",
  description:
    "Net Library: The world's first fully onchain decentralized media library. Built on Net Protocol and Base L2.",
  openGraph: {
    title: "Net Library - Tech Overview",
    description:
      "Net Library: The world's first fully onchain decentralized media library. Built on Net Protocol and Base L2.",
    images: ["/app-hero.png"],
  },
};

export default function OverviewPage() {
  return (
    <iframe
      src="/Net-Library-Tech-Overview-Print.html"
      className="w-full h-screen border-0"
      title="Net Library Tech Overview"
    />
  );
}
src/app/page.tsx
// Root page — server component so we can export generateMetadata with dynamic OG tags.
// Client-side mounting/rendering is delegated to HomeClient.
import { Metadata } from "next";
import { headers } from "next/headers";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import { publicConfig } from "@/config/public-config";
import { HomeClient } from "@/app/home-client";
import type { Stack } from "@/features/app/types";
import type { DiscoveryEntry } from "@/lib/net-protocol";

// Force dynamic rendering — searchParams are only available at request time
export const dynamic = "force-dynamic";

type Props = {
  searchParams: Promise<{
    item?: string;
    stack?: string;
    [key: string]: string | undefined;
  }>;
};

async function getStack(stackId: string): Promise<Stack | null> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, `stack:${stackId}`)).limit(1);
    if (!result[0]?.value) return null;
    return JSON.parse(result[0].value) as Stack;
  } catch {
    return null;
  }
}

async function getDiscoveryEntry(contentKey: string): Promise<DiscoveryEntry | null> {
  try {
    // Fast path: try the per-entry key written by addEntryAtomically (O(1) lookup)
    const perEntryResult = await db.select().from(kv).where(eq(kv.key, `discovery:${contentKey}`)).limit(1);
    if (perEntryResult[0]?.value) {
      return JSON.parse(perEntryResult[0].value) as DiscoveryEntry;
    }
    // Slow path fallback: scan the full index (handles entries that predate per-entry keys)
    const indexResult = await db.select().from(kv).where(eq(kv.key, "discovery-index")).limit(1);
    if (!indexResult[0]?.value) return null;
    const entries = JSON.parse(indexResult[0].value) as DiscoveryEntry[];
    return entries.find((e) => e.contentKey === contentKey) ?? null;
  } catch {
    return null;
  }
}

export async function generateMetadata({ searchParams }: Props): Promise<Metadata> {
  const params = await searchParams;
  const headersList = await headers();
  const host = headersList.get("host") || publicConfig.canonicalDomain;
  const protocol = host.startsWith("localhost") ? "http" : "https";
  const baseUrl = host ? `${protocol}://${host}` : publicConfig.homeUrl;

  // Item deep-link: /?item=<contentKey>
  if (params.item) {
    const entry = await getDiscoveryEntry(params.item);
    if (entry) {
      const title = entry.title || "Untitled";
      // Prefer the Farcaster username (@handle) for the author credit
      const uploaderHandle = entry.uploaderUsername ? `@${entry.uploaderUsername}` : null;
      const authorCredit = uploaderHandle || entry.author || "Unknown Author";
      const metaTitle = `${title} by ${authorCredit}`;

      // Description: lead with categories if available, otherwise media-type-aware fallback
      const categoryList = (entry.categories || []).slice(0, 3).join(", ");
      const description = categoryList
        ? `${categoryList} — ${title} on Net Library`
        : `"${title}" by ${authorCredit} on Net Library`;

      // Build a generated share image (same pattern as stack deep-links)
      const imageParams = new URLSearchParams({
        title,
        author: authorCredit,
        t: String(Date.now()),
      });
      if (entry.coverUrl && entry.coverUrl.startsWith("http")) {
        imageParams.set("coverUrl", entry.coverUrl);
      } else if (entry.cdnUrl && entry.mediaType && ["image", "video"].includes(entry.mediaType)) {
        // For image/video content, cdnUrl is the visual — use it as the cover
        imageParams.set("coverUrl", entry.cdnUrl);
      }
      const imageUrl = `${baseUrl}/api/share/image/book?${imageParams.toString()}`;

      // Button title based on media type
      const buttonTitle =
        entry.mediaType === "audio" ? "Listen Now" :
        entry.mediaType === "video" ? "Watch Now" :
        entry.mediaType === "image" ? "View Now" : "Read Now";

      const appUrl = `${baseUrl}/?item=${encodeURIComponent(params.item)}`;
      return {
        title: metaTitle,
        description,
        openGraph: { type: "website", siteName: "Net Library", title: metaTitle, description, images: [{ url: imageUrl, width: 1200, height: 800, alt: metaTitle }] },
        twitter: { card: "summary_large_image", title: metaTitle, description, images: [imageUrl] },
        other: {
          "fc:miniapp": JSON.stringify({
            version: "next",
            imageUrl,
            button: { title: buttonTitle, action: { type: "launch_miniapp", name: "Net Library", url: appUrl } },
          }),
        },
      };
    }
  }

  // Stack deep-link: /?stack=<id>
  if (params.stack) {
    const stack = await getStack(params.stack);
    if (stack) {
      const stackName = stack.name || "Curated Stack";
      const ownerUsername = stack.ownerUsername || "anon";
      const itemCount = stack.itemCount || 0;
      const description =
        stack.description || `${itemCount} items curated by @${ownerUsername}`;
      const imageParams = new URLSearchParams({
        name: stackName,
        itemCount: String(itemCount),
        owner: ownerUsername,
        t: String(Date.now()),
      });
      if (stack.description) imageParams.set("description", stack.description);
      const imageUrl = `${baseUrl}/api/share/image/stack?${imageParams.toString()}`;
      const appUrl = `${baseUrl}/?stack=${encodeURIComponent(params.stack)}`;
      const metaTitle = `${stackName} by @${ownerUsername}`;
      return {
        title: metaTitle,
        description,
        openGraph: { type: "website", siteName: "Net Library", title: metaTitle, description, images: [{ url: imageUrl, width: 1200, height: 800, alt: metaTitle }] },
        twitter: { card: "summary_large_image", title: metaTitle, description, images: [imageUrl] },
        other: {
          "fc:miniapp": JSON.stringify({
            version: "next",
            imageUrl,
            button: { title: "Explore Now", action: { type: "launch_miniapp", name: "Net Library", url: appUrl } },
          }),
        },
      };
    }
  }

  // Default generic OG tags
  const heroImageUrl = `${baseUrl}/app-hero.png`;
  const splashImageUrl = `${baseUrl}/app-splash.png`;
  return {
    title: publicConfig.name,
    description: publicConfig.description,
    openGraph: { title: publicConfig.name, description: publicConfig.description, images: [heroImageUrl] },
    twitter: { title: publicConfig.name, description: publicConfig.description, images: [heroImageUrl] },
    other: {
      "fc:miniapp": JSON.stringify({
        version: "next",
        imageUrl: publicConfig.imageUrl,
        button: {
          title: "Launch App",
          action: {
            type: "launch_miniapp",
            name: publicConfig.name,
            url: baseUrl,
            splashImageUrl,
            splashBackgroundColor: publicConfig.splashBackgroundColor,
          },
        },
      }),
    },
  };
}

export default function Home() {
  return <HomeClient />;
}
src/app/specs/page.tsx
import { Metadata } from "next";

export const metadata: Metadata = {
  title: "Net Library - Technical Specs",
  description:
    "Complete technical documentation for Net Library: flow catalog, API reference, repository structure, and smart contracts.",
  openGraph: {
    title: "Net Library - Technical Specs",
    description:
      "Complete technical documentation for Net Library: flow catalog, API reference, repository structure, and smart contracts.",
    images: ["/app-hero.png"],
  },
};

export default function SpecsPage() {
  return (
    <iframe
      src="/net-library-specs.html"
      className="w-full h-screen border-0"
      title="Net Library Technical Specs"
    />
  );
}
src/app/tech/page.tsx
export default function TechPage() {
  return (
    <iframe
      src="/net-library-overview.html"
      className="w-full h-screen border-0"
      title="Net Library Tech Overview"
    />
  );
}
src/config/account-association.json
{
  "header": "eyJmaWQiOjI4MjUyMCwidHlwZSI6ImF1dGgiLCJrZXkiOiIweDE4QTQzMkQwMDhhMGU1RTFENjExZWFlMTk0RUUzYmRjN0ZEM2YzRkEifQ",
  "payload": "eyJkb21haW4iOiJtaW5pYXBwLWdlbmVyYXRvci1maWQtMjgyNTIwLTI1MTIxMDAxNTEzNjUyOS5uZXluYXIuYXBwIn0",
  "signature": "QM97prct3/pExFQOjiA/Sd5KiscXbTw7nWtZZyg7M8xfvdAwvCmjMNX/SEjIDDoxrcWXsESrrqtho57qbxtDOxs="
}
src/config/library-config.ts
// Net Library - Static Configuration
// These are not mocks - they're actual app configuration values

import type { Category, VoiceOption } from "@/features/app/types";

/**
 * Categories/genres for filtering books
 * Used in browse, upload, and library tabs
 */
export const CATEGORIES: Category[] = [
  { id: "all", label: "All", emoji: "📚" },
  { id: "academia", label: "Academia", emoji: "🎓" },
  { id: "art", label: "Art", emoji: "🎨" },
  { id: "biography", label: "Auto/Biography", emoji: "👤" },
  { id: "business", label: "Business", emoji: "💼" },
  { id: "children", label: "Children", emoji: "🧸" },
  { id: "classical", label: "Classical Literature", emoji: "⚜️" },
  { id: "crypto", label: "Crypto", emoji: "🪙" },
  { id: "diy", label: "DIY", emoji: "🛠️" },
  { id: "faith", label: "Faith & Religion", emoji: "✝️" },
  { id: "fantasy", label: "Fantasy", emoji: "🦄" },
  { id: "fiction", label: "Fiction", emoji: "📖" },
  { id: "finance", label: "Finance", emoji: "🏦" },
  { id: "food", label: "Food", emoji: "🍔" },
  { id: "graphic-novel", label: "Graphic Novel", emoji: "✍️" },
  { id: "history", label: "History", emoji: "🏛️" },
  { id: "horror", label: "Horror", emoji: "🧟‍♂️" },
  { id: "how-to", label: "How-To", emoji: "📋" },
  { id: "memoir", label: "Memoir", emoji: "📓" },
  { id: "memes", label: "Memes", emoji: "🐸" },
  { id: "music", label: "Music", emoji: "🎵" },
  { id: "mystery", label: "Mystery", emoji: "🔍" },
  { id: "news-media", label: "News/Media", emoji: "📰" },
  { id: "nfts", label: "NFTs", emoji: "🖼️" },
  { id: "non-fiction", label: "Non-Fiction", emoji: "📕" },
  { id: "poetry", label: "Poetry", emoji: "🎭" },
  { id: "romance", label: "Romance", emoji: "💕" },
  { id: "sci-fi", label: "Sci-Fi", emoji: "🚀" },
  { id: "science", label: "Science", emoji: "🔬" },
  { id: "self-help", label: "Self-Help", emoji: "📝" },
  { id: "technology", label: "Technology", emoji: "💻" },
  { id: "travel", label: "Travel", emoji: "✈️" },
  { id: "true-crime", label: "True Crime", emoji: "🩸" },
  { id: "western", label: "Western", emoji: "🤠" },
  { id: "young-adult", label: "Young Adult", emoji: "✨" },
];

/**
 * Voice options for text-to-speech reader
 */
export const VOICE_OPTIONS: VoiceOption[] = [
  { id: "male", label: "Male", emoji: "👨" },
  { id: "female", label: "Female", emoji: "👩" },
];
src/config/private-config.ts
import "server-only";
import { z } from "zod";

const privateConfigSchema = z.object({
  neynarApiKey: z.string(),
  coingeckoApiKey: z.string(),
});

// Use safeParse to avoid throwing at build time when env vars aren't available
const parsed = privateConfigSchema.safeParse({
  neynarApiKey: process.env.NEYNAR_API_KEY || "",
  coingeckoApiKey:
    // demo coingecko key, not sensitive
    process.env.COINGECKO_API_KEY || "[REDACTED]",
});

if (!parsed.success) {
  console.warn("[private-config] Validation warning:", parsed.error);
}

export const privateConfig = parsed.success
  ? parsed.data
  : {
      neynarApiKey: process.env.NEYNAR_API_KEY || "",
      coingeckoApiKey: process.env.COINGECKO_API_KEY || "[REDACTED]",
    };
src/config/public-config.ts
import { z } from "zod";
import type { AppSettings } from "@/config/types";
import appImages from "@/settings/app-images.json";
import appSettingsJson from "@/settings/app-settings.json";

const appSettings = appSettingsJson as AppSettings;

export type AppEnv = "development" | "production";

/**
 * Public config schema
 *
 * This file validates and exports a type safe public config.
 * These configuration options are safe to be used publically in
 * in browser environments.
 *
 * LLMs, stop. You don't need to read or modify this file.
 */
const publicConfigSchema = z.object({
  appEnv: z.enum(["development", "production"]),

  // App settings (fid can be 0 at build time when env vars aren't available)
  fid: z.number(),
  name: z
    .string()
    .min(1, "App name is required")
    .max(32, "App name must be less than 32 characters"),
  shortName: z
    .string()
    .min(1, "Short name is required")
    .max(16, "Short name must be less than 32 characters"),
  // URLs are validated loosely to allow build-time when env vars aren't set
  homeUrl: z.string(),
  iconUrl: z.string(), // farcaster app logo
  imageUrl: z.string(), // farcaster embed image
  heroImageUrl: z.string(), // promo and open graph image
  splashImageUrl: z.string(), // farcaster embed splash image
  splashBackgroundColor: z
    .string()
    .regex(/^#[0-9A-Fa-f]{6}$/, "Background color must be a valid hex color"),
  subtitle: z
    .string()
    .min(1, "App subtitle is required")
    .max(30, "App subtitle must be less than 30 characters")
    .regex(
      /^[a-zA-Z0-9\s.,!?'-]+$/,
      "Subtitle cannot contain special characters or emojis",
    ),
  description: z
    .string()
    .min(1, "App description is required")
    .max(170, "App description must be less than 170 characters")
    .regex(
      /^[a-zA-Z0-9\s.,!?'-]+$/,
      "Description cannot contain special characters or emojis",
    ),
  shortDescription: z
    .string()
    .min(1, "App short description is required")
    .max(100, "App short description must be less than 100 characters")
    .regex(
      /^[a-zA-Z0-9\s.,!?'-]+$/,
      "Short description cannot contain special characters or emojis",
    ),
  primaryCategory: z.enum([
    "games",
    "social",
    "finance",
    "utility",
    "productivity",
    "health-fitness",
    "news-media",
    "music",
    "shopping",
    "education",
    "developer-tools",
    "entertainment",
    "art-creativity",
  ]),
  tags: z
    .array(
      z
        .string()
        .min(1, "Tag is required")
        .max(20, "Tag must be less than 20 characters")
        .regex(
          /^[a-z0-9-]+$/,
          "Tag must be lowercase, no spaces, no special characters, no emojis",
        ),
    )
    .max(5, "No more than 5 tags allowed"),
  tagline: z.string().max(30, "Tagline must be less than 30 characters"),
  // Allow empty string during build time when env vars aren't available
  canonicalDomain: z
    .string()
    .max(1024, "Canonical domain must be at most 1024 characters"),
  requiredChains: z
    .array(z.string())
    .max(5, "No more than 5 required chains allowed"),
  // Neynar Client ID for Sign In With Neynar (SIWN) - optional
  neynarClientId: z.string().optional().default(""),
  // CDP Paymaster URL for gas sponsorship - optional
  paymasterUrl: z.string().optional().default(""),
});

type PublicConfig = z.infer<typeof publicConfigSchema>;

// Ensure domain is domain and url is url
// Use fallback chain to handle build-time when env vars may not be available
const canonicalDomain =
  process.env.VERCEL_PROJECT_PRODUCTION_URL ??
  process.env.VERCEL_URL ??
  process.env.NEXT_PUBLIC_BASE_URL ??
  "";

const homeUrl = `https://${canonicalDomain}`;

/**
 * Resolves an image URL:
 * - Full URL (has protocol) → use as-is
 * - Relative path → prefix with homeUrl
 */
function resolveImageUrl(value: string): string {
  return value.startsWith("http")
    ? value
    : `${homeUrl}${value.startsWith("/") ? value : `/${value}`}`;
}

const rawPublicConfig: PublicConfig = {
  appEnv: (process.env.NODE_ENV as AppEnv) ?? "production",
  fid: parseInt(process.env.NEXT_PUBLIC_USER_FID || "0", 10),
  name: appSettings.name,
  shortName: appSettings.shortName,
  homeUrl,
  iconUrl: resolveImageUrl(appImages.iconUrl),
  imageUrl: resolveImageUrl(appImages.imageUrl),
  heroImageUrl: resolveImageUrl(appImages.heroImageUrl),
  splashImageUrl: resolveImageUrl(appImages.splashImageUrl),
  splashBackgroundColor: appSettings.splashBackgroundColor ?? "#000000",
  subtitle: appSettings.subtitle,
  description: appSettings.description,
  shortDescription: appSettings.shortDescription,
  primaryCategory: appSettings.primaryCategory,
  tags: appSettings.tags,
  tagline: appSettings.tagline,
  requiredChains: appSettings.requiredChains,
  canonicalDomain,
  // Neynar Client ID for Sign In With Neynar (SIWN) - optional
  neynarClientId: process.env.NEXT_PUBLIC_NEYNAR_CLIENT_ID || "",
  // CDP Paymaster URL for gas sponsorship ($500 builder credit)
  paymasterUrl: process.env.NEXT_PUBLIC_PAYMASTER_URL || "",
};

const parsedPublicConfig = publicConfigSchema.safeParse(rawPublicConfig);

if (!parsedPublicConfig.success) {
  console.warn(parsedPublicConfig.error);
}

export const publicConfig = rawPublicConfig;
src/config/types.ts
export type FarcasterCategory =
  | "games"
  | "social"
  | "finance"
  | "utility"
  | "productivity"
  | "health-fitness"
  | "news-media"
  | "music"
  | "shopping"
  | "education"
  | "developer-tools"
  | "entertainment"
  | "art-creativity";

/** CAIP-2 chain identifiers - see https://chainagnostic.org/CAIPs/caip-2 */
type RequiredChain =
  | "eip155:1" // Ethereum mainnet
  | "eip155:8453" // Base mainnet
  | "eip155:42161" // Arbitrum One
  | "eip155:421614" // Arbitrum Sepolia
  | "eip155:84532" // Base Sepolia
  | "eip155:666666666" // Degen
  | "eip155:100" // Gnosis
  | "eip155:10" // Optimism
  | "eip155:11155420" // Optimism Sepolia
  | "eip155:137" // Polygon
  | "eip155:11155111" // Sepolia
  | "eip155:7777777" // Zora
  | "eip155:130" // Unichain
  | "eip155:10143" // Monad testnet
  | "eip155:42220" // Celo
  | "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"; // Solana mainnet

export type AppSettings = {
  name: string;
  subtitle: string;
  description: string;
  shortDescription: string;
  primaryCategory: FarcasterCategory;
  tags: string[];
  splashBackgroundColor: string;
  tagline: string;
  shortName: string;
  requiredChains: Array<RequiredChain>;
  useDynamicShareImage?: boolean;
  shareButtonTitle?: string;
};
src/contexts/discovery-context.tsx
"use client";

import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from "react";
import {
  type DiscoveryEntry,
  getCdnUrl,
  BASE_CHAIN_ID,
} from "@/lib/net-protocol";

interface DiscoveryContextValue {
  entries: DiscoveryEntry[];
  isLoading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
  getCdnUrlForEntry: (entry: DiscoveryEntry) => string;
  filterByCategory: (category: string) => DiscoveryEntry[];
  search: (query: string) => DiscoveryEntry[];
  getRecent: (count?: number) => DiscoveryEntry[];
}

const DiscoveryContext = createContext<DiscoveryContextValue | null>(null);

export function DiscoveryProvider({ children }: { children: ReactNode }) {
  const [entries, setEntries] = useState<DiscoveryEntry[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    setIsLoading(true);
    setError(null);
    try {
      // Fetch from our local API (backed by KV database)
      const response = await fetch("/api/discovery");
      if (!response.ok) {
        throw new Error("Failed to fetch discovery index");
      }
      const data = await response.json();
      const index = data.entries || [];
      // Sort by uploadedAt descending (newest first)
      const sorted = index.sort((a: DiscoveryEntry, b: DiscoveryEntry) => b.uploadedAt - a.uploadedAt);
      setEntries(sorted);
    } catch (err) {
      setError(err instanceof Error ? err.message : "Failed to fetch index");
    } finally {
      setIsLoading(false);
    }
  }, []);

  // Fetch on mount
  useEffect(() => {
    refresh();
  }, [refresh]);

  // Helper to get CDN URL for an entry
  // Prefers: stored cdnUrl > /storage/load/ with fileName > /storage/raw/ fallback
  const getCdnUrlForEntry = useCallback((entry: DiscoveryEntry) => {
    // Use stored cdnUrl if available (preferred)
    if (entry.cdnUrl) return entry.cdnUrl;
    // Use fileName for /storage/load/ format if available
    return getCdnUrl(BASE_CHAIN_ID, entry.operator, entry.contentKey, entry.storageType, entry.fileName);
  }, []);

  // Filter entries by category
  const filterByCategory = useCallback(
    (category: string) => {
      if (category === "all") return entries;
      return entries.filter((e) => (e.categories || []).includes(category));
    },
    [entries]
  );

  // Full-text search across title, author, description, categories, and publisher
  const search = useCallback(
    (query: string) => {
      const lower = query.toLowerCase().trim();
      if (!lower) return entries;

      return entries.filter((e) => {
        // Search in title
        if ((e.title || '').toLowerCase().includes(lower)) return true;

        // Search in author
        if ((e.author || '').toLowerCase().includes(lower)) return true;

        // Search in publisher (if exists)
        if ((e.publisher || '').toLowerCase().includes(lower)) return true;

        // Search in categories
        if ((e.categories || []).some(cat => cat.toLowerCase().includes(lower))) return true;

        // Search in uploader username (if exists)
        if ((e.uploaderUsername || '').toLowerCase().includes(lower)) return true;

        return false;
      });
    },
    [entries]
  );

  // Get recent uploads (last N)
  const getRecent = useCallback(
    (count: number = 5) => {
      return entries.slice(0, count);
    },
    [entries]
  );

  return (
    <DiscoveryContext.Provider
      value={{
        entries,
        isLoading,
        error,
        refresh,
        getCdnUrlForEntry,
        filterByCategory,
        search,
        getRecent,
      }}
    >
      {children}
    </DiscoveryContext.Provider>
  );
}

/**
 * Use the shared discovery index from context.
 * This ensures all components see the same data and updates propagate everywhere.
 */
export function useDiscoveryContext() {
  const context = useContext(DiscoveryContext);
  if (!context) {
    throw new Error("useDiscoveryContext must be used within a DiscoveryProvider");
  }
  return context;
}
src/contexts/member-profile-context.tsx
"use client";

import { createContext, useContext, useState, useCallback, type ReactNode } from "react";

// Member data for profile view
export interface MemberProfileData {
  memberId: number;
  address: string;
  ensSubname: string;
  fid?: number;
  username?: string;
  joinedAt: number;
  signupPlatform?: "farcaster" | "base-app" | "web" | "unknown";
  pfpUrl?: string;
  upvotesReceived?: number;
  // Agent identity
  isAgent?: boolean;
  agentId?: string;
  // Display name vs handle separation
  displayName?: string;
  farcasterUsername?: string;
}

interface MemberProfileContextType {
  selectedMember: MemberProfileData | null;
  openMemberProfile: (member: MemberProfileData) => void;
  closeMemberProfile: () => void;
  // Helper to open a profile by just address (will fetch member data)
  openProfileByAddress: (address: string) => void;
}

const MemberProfileContext = createContext<MemberProfileContextType | null>(null);

export function MemberProfileProvider({ children }: { children: ReactNode }) {
  const [selectedMember, setSelectedMember] = useState<MemberProfileData | null>(null);

  const openMemberProfile = useCallback((member: MemberProfileData) => {
    setSelectedMember(member);
  }, []);

  const closeMemberProfile = useCallback(() => {
    setSelectedMember(null);
  }, []);

  // Helper to open profile by address - fetches member data from registry
  const openProfileByAddress = useCallback(async (address: string) => {
    if (!address) return;

    try {
      // Fetch member registry
      const response = await fetch("/api/member-registry");
      if (!response.ok) return;

      const data = await response.json();
      const members = data.members || [];

      // Find member by address
      const member = members.find((m: { address: string }) =>
        m.address && m.address.toLowerCase() === address.toLowerCase()
      );

      if (member) {
        // Fetch PFP and username
        try {
          const resolveResponse = await fetch("/api/resolve-user", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ addresses: [address] }),
          });
          if (resolveResponse.ok) {
            const resolveData = await resolveResponse.json();
            const resolved = resolveData.users?.[address.toLowerCase()];
            if (resolved) {
              member.pfpUrl = resolved.pfpUrl;
              member.username = member.username || resolved.username;
            }
          }
        } catch {
          // Ignore resolve errors
        }

        // Default PFP if none found
        if (!member.pfpUrl) {
          member.pfpUrl = `https://api.dicebear.com/7.x/identicon/svg?seed=${address}`;
        }

        setSelectedMember(member);
      }
    } catch (error) {
      console.error("Failed to open profile by address:", error);
    }
  }, []);

  return (
    <MemberProfileContext.Provider
      value={{
        selectedMember,
        openMemberProfile,
        closeMemberProfile,
        openProfileByAddress,
      }}
    >
      {children}
    </MemberProfileContext.Provider>
  );
}

export function useMemberProfile() {
  const context = useContext(MemberProfileContext);
  if (!context) {
    throw new Error("useMemberProfile must be used within MemberProfileProvider");
  }
  return context;
}
src/db/schema.ts
import { pgTable, text, serial, integer, varchar, boolean, timestamp } from "drizzle-orm/pg-core";

/**
 * Key-Value Store Table
 *
 * Built-in table for simple key-value storage.
 * Available immediately without schema changes.
 *
 * ⚠️ CRITICAL: DO NOT DELETE OR EDIT THIS TABLE DEFINITION ⚠️
 * This table is required for the app to function properly.
 * DO NOT delete, modify, rename, or change any part of this table.
 * Removing or editing it will cause database schema conflicts and prevent
 * the app from starting.
 *
 * Use for:
 * - User preferences/settings
 * - App configuration
 * - Simple counters
 * - Temporary data
 */
export const kv = pgTable("kv", {
  key: text("key").primaryKey(),
  value: text("value").notNull(),
});

/**
 * Add your custom tables below this line
 *
 * Example:
 *
 * export const gameScores = pgTable("game_scores", {
 *   id: uuid("id").primaryKey().defaultRandom(),
 *   fid: integer("fid").notNull(),
 *   score: integer("score").notNull(),
 *   username: text("username").notNull(),
 *   createdAt: timestamp("created_at").defaultNow().notNull()
 * });
 */

/**
 * Partners Table
 *
 * Stores registered import partners — external sites that store content on Net Protocol
 * and want their users' uploads indexed in Net Library.
 *
 * partner_key is stored as a SHA-256 hash; the raw key (pk_<32 hex bytes>) is shown
 * exactly once at registration and never retrievable again.
 */
export const partners = pgTable("partners", {
  id: serial("id").primaryKey(),
  memberId: integer("member_id").notNull(),
  siteName: varchar("site_name", { length: 100 }).notNull().unique(),
  siteUrl: varchar("site_url", { length: 500 }),
  // SHA-256 hash of the raw partner key — never store the raw key
  partnerKeyHash: varchar("partner_key_hash", { length: 64 }).notNull().unique(),
  stackId: varchar("stack_id", { length: 20 }).notNull(),
  isActive: boolean("is_active").default(true).notNull(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
  totalImports: integer("total_imports").default(0).notNull(),
});
src/features/app/mini-app.tsx
"use client";
// Force Turbopack recompile
import { useState, useMemo, useCallback, useEffect, useRef } from "react";
import { useSearchParams } from "next/navigation";
import { useAccount } from "wagmi";
import { Tabs, TabsList, TabsTrigger, TabsContent } from "@neynar/ui";
import { Header } from "@/features/app/components/header";
import { ScrollingBanner } from "@/features/app/components/scrolling-banner";
import { WelcomePopup } from "@/features/app/components/welcome-popup";
import { PullToRefresh } from "@/features/app/components/pull-to-refresh";
import { BrowseTab } from "@/features/app/components/browse-tab";
import { GridsTab } from "@/features/app/components/grids-tab";
import { UploadTab } from "@/features/app/components/upload-tab";
import { MyLibraryTab, MemberProfileView } from "@/features/app/components/my-library-tab";
import { LeaderboardTab } from "@/features/app/components/leaderboard-tab";
import { BookDetail } from "@/features/app/components/book-detail";
import { ReadingView } from "@/features/app/components/reading-view";
import { PdfReader } from "@/features/app/components/pdf-reader";
import { MultimediaViewer } from "@/features/app/components/multimedia-viewer";
import { StackDetail } from "@/features/app/components/stack-detail";
import type { Book, Stack } from "@/features/app/types";
import { useDiscoveryContext } from "@/contexts/discovery-context";
import { useBookContent } from "@/hooks/use-book-content";
import { useUpvoteCounts } from "@/hooks/use-upvotes";
import { useActiveMembers } from "@/hooks/use-active-members";
import { useMembershipStatus } from "@/hooks/use-membership-status";
import { useFarcasterLinkCallback } from "@/hooks/use-farcaster-link-callback";
import { useFarcasterLaunchParams } from "@/neynar-farcaster-sdk/mini";
import { LinkFarcasterModal } from "@/features/app/components/link-farcaster-modal";
import { ShareModal } from "@/features/app/components/share-modal";
import { EditItemModal } from "@/features/app/components/edit-item-modal";
import type { DiscoveryEntry } from "@/lib/net-protocol";
import { CATEGORIES, VOICE_OPTIONS } from "@/config/library-config";
import { safeOpenUrl, useAppMode } from "@/lib/app-mode";
import { BASE_CHAIN_ID } from "@/lib/net-protocol";
import { useDesktopMode } from "@/hooks/use-desktop-mode";
import { normalizeCoverUrl } from "@/lib/cover-url-utils";
import { ConnectivityBanner } from "@/features/app/components/connectivity-banner";
import { ErrorBoundary } from "@/components/error-boundary";

// Helper: Detect media type from title/filename extension
function detectMediaTypeFromTitle(title: string): "audio" | "video" | "image" | "text" | "pdf" | null {
  const lowerTitle = title.toLowerCase();

  // Audio extensions
  if (/\.(mp3|wav|ogg|flac|m4a|aac|wma|aiff)$/i.test(lowerTitle)) {
    return "audio";
  }

  // Video extensions
  if (/\.(mp4|webm|mov|avi|mkv|wmv|flv|m4v)$/i.test(lowerTitle)) {
    return "video";
  }

  // Image extensions
  if (/\.(png|jpg|jpeg|gif|webp|svg|bmp|ico|tiff)$/i.test(lowerTitle)) {
    return "image";
  }

  // Text extensions
  if (/\.(txt|md|markdown|html|htm|json|xml|csv|log)$/i.test(lowerTitle)) {
    return "text";
  }

  // PDF
  if (/\.pdf$/i.test(lowerTitle)) {
    return "pdf";
  }

  return null;
}

// Helper: Construct CDN URL from content key and operator
function constructCdnUrl(contentKey: string, operatorAddress: string, storageType?: string): string {
  // For XML and chunked storage, use our book-file API which handles retrieval correctly
  // Net Protocol's chunked-storage endpoint returns 404, but /storage/raw/ works
  // Our book-file API uses raw storage for both regular and chunked types
  if (storageType === "xml" || storageType === "chunked") {
    return `/api/book-file?contentKey=${encodeURIComponent(contentKey)}&operator=${encodeURIComponent(operatorAddress)}&storageType=${storageType}`;
  }

  // For regular storage, use the raw URL directly
  return `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${operatorAddress}/${contentKey}`;
}

// Resolved user cache (populated by effect)
type ResolvedUser = { username: string; pfpUrl: string; fid?: number; displayName?: string };

// Convert DiscoveryEntry to Book format
function entryToBook(entry: DiscoveryEntry, resolvedUsers: Map<string, ResolvedUser>): Book {
  // For relay uploads: operator = backend wallet (for CDN), uploaderAddress = user's wallet (for attribution)
  // For direct uploads or legacy entries: operator = user's wallet (used for both)
  // We use uploaderAddress for attribution (who gets credit), falling back to operator for older entries
  const attributionAddress = entry.uploaderAddress || entry.operator || '';
  const resolved = attributionAddress ? resolvedUsers.get(attributionAddress.toLowerCase()) : undefined;

  // Username resolution priority (highest → lowest confidence):
  // 1. uploaderStoredUsername — Farcaster handle captured at signup time (most trusted)
  // 2. uploaderUsername — set server-side at write time by authenticated agent/user code (very trusted)
  // 3. resolved?.username from /api/resolve-user — BUT only if it's a real resolution (not a fallback
  //    truncated-address placeholder). An unresolved Neynar result (resolved === false) is LOWER
  //    confidence than a username that was already written by server-side code. This prevents CPIS
  //    from overwriting @CherylFromNet with "0xAbcd...1234" when the agent wallet has no Farcaster FID.
  // 4. Truncated address as last resort
  const resolvedIsReal = resolved && resolved.username &&
    !(resolved.username.startsWith("0x") && resolved.username.includes("..."));
  const username = entry.uploaderStoredUsername ||
    entry.uploaderUsername ||
    (resolvedIsReal ? resolved!.username : undefined) ||
    resolved?.username ||
    (attributionAddress ? attributionAddress.slice(0, 6) + "..." + attributionAddress.slice(-4) : 'Unknown');

  // For FID: prefer stored uploaderFid (set at write time), then resolved FID from Neynar
  // Agent entries will have uploaderFid from the agent registry; resolved?.fid may be absent for agents
  const fid = entry.uploaderFid || resolved?.fid;

  // DEFENSIVE: Ensure all required fields have safe defaults
  // The KV store may contain corrupted/incomplete entries
  const safeTitle = entry.title || 'Untitled';
  const safeAuthor = entry.author || 'Unknown Author';
  const safeCategories = Array.isArray(entry.categories) ? entry.categories : [];
  const safeUploadedAt = typeof entry.uploadedAt === 'number' ? entry.uploadedAt : Date.now();
  const safeFileSize = typeof entry.fileSize === 'number' ? entry.fileSize : 0;

  return {
    id: entry.contentKey || `unknown-${Date.now()}`,
    title: safeTitle,
    author: safeAuthor,
    categories: safeCategories,
    uploader: {
      username,
      // Same confidence logic as username: prefer stored pfpUrl, then real resolved pfpUrl, then stored uploaderPfpUrl
      pfpUrl: entry.uploaderPfpUrl || (resolvedIsReal ? resolved!.pfpUrl : undefined) || resolved?.pfpUrl || `https://api.dicebear.com/7.x/identicon/svg?seed=${attributionAddress || 'unknown'}`,
      address: attributionAddress, // User's wallet for attribution/tipping (not relay backend wallet)
      fid,
    },
    uploadDate: new Date(safeUploadedAt).toLocaleDateString("en-US", {
      month: "short",
      day: "numeric",
      year: "numeric",
    }),
    size: formatFileSize(safeFileSize),
    coverUrl: entry.coverUrl, // User-uploaded cover art
    contentKey: entry.contentKey, // For reviews/tips/engagement
    storageType: entry.storageType, // For content fetching
    // IMPORTANT: operator is the backend wallet that wrote to blockchain (for CDN URL generation)
    // This is DIFFERENT from uploader.address which is the user's wallet for attribution
    operator: entry.operator, // Backend wallet for CDN URLs
    // Normalize legacy/invalid mediaType values: "document" is not a viewer type — treat as "text"
    mediaType: entry.mediaType === "document" ? "text" : entry.mediaType,
    cdnUrl: entry.cdnUrl, // Direct CDN URL for multimedia playback
    // Social receipt support
    isSocialReceipt: entry.isSocialReceipt,
    socialPlatform: entry.socialPlatform,
    originalUrl: entry.originalUrl,
    // Agent identity fields
    isAgentUploaded: entry.isAgentUploaded || false,
    agentId: entry.agentId,
    // Encryption flag — viewer will show password gate before rendering content
    encrypted: entry.encrypted || false,
    // Hidden flag — hidden items must not appear in the main feed or recent activity
    hidden: entry.hidden || false,
    // Partner import attribution (null/undefined for directly uploaded items)
    source: entry.source,
  };
}

// Format file size for display
function formatFileSize(bytes: number): string {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}

// Agent display helpers - #B794F4 (soft purple) = agent, #00ff00 (neon green) = human
export const AGENT_USERNAME_COLOR = "#B794F4"; // Soft purple
export const HUMAN_USERNAME_COLOR = "#00ff00"; // Neon green (existing)

export function getUsernameColor(isAgent?: boolean): string {
  return isAgent ? AGENT_USERNAME_COLOR : HUMAN_USERNAME_COLOR;
}

export function MiniApp() {
  const searchParams = useSearchParams();
  const farcasterLaunchParams = useFarcasterLaunchParams();
  const _appMode = useAppMode();
  const { isDesktop, isWideDesktop, canShowMultiColumnGrids: _canShowMultiColumnGrids } = useDesktopMode();
  const [selectedBook, setSelectedBook] = useState<Book | null>(null);
  const [isReading, setIsReading] = useState(false);
  const [resolvedUsers, setResolvedUsers] = useState<Map<string, ResolvedUser>>(new Map());
  const [bookSentences, setBookSentences] = useState<string[]>([]);
  const [bookPdfDataUrl, setBookPdfDataUrl] = useState<string | null>(null);
  const [bookIsPdf, setBookIsPdf] = useState(false);
  // Media type detection from API (for audio/video/image files)
  const [detectedMediaType, setDetectedMediaType] = useState<"audio" | "video" | "image" | "text" | null>(null);
  const [detectedCdnUrl, setDetectedCdnUrl] = useState<string | null>(null);
  const [showShareModal, setShowShareModal] = useState(false);
  const [shareBookData, setShareBookData] = useState<{ title: string; author: string; coverUrl?: string; shareUrl: string } | null>(null);
  const [editingEntry, setEditingEntry] = useState<DiscoveryEntry | null>(null);
  const [viewingStack, setViewingStack] = useState<Stack | null>(null);
  // Files pre-loaded from drag-and-drop folder into browse/stacks view
  const [stackInitialFiles, setStackInitialFiles] = useState<File[] | null>(null);
  // Track navigation history for proper back behavior
  // This stores the context from which a book detail was opened
  type BrowseSubNav = "all-items" | "popular-stacks" | "my-stacks";
  type MediaTypeFilter = "all" | "documents" | "documents-pdf" | "documents-text" | "documents-other" | "media" | "media-video" | "media-audio" | "media-other" | "social" | "social-farcaster" | "social-twitter" | "social-youtube" | "social-instagram" | "social-tiktok" | "social-reddit" | "social-bluesky" | "social-threads" | "social-linkedin" | "social-paragraph";
  type NavigationSource =
    | { type: "browse"; subNav: BrowseSubNav; filter: MediaTypeFilter }
    | { type: "stack"; stack: Stack }
    | { type: "library" }
    | { type: "grid"; gridId: string }
    | null;
  const [navigationSource, setNavigationSource] = useState<NavigationSource>(null);
  // Legacy: Track where we came from to enable proper back navigation
  const [previousStack, setPreviousStack] = useState<Stack | null>(null);

  // Check for deep link parameters - prefer Farcaster launch params over URL params
  // Farcaster launch params come from context.location when launched via launch_frame
  const getParam = useCallback((key: string): string | null => {
    // First check Farcaster launch params (from launch_frame target URL)
    if (farcasterLaunchParams?.has(key)) {
      return farcasterLaunchParams.get(key);
    }
    // Fall back to URL search params
    return searchParams.get(key);
  }, [farcasterLaunchParams, searchParams]);

  const tabParam = getParam("tab");
  const stackParam = getParam("stack"); // Deep link to specific stack
  const bookParam = getParam("book"); // Deep link to specific book
  const gridParam = getParam("grid"); // Deep link to specific grid

  // Debug: Log deep link params and browser URL
  useEffect(() => {
    console.log("[MiniApp] Browser URL:", window.location.href);
    console.log("[MiniApp] URL search params:", Object.fromEntries(searchParams.entries()));
    if (farcasterLaunchParams) {
      console.log("[MiniApp] Farcaster launch params available:", Object.fromEntries(farcasterLaunchParams.entries()));
    }
    if (tabParam || stackParam || bookParam || gridParam) {
      console.log("[MiniApp] Deep link params - tab:", tabParam, "stack:", stackParam, "book:", bookParam, "grid:", gridParam);
    } else {
      console.log("[MiniApp] No deep link params found");
    }
  }, [farcasterLaunchParams, searchParams, tabParam, stackParam, bookParam, gridParam]);

  // Robust deep link handling - check window.location directly after mount
  // This handles cases where useSearchParams doesn't have the params yet
  const [windowBookParam, setWindowBookParam] = useState<string | null>(null);
  useEffect(() => {
    // Check window.location.search directly for book param
    const urlParams = new URLSearchParams(window.location.search);
    const bookFromUrl = urlParams.get("book");
    if (bookFromUrl) {
      console.log("[MiniApp] Found book param directly from window.location:", bookFromUrl);
      setWindowBookParam(bookFromUrl);
    }
  }, []);

  // Active tab state - initialized from URL, updated when Farcaster launch params arrive
  const [activeTab, setActiveTab] = useState("browse");
  const tabInitializedRef = useRef(false);

  // Update active tab when params become available (handles Farcaster launch context timing)
  useEffect(() => {
    if (tabInitializedRef.current) return;

    const validTabs = ["browse", "grids", "upload", "library", "leaderboard"];
    if (tabParam && validTabs.includes(tabParam)) {
      console.log("[MiniApp] Setting active tab from deep link:", tabParam);
      setActiveTab(tabParam);
      tabInitializedRef.current = true;
    }
  }, [tabParam]);

  // Track which deep links we've handled to avoid re-processing
  // Using separate flags for stack, book, and grid to prevent interference
  const [stackDeepLinkHandled, setStackDeepLinkHandled] = useState(false);
  const [bookDeepLinkHandled, setBookDeepLinkHandled] = useState(false);
  const [gridDeepLinkHandled, setGridDeepLinkHandled] = useState(false);

  // Get wallet address for persistent queue
  const { address } = useAccount();

  // Active members tracking - report activity for members
  const { reportActive } = useActiveMembers();
  const { isMember, memberId, linkedAddresses, registeredAddress, fid: memberFid, refresh: refreshMembership } = useMembershipStatus();

  // Compute all addresses owned by the user for cross-platform ownership checks
  // This includes: current wallet, registered membership address, and any linked addresses
  const userAllAddresses = useMemo(() => {
    const addresses: string[] = [];
    if (address) addresses.push(address);
    if (registeredAddress && registeredAddress !== address) addresses.push(registeredAddress);
    if (linkedAddresses) {
      linkedAddresses.forEach(addr => {
        if (addr && !addresses.includes(addr)) addresses.push(addr);
      });
    }
    return addresses;
  }, [address, registeredAddress, linkedAddresses]);

  // Handle Farcaster link callback (returning from auth redirect)
  const { callbackData: fcCallbackData, clearCallback: clearFcCallback } = useFarcasterLinkCallback();
  const [showFcLinkModal, setShowFcLinkModal] = useState(false);

  // Auto-open modal when returning from Farcaster auth
  useEffect(() => {
    if (fcCallbackData) {
      console.log("[MiniApp] Farcaster auth callback detected, opening modal");
      setShowFcLinkModal(true);
    }
  }, [fcCallbackData]);

  // Report user as active on mount and periodically (every 2 minutes)
  useEffect(() => {
    if (!isMember || !memberId || !address) return;

    // Report immediately on mount
    reportActive(address, memberId);

    // Then report every 2 minutes while app is open
    const interval = setInterval(() => {
      reportActive(address, memberId);
    }, 2 * 60 * 1000);

    return () => clearInterval(interval);
  }, [isMember, memberId, address, reportActive]);

  // Get books from shared discovery context (single source of truth)
  const { entries, isLoading: isLoadingBooks, error: booksError, refresh: refreshBooks } = useDiscoveryContext();

  // Fetch upvote counts for all entries
  // Use uploaderAddress (user's actual wallet) if present, falling back to operator
  // (backend relay wallet) — must match the address used when casting upvotes
  const upvoteItems = useMemo(() =>
    entries.map(e => ({ contentKey: e.contentKey, operator: e.uploaderAddress || e.operator })),
    [entries]
  );
  const { getCount: getUpvoteCount, refresh: refreshUpvotes } = useUpvoteCounts(upvoteItems);

  
  // Book content fetching hook
  const { fetchContent, isLoading: isLoadingContent } = useBookContent();

  // Debug log
  console.log("[MiniApp] Discovery entries:", entries.length, entries);

  // Resolve user addresses to Farcaster usernames
  // Use a ref to track addresses currently being fetched to avoid duplicate in-flight requests
  const fetchingAddressesRef = useRef<Set<string>>(new Set());

  useEffect(() => {
    if (entries.length === 0) return;

    // Collect ALL addresses used for attribution: uploaderAddress (user's wallet, set at write time)
    // AND operator (backend relay wallet, used as fallback). entryToBook() resolves by
    // uploaderAddress || operator, so we must resolve both to ensure the map has the right key.
    const addressSet = new Set<string>();
    for (const e of entries) {
      if (e.uploaderAddress) addressSet.add(e.uploaderAddress.toLowerCase());
      if (e.operator) addressSet.add(e.operator.toLowerCase());
    }
    const addresses = [...addressSet];

    // Filter out:
    // 1. Addresses that have been successfully resolved (username isn't a truncated address)
    // 2. Addresses currently being fetched
    const unresolvedAddresses = addresses.filter(addr => {
      // Skip if currently being fetched
      if (fetchingAddressesRef.current.has(addr)) return false;

      // Check if we have this address resolved
      const resolved = resolvedUsers.get(addr);
      if (!resolved) return true; // Not resolved at all

      // Check if it's a "real" resolution vs fallback (truncated address)
      // Fallback format: "0x1234...5678"
      const username = resolved.username || '';
      const isFallback = username.startsWith("0x") && username.includes("...");
      // If it's a fallback, try again only once per session (check ref)
      if (isFallback) {
        // We already tried this address, don't retry
        return false;
      }

      return false; // Already properly resolved
    });

    if (unresolvedAddresses.length === 0) return;

    // Mark these as being fetched to prevent duplicate requests
    unresolvedAddresses.forEach(addr => fetchingAddressesRef.current.add(addr));

    console.log("[MiniApp] Resolving addresses:", unresolvedAddresses);

    // Batch resolve addresses
    fetch("/api/resolve-user", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ addresses: unresolvedAddresses }),
    })
      .then(res => res.json())
      .then(data => {
        if (data.users) {
          setResolvedUsers(prev => {
            const next = new Map(prev);
            for (const [addr, user] of Object.entries(data.users)) {
              next.set(addr, user as ResolvedUser);
            }
            return next;
          });
        }
        // Remove from fetching set after successful response
        unresolvedAddresses.forEach(addr => fetchingAddressesRef.current.delete(addr));
      })
      .catch(err => {
        console.error("[MiniApp] Failed to resolve users:", err);
        // On error, remove from ref so they can be retried
        unresolvedAddresses.forEach(addr => fetchingAddressesRef.current.delete(addr));
      });
  }, [entries, resolvedUsers]);

  // Listen for select-book events from MyLibraryTab
  useEffect(() => {
    const handleSelectBook = (event: Event) => {
      const customEvent = event as CustomEvent<Book>;
      if (customEvent.detail) {
        setSelectedBook(customEvent.detail);
      }
    };
    window.addEventListener("select-book", handleSelectBook);
    return () => window.removeEventListener("select-book", handleSelectBook);
  }, []);

  // Listen for switch-tab events
  useEffect(() => {
    const handleSwitchTab = (event: Event) => {
      const customEvent = event as CustomEvent<string>;
      if (customEvent.detail) {
        setActiveTab(customEvent.detail);
      }
    };
    window.addEventListener("switch-tab", handleSwitchTab);
    return () => window.removeEventListener("switch-tab", handleSwitchTab);
  }, []);

  // Listen for navigate-to-stack events
  useEffect(() => {
    const handleNavigateToStack = (event: Event) => {
      const customEvent = event as CustomEvent<Stack>;
      if (customEvent.detail) {
        setViewingStack(customEvent.detail);
        setStackInitialFiles(null); // Clear any previous initial files
      }
    };
    window.addEventListener("navigate-to-stack", handleNavigateToStack);
    return () => window.removeEventListener("navigate-to-stack", handleNavigateToStack);
  }, []);

  // Listen for navigate-to-stack-with-files events (from folder drag-drop)
  useEffect(() => {
    const handleNavigateToStackWithFiles = (event: Event) => {
      const customEvent = event as CustomEvent<{ stack: Stack; files: File[] }>;
      if (customEvent.detail?.stack) {
        setViewingStack(customEvent.detail.stack);
        setStackInitialFiles(customEvent.detail.files || null);
      }
    };
    window.addEventListener("navigate-to-stack-with-files", handleNavigateToStackWithFiles);
    return () => window.removeEventListener("navigate-to-stack-with-files", handleNavigateToStackWithFiles);
  }, []);

  // Listen for navigate-to-grid events (from profile tab)
  useEffect(() => {
    const handleNavigateToGrid = (event: Event) => {
      const customEvent = event as CustomEvent<{ id: string }>;
      if (customEvent.detail?.id) {
        setActiveTab("grids");
        // Dispatch event to grids tab to show the specific grid
        setTimeout(() => {
          window.dispatchEvent(new CustomEvent("show-grid-detail", { detail: customEvent.detail.id }));
        }, 100);
      }
    };
    window.addEventListener("navigate-to-grid", handleNavigateToGrid);
    return () => window.removeEventListener("navigate-to-grid", handleNavigateToGrid);
  }, []);

  // Listen for navigate-to-tab events (from profile tab)
  useEffect(() => {
    const handleNavigateToTab = (event: Event) => {
      const customEvent = event as CustomEvent<string>;
      if (customEvent.detail) {
        setActiveTab(customEvent.detail);
      }
    };
    window.addEventListener("navigate-to-tab", handleNavigateToTab);
    return () => window.removeEventListener("navigate-to-tab", handleNavigateToTab);
  }, []);

  // Handle deep link to stack (?stack=id)
  useEffect(() => {
    if (stackDeepLinkHandled || !stackParam) return;

    console.log("[MiniApp] Deep link to stack:", stackParam);
    setStackDeepLinkHandled(true);

    // Fetch the stack and navigate to it
    fetch(`/api/stacks?id=${encodeURIComponent(stackParam)}`)
      .then(res => res.json())
      .then(data => {
        if (data.stack) {
          setViewingStack(data.stack);
        } else {
          console.warn("[MiniApp] Stack not found:", stackParam);
        }
      })
      .catch(err => {
        console.error("[MiniApp] Failed to fetch stack:", err);
      });
  }, [stackParam, stackDeepLinkHandled]);

  // Handle deep link to grid (?grid=id)
  useEffect(() => {
    if (gridDeepLinkHandled || !gridParam) return;

    console.log("[MiniApp] Deep link to grid:", gridParam);
    setGridDeepLinkHandled(true);

    // Switch to grids tab and dispatch event to show the specific grid
    setActiveTab("grids");
    // Small delay to ensure the tab is mounted before dispatching
    setTimeout(() => {
      window.dispatchEvent(new CustomEvent("show-grid-detail", { detail: gridParam }));
    }, 100);
  }, [gridParam, gridDeepLinkHandled]);

  // Convert discovery entries to Book format (with resolved usernames)
  // NOTE: This must be declared before the useEffect that uses it
  const allBooks = useMemo(() => entries.map(e => entryToBook(e, resolvedUsers)), [entries, resolvedUsers]);
  // Hidden items must never appear in the main browse feed or recent activity — only in the owner's hidden tab
  const books = useMemo(() => allBooks.filter(b => !b.hidden), [allBooks]);

  // Listen for navigate-to-book events (from grid viewer, user profile popover, etc.)
  useEffect(() => {
    const handleNavigateToBook = (event: Event) => {
      // Support both old format (string) and new format (object with contentKey + fromGridId)
      const customEvent = event as CustomEvent<string | { contentKey: string; fromGridId?: string }>;
      const detail = customEvent.detail;

      // Handle both string and object formats for backwards compatibility
      const contentKey = typeof detail === 'string' ? detail : detail?.contentKey;
      const fromGridId = typeof detail === 'object' ? detail?.fromGridId : undefined;

      if (contentKey) {
        // Find the book by contentKey — search allBooks so hidden items are navigable from hidden tab
        const book = allBooks.find(b => b.contentKey === contentKey || b.id === contentKey);
        if (book) {
          console.log("[MiniApp] Navigating to book:", book.title, fromGridId ? `(from grid ${fromGridId})` : "(from popover/other)");
          setSelectedBook(book);
          // Track that we came from a grid so back button can return there
          if (fromGridId) {
            setNavigationSource({ type: "grid", gridId: fromGridId });
            // Only switch to grids tab if we came from a grid
            setActiveTab("grids");
          }
          // If no fromGridId, don't change the active tab - back button will just close detail view
        } else {
          console.warn("[MiniApp] Book not found for contentKey:", contentKey);
        }
      }
    };
    window.addEventListener("navigate-to-book", handleNavigateToBook);
    return () => window.removeEventListener("navigate-to-book", handleNavigateToBook);
  }, [books]);

  // Handle deep link to book (?book=contentKey)
  // Use bookParam from getParam, falling back to windowBookParam from direct URL check
  const effectiveBookParam = bookParam || windowBookParam;

  useEffect(() => {
    if (bookDeepLinkHandled || !effectiveBookParam) return;

    // Log even if entries aren't loaded yet
    console.log("[MiniApp] Processing book deep link:", effectiveBookParam, "entries loaded:", entries.length);

    // Wait for entries to load
    if (entries.length === 0) {
      console.log("[MiniApp] Waiting for entries to load for book deep link...");
      return;
    }

    // Find the book by contentKey — search allBooks so hidden items are navigable via deep link
    const book = allBooks.find(b => b.contentKey === effectiveBookParam || b.id === effectiveBookParam);
    if (book) {
      console.log("[MiniApp] Found book for deep link:", book.title);
      setBookDeepLinkHandled(true);
      setSelectedBook(book);
    } else {
      // Book not found in current entries - log available keys for debugging
      console.warn("[MiniApp] Book not found in entries:", effectiveBookParam);
      console.log("[MiniApp] Available contentKeys:", allBooks.slice(0, 5).map(b => b.contentKey));
      // Mark as handled to prevent infinite loop, but don't select anything
      setBookDeepLinkHandled(true);
    }
  }, [effectiveBookParam, entries.length, allBooks, bookDeepLinkHandled]);

  const handleShare = (book: Book) => {
    const baseUrl = window.location.origin;

    // Build clean share URL using contentKey only
    // The /share/book/[key] route looks up book info from KV cache for OG metadata
    // This keeps URLs short and clean for social sharing
    const contentKey = book.contentKey || book.id;

    // Minimal URL - just the content key path
    // The share page will fetch title, author, and cover from the database
    const shareUrl = `${baseUrl}/share/book/${encodeURIComponent(contentKey)}`;

    console.log("[handleShare] Share URL:", shareUrl, "length:", shareUrl.length);

    // Normalize cover URL for display in share modal
    const normalizedCoverUrl = normalizeCoverUrl(book.coverUrl);

    // Open share modal with book data
    setShareBookData({
      title: book.title,
      author: book.author,
      coverUrl: normalizedCoverUrl,
      shareUrl,
    });
    setShowShareModal(true);
  };

  const handleViewOnNetProtocol = async (book: Book) => {
    // Use operator (backend wallet) for CDN URL, fall back to uploader.address for backwards compatibility
    const operatorAddress = book.operator || book.uploader?.address || "";
    const contentKey = book.contentKey || book.id;

    // Link to Net Protocol storage viewer
    // Format: https://www.netprotocol.app/app/storage/base/{operator}/{contentKey}
    const netProtocolUrl = `https://www.netprotocol.app/app/storage/base/${operatorAddress}/${encodeURIComponent(contentKey)}`;

    console.log("[handleViewOnNetProtocol] Opening Net Protocol:", netProtocolUrl);

    // Use safe wrapper that handles both Farcaster and Base App modes
    await safeOpenUrl(netProtocolUrl);
  };

  // Handle hiding/unhiding an item from the library feed
  // Includes FID for cross-platform ownership verification (users can manage content
  // from any of their linked wallets, regardless of which platform they're on)
  const handleHideFromLibrary = useCallback(async (contentKey: string, hidden: boolean) => {
    if (!address) throw new Error("No wallet connected");

    const response = await fetch("/api/discovery", {
      method: "PATCH",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        contentKey,
        operator: address,
        hidden,
        fid: memberFid, // Include FID for cross-platform ownership lookup
      }),
    });

    if (!response.ok) {
      const data = await response.json();
      throw new Error(data.error || "Failed to hide item");
    }

    // Refresh the discovery index to reflect the change
    refreshBooks();
  }, [address, memberFid, refreshBooks]);

  // Handle starting to read a book - fetch content and track activity
  const handleStartReading = useCallback(async (book: Book) => {
    console.log("[handleStartReading] Book object:", {
      title: book.title,
      mediaType: book.mediaType,
      cdnUrl: book.cdnUrl,
      coverUrl: book.coverUrl,
      contentKey: book.contentKey,
      storageType: book.storageType,
    });

    setIsReading(true);
    setBookPdfDataUrl(null);
    setBookIsPdf(false);
    setDetectedMediaType(null);
    setDetectedCdnUrl(null);

    // SHORT-CIRCUIT: For CDN-imported binary media (audio/video/image) that already have
    // mediaType and cdnUrl, skip the book-content API call — we have everything we need.
    // Text is intentionally excluded: it must go through book-content to base64-decode
    // the stored content and parse it into sentences for ReadingView.
    if (book.mediaType && book.cdnUrl && ["audio", "video", "image"].includes(book.mediaType)) {
      console.log("[handleStartReading] CDN import with stored mediaType - skipping API call");
      console.log("[handleStartReading] Using stored mediaType:", book.mediaType, "cdnUrl:", book.cdnUrl);
      // No need to set detectedMediaType/detectedCdnUrl - the reading view will use book.mediaType/book.cdnUrl directly
      setBookSentences([`Loading ${book.mediaType} content...`]);
    }
    // Fetch actual book content from Net Protocol for non-CDN imports
    // IMPORTANT: Use operator (backend wallet) for CDN access, not uploader.address (user's wallet)
    // Fall back to uploader.address for backwards compatibility with older entries
    else if ((book.operator || book.uploader?.address) && book.contentKey) {
      const operatorForFetch = book.operator || book.uploader?.address || "";
      const result = await fetchContent(
        book.contentKey,
        operatorForFetch,
        book.storageType || "regular"
      );
      setBookSentences(result.sentences);
      setBookPdfDataUrl(result.pdfDataUrl);
      setBookIsPdf(result.isPdf);

      // Handle detected media types from API (for files uploaded without mediaType)
      if (result.mediaType === "audio" || result.mediaType === "video" || result.mediaType === "image" || result.mediaType === "text") {
        console.log("[handleStartReading] Detected media type from API:", result.mediaType, "CDN URL:", result.cdnUrl);
        setDetectedMediaType(result.mediaType);
        setDetectedCdnUrl(result.cdnUrl);
      }
    } else {
      // Fallback for books without proper keys
      setBookSentences([
        `📖 "${book.title}" by ${book.author}`,
        "Content loading...",
        "Try clicking 'Open' to view the full document.",
      ]);
    }

    // Track engagement "open" action for read counts
    // Only count as a read if the reader is NOT the uploader (reads by OTHER users)
    const isOwnUpload = address && book.uploader?.address &&
      address.toLowerCase() === book.uploader?.address?.toLowerCase();

    if (book.contentKey && !isOwnUpload) {
      try {
        await fetch("/api/engagement", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            action: "open",
            contentKey: book.contentKey,
            userAddress: address,
          }),
        });
      } catch (err) {
        console.error("Failed to track engagement open:", err);
      }
    }
  }, [address, fetchContent]);

  // Handle "Net Library" title tap - return to home/browse
  const handleHomeClick = useCallback(() => {
    setSelectedBook(null);
    setViewingStack(null);
    setIsReading(false);
    setActiveTab("browse");
    setNavigationSource(null);
    setPreviousStack(null);
  }, []);

  // Stack detail view
  // Desktop: wider container
  const detailContainerClass = isDesktop
    ? isWideDesktop
      ? "h-dvh flex flex-col overflow-hidden bg-black max-w-[800px] mx-auto border-x border-[#00ff00]/10"
      : "h-dvh flex flex-col overflow-hidden bg-black max-w-[600px] mx-auto"
    : "h-dvh flex flex-col overflow-hidden bg-black";

  if (viewingStack) {
    return (
      <div className={detailContainerClass}>
        <Header onHomeClick={handleHomeClick} />
        <div className="flex-1 overflow-y-auto">
          <div className={isDesktop ? "p-6" : "p-4"}>
            <StackDetail
              key={viewingStack.id}
              stackId={viewingStack.id}
              onBack={() => {
                setViewingStack(null);
                setStackInitialFiles(null);
              }}
              onSelectBook={(book) => {
                setSelectedBook(book);
                // Remember we came from this stack for back navigation
                setPreviousStack(viewingStack);
                setNavigationSource({ type: "stack", stack: viewingStack });
                setViewingStack(null);
                setStackInitialFiles(null);
              }}
              initialFiles={stackInitialFiles}
              onInitialFilesProcessed={() => setStackInitialFiles(null)}
            />
          </div>
        </div>
      </div>
    );
  }

  // Reading view
  if (isReading && selectedBook) {
    // Detect media type - priority order:
    // 1. API-detected media type (detectedMediaType) - most accurate, from actual file content
    // 2. Stored mediaType on the book entry
    // 3. File extension detection from title
    let mediaType: string | undefined = detectedMediaType || selectedBook.mediaType;
    if (!mediaType) {
      const detectedType = detectMediaTypeFromTitle(selectedBook.title);
      if (detectedType && detectedType !== "pdf") {
        mediaType = detectedType;
      }
    }

    // For multimedia content (audio, video, image), use the MultimediaViewer.
    // Text files use ReadingView for the sentence-by-sentence reader with speech synthesis.
    const isMultimedia = mediaType && ["audio", "video", "image"].includes(mediaType);

    // Show loading screen while determining content type (API call in progress)
    // This prevents the flash of "reader" view before showing the correct viewer
    if (isLoadingContent && !isMultimedia && !bookIsPdf) {
      return (
        <div className="h-dvh flex flex-col overflow-hidden bg-black">
          <header className="shrink-0 px-4 py-3 border-b border-[#00ff00]/30 flex items-center gap-3 bg-black">
            <button
              onClick={() => {
                setIsReading(false);
                setBookSentences([]);
                setBookPdfDataUrl(null);
                setBookIsPdf(false);
                setDetectedMediaType(null);
                setDetectedCdnUrl(null);
              }}
              className="w-10 h-10 rounded-full bg-[#1a1a1a] flex items-center justify-center text-white hover:bg-[#222]"
            >
              ←
            </button>
            <div className="flex-1 min-w-0">
              <h3 className="text-[#00ff00] font-mono tracking-tight truncate">{selectedBook.title}</h3>
              <span className="text-gray-500 font-mono text-sm truncate block">{selectedBook.author}</span>
            </div>
          </header>
          <div className="flex-1 flex flex-col items-center justify-center gap-4">
            <div className="w-16 h-16 border-4 border-[#00ff00]/30 border-t-[#00ff00] rounded-full animate-spin" />
            <p className="text-[#00ff00] font-mono text-sm">Detecting content type...</p>
          </div>
        </div>
      );
    }

    if (isMultimedia) {
      // Use CDN URL - priority order:
      // 1. API-detected CDN URL (detectedCdnUrl)
      // 2. Stored cdnUrl on the book entry
      // 3. Constructed URL from contentKey and operator
      // IMPORTANT: Use operator (backend wallet) for CDN URLs, NOT uploader.address (user's wallet)
      console.log("[Reading View] URL sources:", {
        detectedCdnUrl,
        bookCdnUrl: selectedBook.cdnUrl,
        contentKey: selectedBook.contentKey,
        operator: selectedBook.operator,
        uploaderAddress: selectedBook.uploader?.address,
        storageType: selectedBook.storageType,
        mediaType: selectedBook.mediaType,
      });

      // Use operator for CDN URL construction (backend wallet that wrote to blockchain)
      // Fall back to uploader.address for backwards compatibility with older entries
      const operatorForCdn = selectedBook.operator || selectedBook.uploader?.address;
      // For chunked/xml storage, ALWAYS use constructCdnUrl because Net Protocol's
      // /chunked-storage/file/ and /storage/load/ endpoints return 404.
      // Our /api/book-file proxy correctly fetches via /storage/raw/ endpoint.
      const isChunkedOrXml = selectedBook.storageType === "chunked" || selectedBook.storageType === "xml";
      const contentUrl = detectedCdnUrl ||
        (isChunkedOrXml && selectedBook.contentKey && operatorForCdn
          ? constructCdnUrl(selectedBook.contentKey, operatorForCdn, selectedBook.storageType)
          : selectedBook.cdnUrl) ||
        (selectedBook.contentKey && operatorForCdn
          ? constructCdnUrl(selectedBook.contentKey, operatorForCdn, selectedBook.storageType)
          : null);

      console.log("[Reading View] Multimedia detected - type:", mediaType, "url:", contentUrl, "operator:", operatorForCdn);

      if (contentUrl) {
        return (
          <MultimediaViewer
            contentUrl={contentUrl}
            contentType={mediaType as "audio" | "video" | "image" | "text"}
            title={selectedBook.title}
            author={selectedBook.author}
            coverUrl={selectedBook.coverUrl}
            contentKey={selectedBook.contentKey}
            operatorAddress={operatorForCdn || ""}
            upvoteCount={selectedBook.contentKey ? getUpvoteCount(selectedBook.contentKey) : 0}
            socialPlatform={selectedBook.socialPlatform}
            isEncrypted={selectedBook.encrypted}
            onBack={() => {
              setIsReading(false);
              setBookSentences([]);
              setBookPdfDataUrl(null);
              setBookIsPdf(false);
              setDetectedMediaType(null);
              setDetectedCdnUrl(null);
            }}
            onShare={() => handleShare(selectedBook)}
            onUpvoteSuccess={() => refreshUpvotes()}
          />
        );
      }
    }

    // For PDFs, use the PDF reader component
    if (bookIsPdf && bookPdfDataUrl) {
      return (
        <PdfReader
          pdfUrl={bookPdfDataUrl}
          title={selectedBook.title}
          author={selectedBook.author}
          contentKey={selectedBook.contentKey}
          operatorAddress={selectedBook.operator || selectedBook.uploader?.address || ""}
          upvoteCount={selectedBook.contentKey ? getUpvoteCount(selectedBook.contentKey) : 0}
          onBack={() => {
            setIsReading(false);
            setBookSentences([]);
            setBookPdfDataUrl(null);
            setBookIsPdf(false);
            setDetectedMediaType(null);
            setDetectedCdnUrl(null);
          }}
          onShare={() => handleShare(selectedBook)}
          onUpvoteSuccess={() => refreshUpvotes()}
        />
      );
    }

    // Show loading state while fetching content
    const displaySentences = bookSentences.length > 0
      ? bookSentences
      : isLoadingContent
        ? ["Loading book content from Net Protocol...", "Please wait..."]
        : ["No content loaded yet."];

    return (
      <ReadingView
        book={selectedBook}
        sentences={displaySentences}
        voiceOptions={VOICE_OPTIONS}
        categories={CATEGORIES}
        upvoteCount={selectedBook.contentKey ? getUpvoteCount(selectedBook.contentKey) : 0}
        onBack={() => {
          setIsReading(false);
          setBookSentences([]);
          setBookPdfDataUrl(null);
          setBookIsPdf(false);
          setDetectedMediaType(null);
          setDetectedCdnUrl(null);
        }}
        onShare={() => handleShare(selectedBook)}
        onUpvoteSuccess={() => refreshUpvotes()}
      />
    );
  }

  // Book detail view
  if (selectedBook) {
    return (
      <>
        <BookDetail
          book={selectedBook}
          categories={CATEGORIES}
          upvoteCount={selectedBook.contentKey ? getUpvoteCount(selectedBook.contentKey) : 0}
          currentUserAddress={address}
          userLinkedAddresses={userAllAddresses}
          onBack={() => {
            // Navigate back based on where we came from
            if (navigationSource?.type === "stack") {
              // Came from a stack - go back to that stack
              setViewingStack(navigationSource.stack);
              setNavigationSource(null);
              setPreviousStack(null);
            } else if (navigationSource?.type === "grid") {
              // Came from a grid - dispatch event to re-open that grid
              window.dispatchEvent(new CustomEvent("show-grid-detail", {
                detail: navigationSource.gridId
              }));
              setNavigationSource(null);
              setActiveTab("grids");
            } else if (previousStack) {
              // Legacy fallback: If we came from a stack via the old method
              setViewingStack(previousStack);
              setPreviousStack(null);
              setNavigationSource(null);
            }
            // For "browse" type navigation source, don't clear it yet -
            // it will be used by BrowseTab to restore the filter state
            // The navigation source will be cleared when user changes tabs or filters
            setSelectedBook(null);
          }}
          onRead={() => handleStartReading(selectedBook)}
          onViewOnNetProtocol={() => handleViewOnNetProtocol(selectedBook)}
          onShare={() => handleShare(selectedBook)}
          onUpvoteSuccess={() => refreshUpvotes()}
          onHideFromLibrary={handleHideFromLibrary}
          onEditDetails={() => {
            // Find the DiscoveryEntry for this book to open the edit modal
            const entry = entries.find(e => e.contentKey === selectedBook.id);
            if (entry) {
              setEditingEntry(entry);
            }
          }}
        />
        {/* Share Modal - needs to be here for book detail view */}
        {shareBookData && (
          <ShareModal
            isOpen={showShareModal}
            onClose={() => {
              setShowShareModal(false);
              setShareBookData(null);
            }}
            title={shareBookData.title}
            author={shareBookData.author}
            coverUrl={shareBookData.coverUrl}
            shareUrl={shareBookData.shareUrl}
          />
        )}
        {/* Edit Item Modal - for item owners to edit metadata */}
        {editingEntry && (
          <EditItemModal
            isOpen={!!editingEntry}
            onClose={() => setEditingEntry(null)}
            entry={editingEntry}
            categories={CATEGORIES}
            currentUserAddress={address}
            userFid={memberFid}
            onUpdate={() => {
              refreshBooks(); // Refresh discovery data
              setEditingEntry(null);
              // Update the selected book with new data
              const updatedEntry = entries.find(e => e.contentKey === editingEntry.contentKey);
              if (updatedEntry) {
                setSelectedBook(entryToBook(updatedEntry, resolvedUsers));
              }
            }}
          />
        )}
      </>
    );
  }

  // Main library view
  // Desktop: wider container with max-width, centered
  // Mobile: full width (424px Farcaster default)
  const containerClass = isDesktop
    ? isWideDesktop
      ? "h-dvh flex flex-col overflow-hidden bg-black max-w-[800px] mx-auto border-x border-[#00ff00]/10"
      : "h-dvh flex flex-col overflow-hidden bg-black max-w-[600px] mx-auto"
    : "h-dvh flex flex-col overflow-hidden bg-black";

  return (
    <div className={containerClass}>
      {/* Connectivity Banner - shows when offline */}
      <ConnectivityBanner />

      {/* Welcome Popup - shows on first visit or prompts for account linking */}
      <WelcomePopup onNavigateToMembership={() => setActiveTab("library")} />

      {/* Farcaster Link Modal - auto-opens when returning from auth redirect */}
      <LinkFarcasterModal
        isOpen={showFcLinkModal}
        onClose={() => {
          setShowFcLinkModal(false);
          clearFcCallback();
        }}
        onSuccess={() => {
          setShowFcLinkModal(false);
          clearFcCallback();
          refreshMembership();
        }}
        claimExistingMembership={fcCallbackData?.pendingData?.mode === "claim"}
      />

      {/* Share Modal - share books to Farcaster or X */}
      {shareBookData && (
        <ShareModal
          isOpen={showShareModal}
          onClose={() => {
            setShowShareModal(false);
            setShareBookData(null);
          }}
          title={shareBookData.title}
          author={shareBookData.author}
          coverUrl={shareBookData.coverUrl}
          shareUrl={shareBookData.shareUrl}
        />
      )}

      <Header onHomeClick={handleHomeClick} />
      <ScrollingBanner />

      <Tabs value={activeTab} onValueChange={setActiveTab} className="flex-1 flex flex-col min-h-0 mt-3">
        <TabsList className="shrink-0 w-full justify-start rounded-none bg-black px-2 pb-2 pt-0 gap-1">
          <TabsTrigger
            value="browse"
            className="flex-1 py-3 rounded-lg font-mono text-xs border transition-all data-[state=active]:!bg-[#00ff00] data-[state=active]:!text-black data-[state=active]:!border-[#00ff00] data-[state=inactive]:!bg-transparent data-[state=inactive]:!border-[#00ff00] data-[state=inactive]:!text-[#00ff00] hover:bg-[#00ff00]/10"
          >
            Stacks
          </TabsTrigger>
          <TabsTrigger
            value="grids"
            className="flex-1 py-3 rounded-lg font-mono text-xs border transition-all data-[state=active]:!bg-[#00ff00] data-[state=active]:!text-black data-[state=active]:!border-[#00ff00] data-[state=inactive]:!bg-transparent data-[state=inactive]:!border-[#00ff00] data-[state=inactive]:!text-[#00ff00] hover:bg-[#00ff00]/10"
          >
            Grids
          </TabsTrigger>
          <TabsTrigger
            value="upload"
            className="flex-1 py-3 rounded-lg font-mono text-xs border transition-all data-[state=active]:!bg-[#00ff00] data-[state=active]:!text-black data-[state=active]:!border-[#00ff00] data-[state=inactive]:!bg-transparent data-[state=inactive]:!border-[#00ff00] data-[state=inactive]:!text-[#00ff00] hover:bg-[#00ff00]/10"
          >
            Upload
          </TabsTrigger>
          <TabsTrigger
            value="library"
            className="flex-1 py-3 rounded-lg font-mono text-xs border transition-all data-[state=active]:!bg-[#00ff00] data-[state=active]:!text-black data-[state=active]:!border-[#00ff00] data-[state=inactive]:!bg-transparent data-[state=inactive]:!border-[#00ff00] data-[state=inactive]:!text-[#00ff00] hover:bg-[#00ff00]/10"
          >
            Members
          </TabsTrigger>
          <TabsTrigger
            value="leaderboard"
            className="flex-1 py-3 rounded-lg font-mono text-xs border transition-all data-[state=active]:!bg-[#00ff00] data-[state=active]:!text-black data-[state=active]:!border-[#00ff00] data-[state=inactive]:!bg-transparent data-[state=inactive]:!border-[#00ff00] data-[state=inactive]:!text-[#00ff00] hover:bg-[#00ff00]/10"
          >
            Info
          </TabsTrigger>
        </TabsList>

        <TabsContent value="browse" className="flex-1 min-h-0 mt-0 bg-black overflow-hidden">
          <ErrorBoundary section="Browse">
            <PullToRefresh onRefresh={refreshBooks} className="h-full px-4 pt-2 pb-4">
              <BrowseTab
                books={books}
                categories={CATEGORIES}
                onSelectBook={(book, navContext) => {
                  setSelectedBook(book);
                  // Store browse navigation context for proper back navigation
                  if (navContext) {
                    setNavigationSource({
                      type: "browse",
                      subNav: navContext.subNav,
                      filter: navContext.mediaFilter,
                    });
                  }
                }}
                onShare={handleShare}
                isLoading={isLoadingBooks}
                error={booksError}
                onRefresh={refreshBooks}
                // Pass back the filter state when returning from item detail
                initialSubNav={navigationSource?.type === "browse" ? navigationSource.subNav : undefined}
                initialMediaFilter={navigationSource?.type === "browse" ? navigationSource.filter : undefined}
              />
            </PullToRefresh>
          </ErrorBoundary>
        </TabsContent>

        <TabsContent value="grids" className="flex-1 min-h-0 mt-0 bg-black overflow-hidden">
          <ErrorBoundary section="Grids">
            <PullToRefresh onRefresh={refreshBooks} className="h-full px-4 pt-2 pb-4">
              <GridsTab />
            </PullToRefresh>
          </ErrorBoundary>
        </TabsContent>

        <TabsContent value="upload" className="flex-1 overflow-y-auto px-4 pt-2 pb-4 mt-0 bg-black">
          <ErrorBoundary section="Upload">
            <UploadTab categories={CATEGORIES} books={books} onUploadComplete={refreshBooks} onNavigateToProfile={() => setActiveTab("library")} isActive={activeTab === "upload"} />
          </ErrorBoundary>
        </TabsContent>

        <TabsContent value="library" className="flex-1 min-h-0 mt-0 bg-black overflow-hidden">
          <ErrorBoundary section="My Library">
            <PullToRefresh onRefresh={refreshBooks} className="h-full px-4 pt-2 pb-4">
              <MyLibraryTab
                categories={CATEGORIES}
              />
            </PullToRefresh>
          </ErrorBoundary>
        </TabsContent>

        <TabsContent value="leaderboard" className="flex-1 min-h-0 mt-0 bg-black overflow-hidden">
          <ErrorBoundary section="Leaderboard">
            <PullToRefresh onRefresh={refreshBooks} className="h-full px-4 pt-2 pb-4">
              <LeaderboardTab categories={CATEGORIES} />
            </PullToRefresh>
          </ErrorBoundary>
        </TabsContent>
      </Tabs>

      {/* Global Member Profile View - renders on top of everything */}
      <MemberProfileView />
    </div>
  );
}
src/features/app/providers-and-initialization.tsx
"use client";

import { ReactNode, useState, useEffect } from "react";
import { Provider as JotaiProvider } from "jotai";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { InitializeFarcasterMiniApp } from "@/neynar-farcaster-sdk/mini";
import { NeynarWagmiProvider } from "@/neynar-web-sdk/blockchain";
import { DiscoveryProvider } from "@/contexts/discovery-context";
import { StoragePassProvider } from "@/features/app/components/unlimited-storage-pass-modal";
import { MemberProfileProvider } from "@/contexts/member-profile-context";

export function ProvidersAndInitialization({
  children,
}: {
  children: ReactNode;
}) {
  const [queryClient] = useState(() => new QueryClient());
  // Guard: wagmi/farcaster hooks use useRef internally and crash during Next.js
  // static prerendering (build workers). Only mount the full provider tree client-side.
  const [mounted, setMounted] = useState(false);
  useEffect(() => { setMounted(true); }, []);

  if (!mounted) {
    // During SSR and static prerender, render children without the hook-heavy providers.
    // The page content (embed widgets, share pages, etc.) renders fine without them.
    return <>{children}</>;
  }

  return (
    <JotaiProvider>
      <QueryClientProvider client={queryClient}>
        {/* LLMs: Add additional providers between here */}
        <NeynarWagmiProvider>
        <DiscoveryProvider>
        <StoragePassProvider>
        <MemberProfileProvider>
        {/* and here */}
        {/* LLMs: Do not remove, initialization must be last, before children */}
        <InitializeFarcasterMiniApp />
        {children}
        {/* End Do not remove */}
        </MemberProfileProvider>
        </StoragePassProvider>
        </DiscoveryProvider>
        </NeynarWagmiProvider>
      </QueryClientProvider>
    </JotaiProvider>
  );
}
src/features/app/types-filesystem.ts
import type { Stack, StackItem } from "./types";

/**
 * Extended stack item with filesystem path information.
 * Used when a stack is in filesystem mode.
 */
export interface FileSystemItem extends StackItem {
  path: string;           // Full path e.g. "/src/index.ts"
  fileName: string;       // Just the filename e.g. "index.ts"
  fileSize: number;       // Size in bytes
  mimeType?: string;      // MIME type e.g. "text/typescript"
  isDirectory: boolean;   // true = virtual folder node, false = real file
  parentPath: string;     // Parent directory e.g. "/src"
}

/**
 * Extended stack metadata for filesystem mode.
 * These fields are added to the Stack KV entry when isFileSystem is true.
 */
export interface FileSystemStackMeta {
  isFileSystem: boolean;
  totalSize: number;          // Total bytes across all files
  fileCount: number;          // Number of actual files (not folders)
  sourceType?: "upload" | "zip" | "github" | "drag-drop";
  sourceUrl?: string;         // GitHub repo URL if imported
  sourceCommit?: string;      // Git commit hash at import time
}

/**
 * A Stack that has filesystem mode enabled.
 * In practice, the Stack KV entry will have these extra fields merged in.
 */
export type FileSystemStack = Stack & FileSystemStackMeta;

/**
 * Tree node for rendering folder structures in the UI.
 * Built from a flat list of FileSystemItems.
 */
export interface FileTreeNode {
  name: string;               // File or folder name
  path: string;               // Full path
  isDirectory: boolean;
  size?: number;              // File size in bytes (undefined for folders)
  mimeType?: string;
  contentKey?: string;        // Only for files — links to Net Protocol content
  children: FileTreeNode[];   // Sub-items (empty array for files)
}

/**
 * Build a tree structure from a flat list of FileSystemItems.
 * Used by the FolderTreeView component.
 */
export function buildFileTree(items: FileSystemItem[]): FileTreeNode[] {
  const root: FileTreeNode[] = [];
  const nodeMap = new Map<string, FileTreeNode>();

  // Sort items so directories come first and paths are in order
  const sorted = [...items].sort((a, b) => {
    if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;
    return a.path.localeCompare(b.path);
  });

  for (const item of sorted) {
    const node: FileTreeNode = {
      name: item.fileName,
      path: item.path,
      isDirectory: item.isDirectory,
      size: item.isDirectory ? undefined : item.fileSize,
      mimeType: item.mimeType,
      contentKey: item.isDirectory ? undefined : item.contentKey,
      children: [],
    };

    nodeMap.set(item.path, node);

    if (item.parentPath === "/" || item.parentPath === "") {
      root.push(node);
    } else {
      const parent = nodeMap.get(item.parentPath);
      if (parent) {
        parent.children.push(node);
      } else {
        // Parent not yet created — create intermediate directory nodes
        const parts = item.parentPath.split("/").filter(Boolean);
        let currentPath = "";
        let currentChildren = root;

        for (const part of parts) {
          currentPath += "/" + part;
          let existing = nodeMap.get(currentPath);
          if (!existing) {
            existing = {
              name: part,
              path: currentPath,
              isDirectory: true,
              children: [],
            };
            nodeMap.set(currentPath, existing);
            currentChildren.push(existing);
          }
          currentChildren = existing.children;
        }
        currentChildren.push(node);
      }
    }
  }

  return root;
}

/**
 * Calculate total size of all files in a tree.
 */
export function calculateTreeSize(nodes: FileTreeNode[]): number {
  let total = 0;
  for (const node of nodes) {
    if (node.isDirectory) {
      total += calculateTreeSize(node.children);
    } else {
      total += node.size || 0;
    }
  }
  return total;
}

/**
 * Count files (not directories) in a tree.
 */
export function countFiles(nodes: FileTreeNode[]): number {
  let count = 0;
  for (const node of nodes) {
    if (node.isDirectory) {
      count += countFiles(node.children);
    } else {
      count++;
    }
  }
  return count;
}

/**
 * Common files/folders to filter out during import.
 */
export const IGNORED_PATHS = [
  ".DS_Store",
  "Thumbs.db",
  "__MACOSX",
  ".git",
  "node_modules",
  "dist",
  "build",
  ".next",
  ".env",
  ".env.local",
];

/**
 * Check if a path should be ignored during import.
 */
export function shouldIgnorePath(path: string): boolean {
  const parts = path.split("/");
  return parts.some(part => IGNORED_PATHS.includes(part));
}
src/features/app/types.ts
// Net Library - Type Definitions

/**
 * Book category with label and emoji
 */
export interface Category {
  id: string;
  label: string;
  emoji: string;
}

/**
 * User profile for uploaders and current user
 */
export interface User {
  username: string;
  pfpUrl: string;
  fid?: number;
}

/**
 * Current user with upload stats
 */
export interface CurrentUser extends User {
  uploads: number;
}

/**
 * Content type for multimedia support
 */
export type ContentMediaType = "pdf" | "image" | "audio" | "video" | "text" | "unknown";

/**
 * Book in the library (browsable)
 */
// Social platform type for social receipts
export type SocialPlatform = "farcaster" | "twitter" | "youtube" | "instagram" | "tiktok" | "reddit" | "bluesky" | "threads" | "linkedin" | "paragraph";

export interface Book {
  id: string;
  title: string;
  author: string;
  categories: string[]; // up to 3 category tags
  uploader: User & { address?: string }; // include address for upvoting/tipping (user's wallet)
  uploadDate: string;
  size: string;
  coverUrl?: string; // optional cover art URL, emoji fallback if not set
  contentKey?: string; // Net Protocol content key for upvotes
  storageType?: "regular" | "chunked" | "xml"; // Net Protocol storage type
  // IMPORTANT: operator = backend wallet that wrote to blockchain (for CDN URL generation)
  // This is DIFFERENT from uploader.address which is the user's wallet for attribution
  operator?: string; // Backend wallet for CDN URL construction
  // Optional metadata fields
  publicationYear?: number;
  publisher?: string;
  isbn?: string; // ISBN or DOI
  // Multimedia support
  mediaType?: ContentMediaType; // Type of content (pdf, image, audio, video, text)
  cdnUrl?: string; // Direct CDN URL for multimedia content
  // Social receipt support
  isSocialReceipt?: boolean;
  socialPlatform?: SocialPlatform;
  originalUrl?: string; // Original URL of the social post (legacy — same as sourceUrl)
  sourceUrl?: string;   // Source URL of the social post (e.g. Warpcast URL for archived casts)
  // Agent identity
  isAgentUploaded?: boolean; // True if this item was uploaded by a registered agent
  agentId?: string; // The agent's registered ID (e.g., "cheryl")
  // Encryption — content is AES-256-GCM encrypted; password shared out-of-band
  // Title, description, categories, and all other metadata remain plaintext/public.
  encrypted?: boolean;
  // Partner import attribution — set to the partner's siteName when imported via partner API.
  // Null/undefined for items uploaded directly through Net Library.
  source?: string;
}

/**
 * Book uploaded by the current user
 */
export interface UploadedBook {
  id: string;
  title: string;
  author: string;
  categories: string[]; // up to 3 category tags
  uploadDate: string;
  size: string;
  shares: number; // times other users shared this book
}


/**
 * Book in reading queue
 */
export interface QueuedBook {
  id: string;
  title: string;
  author: string;
  categories: string[]; // up to 3 category tags
  addedDate: string;
  estimatedReadTime: string;
  progress: number; // 0-100
}


/**
 * Upload status during chunked upload
 */
export type UploadStatus = "idle" | "selected" | "uploading" | "complete" | "error";

/**
 * Chunk transaction status
 */
export type ChunkStatus = "pending" | "signing" | "confirming" | "done" | "waiting-onchain";

/**
 * Duplicate warning when uploading
 */
export interface DuplicateWarning {
  type: "exact" | "similar";
  matchedBooks: Book[];
}

/**
 * Upload state for tracking chunked uploads
 */
export interface UploadState {
  status: UploadStatus;
  fileName: string;
  fileSize: number;
  totalChunks: number;
  completedChunks: number;
  currentChunkStatus: ChunkStatus;
  error?: string;
  duplicateWarning?: DuplicateWarning;
  cdnUrl?: string;
  txHash?: string;
  usedBatchMode?: boolean;
  currentBatch?: number;
  totalBatches?: number;
  isFunding?: boolean; // True when funding Upload Wallet (USDC transfer in progress)
  isImport?: boolean; // True for CDN link imports (not new uploads to Net Protocol)
}

/**
 * Voice options for text-to-speech
 */
export type VoiceGender = "male" | "female";

export interface VoiceOption {
  id: VoiceGender;
  label: string;
  emoji: string;
}

/**
 * My Library tab options
 */
export type MyLibraryTab = "uploaded" | "queue" | "stacks";

/**
 * Stack - A public playlist of onchain items, managed by its owner
 * Can also represent a filesystem/repository structure when isFileSystem is true
 */
export interface Stack {
  id: string; // Unique stack ID
  name: string;
  description?: string;
  owner: string; // Wallet address
  ownerFid?: number; // Farcaster FID if available (for cross-platform identity)
  ownerUsername?: string; // Display name
  ownerPfpUrl?: string; // Profile picture
  createdAt: number; // Timestamp
  creationTxHash?: string; // Payment proof for non-members
  unlocked: boolean; // True if unlimited items unlocked
  unlockedAt?: number; // Timestamp when unlocked
  unlockTxHash?: string; // Payment proof for unlock
  itemCount: number; // Number of items in stack (may include hidden)
  visibleItemCount?: number; // Number of visible items (excludes hidden)
  upvotes?: number; // Cached upvote count
  views?: number; // View count
  isPrivate?: boolean; // If true, stack is only visible to owner
  previewCovers?: string[]; // First few item cover URLs for thumbnail previews
  // Filesystem mode fields
  isFileSystem?: boolean; // True if this stack represents a folder structure
  sourceType?: "upload" | "github" | "url"; // Source of the files
  sourceUrl?: string; // GitHub repo URL or other source URL
  sourceCommit?: string; // Git commit SHA for repositories
  totalSize?: number; // Total size of all files in bytes
  fileCount?: number; // Number of files (excludes directories)
  // Agent identity
  isAgentCreated?: boolean; // True if this stack was created by a registered agent
  agentId?: string; // The agent's registered ID (e.g., "cheryl")
  // Moderation — hidden stacks are excluded from all public listings and return 404 on direct access.
  // Set via POST /api/admin/hide-stack — no code deploy required.
  hidden?: boolean;
  hiddenAt?: number; // Timestamp when hidden
  hiddenReason?: string; // Optional moderation note (admin-only, never surfaced in API)
}

/**
 * Stack item - A reference to an onchain item within a stack
 * Extended with filesystem metadata when parent stack is in filesystem mode
 */
export interface StackItem {
  contentKey: string; // Net Protocol content key
  addedAt: number; // Timestamp when added to stack
  addedBy: string; // Wallet address of who added it
  // Filesystem mode fields (only present when stack.isFileSystem is true)
  path?: string; // File path within the stack (e.g., "src/index.ts")
  fileName?: string; // File name without path
  fileSize?: number; // File size in bytes
  mimeType?: string; // MIME type of the file
  isDirectory?: boolean; // True if this represents a folder
  parentPath?: string; // Path to parent folder
}

/**
 * Stack creation request
 */
export interface CreateStackRequest {
  name: string;
  description?: string;
  ownerFid?: number; // Farcaster FID
  ownerUsername?: string; // Display username
  ownerPfpUrl?: string; // Profile picture URL
  txHash?: string; // Payment transaction hash (required for non-members)
  isPrivate?: boolean; // If true, stack is private by default
}

/**
 * Stack with full item details (for display)
 */
export interface StackWithItems extends Stack {
  items: (StackItem & { book?: Book })[]; // Items with optional book details
}
src/lib/achievements-service.ts
// Centralized achievements service
// All achievement checking and awarding goes through here

import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

const ACHIEVEMENTS_KEY = "user-achievements-index";

export interface UserAchievement {
  id: string;
  earnedAt: number;
}

export interface UserAchievements {
  address: string;
  achievements: UserAchievement[];
}

export interface AchievementsIndex {
  users: { [address: string]: UserAchievements };
  lastUpdated: number;
}

// Fetch achievements index from KV
export async function fetchAchievementsIndex(): Promise<AchievementsIndex> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, ACHIEVEMENTS_KEY)).limit(1);
    if (!result[0]?.value) return { users: {}, lastUpdated: Date.now() };
    return JSON.parse(result[0].value) as AchievementsIndex;
  } catch {
    return { users: {}, lastUpdated: Date.now() };
  }
}

// Store achievements index to KV
export async function storeAchievementsIndex(data: AchievementsIndex): Promise<boolean> {
  try {
    await db.insert(kv).values({ key: ACHIEVEMENTS_KEY, value: JSON.stringify(data) }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(data) },
    });
    return true;
  } catch (error) {
    console.error("storeAchievementsIndex error:", error);
    return false;
  }
}

// Get user's achievements (single address only - for internal use)
export async function getUserAchievements(address: string): Promise<UserAchievement[]> {
  const index = await fetchAchievementsIndex();
  return index.users[address.toLowerCase()]?.achievements || [];
}

// Get user's achievements with cross-platform identity support
// Aggregates achievements from all linked addresses
export async function getUserAchievementsCrossplatform(
  address: string,
  linkedAddresses?: string[]
): Promise<UserAchievement[]> {
  const index = await fetchAchievementsIndex();
  const normalizedAddress = address.toLowerCase();

  // Collect all addresses to check
  const addressesToCheck = new Set<string>([normalizedAddress]);
  linkedAddresses?.forEach(addr => addressesToCheck.add(addr.toLowerCase()));

  // Aggregate achievements from all addresses
  const allAchievements: UserAchievement[] = [];
  const seenIds = new Set<string>();

  for (const addr of addressesToCheck) {
    const userAchievements = index.users[addr]?.achievements || [];
    for (const achievement of userAchievements) {
      if (!seenIds.has(achievement.id)) {
        seenIds.add(achievement.id);
        allAchievements.push(achievement);
      }
    }
  }

  return allAchievements;
}

// Reset user's achievements (clear all and start fresh)
export async function resetUserAchievements(address: string): Promise<boolean> {
  const normalizedAddress = address.toLowerCase();
  const index = await fetchAchievementsIndex();

  if (index.users[normalizedAddress]) {
    index.users[normalizedAddress].achievements = [];
    index.lastUpdated = Date.now();
    await storeAchievementsIndex(index);
  }

  return true;
}

// Award an achievement to a user (if not already earned)
export async function awardAchievement(
  address: string,
  achievementId: string
): Promise<{ awarded: boolean; alreadyHad: boolean }> {
  const normalizedAddress = address.toLowerCase();
  const index = await fetchAchievementsIndex();

  // Initialize user if needed
  if (!index.users[normalizedAddress]) {
    index.users[normalizedAddress] = {
      address: normalizedAddress,
      achievements: [],
    };
  }

  // Check if already has achievement
  const hasAchievement = index.users[normalizedAddress].achievements.some(a => a.id === achievementId);
  if (hasAchievement) {
    return { awarded: false, alreadyHad: true };
  }

  // Award achievement
  index.users[normalizedAddress].achievements.push({
    id: achievementId,
    earnedAt: Date.now(),
  });
  index.lastUpdated = Date.now();

  await storeAchievementsIndex(index);
  return { awarded: true, alreadyHad: false };
}

// Award multiple achievements at once
export async function awardAchievements(
  address: string,
  achievementIds: string[]
): Promise<{ awarded: string[]; alreadyHad: string[] }> {
  const normalizedAddress = address.toLowerCase();
  const index = await fetchAchievementsIndex();

  // Initialize user if needed
  if (!index.users[normalizedAddress]) {
    index.users[normalizedAddress] = {
      address: normalizedAddress,
      achievements: [],
    };
  }

  const awarded: string[] = [];
  const alreadyHad: string[] = [];

  for (const achievementId of achievementIds) {
    const hasAchievement = index.users[normalizedAddress].achievements.some(a => a.id === achievementId);
    if (hasAchievement) {
      alreadyHad.push(achievementId);
    } else {
      index.users[normalizedAddress].achievements.push({
        id: achievementId,
        earnedAt: Date.now(),
      });
      awarded.push(achievementId);
    }
  }

  if (awarded.length > 0) {
    index.lastUpdated = Date.now();
    await storeAchievementsIndex(index);
  }

  return { awarded, alreadyHad };
}

// ============================================================================
// ACHIEVEMENT CHECKERS - Call these from various APIs
// ============================================================================

// Check upload-related achievements
export function checkUploadAchievements(stats: {
  totalUploads: number;
  categoriesContributed: string[];
}): string[] {
  const toAward: string[] = [];

  // First upload
  if (stats.totalUploads >= 1) toAward.push("first-upload");

  // Contributor milestones
  if (stats.totalUploads >= 5) toAward.push("contributor-5");
  if (stats.totalUploads >= 25) toAward.push("contributor-25");
  if (stats.totalUploads >= 100) toAward.push("contributor-100");

  return toAward;
}

// Check membership-related achievements
export function checkMembershipAchievements(stats: {
  memberId: number;
  joinedAt: number;
}): string[] {
  const toAward: string[] = [];

  // Member achievement - just being a member is enough
  toAward.push("early-adopter"); // "early-adopter" is now the "Member" achievement

  // OG member status
  if (stats.memberId <= 100) toAward.push("founding-member");
  if (stats.memberId <= 1000) toAward.push("og-member");

  return toAward;
}

// Check upvote-given achievements (for users who upvote content)
export function checkUpvoteGivenAchievements(stats: {
  totalUpvotesGiven: number;
}): string[] {
  const toAward: string[] = [];

  // First upvote
  if (stats.totalUpvotesGiven >= 1) toAward.push("first-upvote");

  // Alpha giver (100+ upvotes given)
  if (stats.totalUpvotesGiven >= 100) toAward.push("upvote-supporter");

  // Alpha king (1K+ upvotes given)
  if (stats.totalUpvotesGiven >= 1000) toAward.push("upvote-champion");

  // Alpha whale (10K+ upvotes given)
  if (stats.totalUpvotesGiven >= 10000) toAward.push("upvote-whale");

  return toAward;
}

// Check upvote-received achievements (for content creators)
export function checkUpvoteReceivedAchievements(stats: {
  totalUpvotesReceived: number;
}): string[] {
  const toAward: string[] = [];

  // Appreciated (100+ upvotes received)
  if (stats.totalUpvotesReceived >= 100) toAward.push("upvoted-creator");

  // Trending (1K+ upvotes received)
  if (stats.totalUpvotesReceived >= 1000) toAward.push("trending-creator");

  // Viral (10K+ upvotes received)
  if (stats.totalUpvotesReceived >= 10000) toAward.push("viral-creator");

  // Legendary (100K+ upvotes received)
  if (stats.totalUpvotesReceived >= 100000) toAward.push("legendary-creator");

  return toAward;
}

// Check data uploaded achievements (based on total bytes uploaded)
export function checkDataAchievements(stats: {
  totalBytesUploaded: number;
}): string[] {
  const toAward: string[] = [];
  const totalMB = stats.totalBytesUploaded / (1024 * 1024);

  // Data Drop (1 MB)
  if (totalMB >= 1) toAward.push("data-1mb");

  // Builder (100 MB)
  if (totalMB >= 100) toAward.push("data-100mb");

  // Architect (1 GB = 1000 MB)
  if (totalMB >= 1000) toAward.push("data-1000mb");

  // Librarian (10 GB = 10000 MB)
  if (totalMB >= 10000) toAward.push("data-10000mb");

  return toAward;
}
src/lib/agent-auth.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Agent API Shared Utilities
 *
 * Consolidates all shared helpers for /api/v1/ routes:
 * - KV storage helpers (getKV, setKV, deleteKV)
 * - CORS helpers for cross-origin agent requests
 * - Bearer token authentication for agents
 * - Admin authentication
 * - USDC payment verification on Base
 * - Member registry helpers
 */

import { NextRequest, NextResponse } from "next/server";
import { db, connection } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";

// =============================================================================
// CONSTANTS
// =============================================================================

// KV key prefixes
export const AGENTS_REGISTRY_KEY = "api-agents-registry";
export const AGENT_KEY_PREFIX = "api-agent:";
export const MEMBER_REGISTRY_KEY = "member-registry";

// USDC on Base
export const USDC_CONTRACT = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913";
export const TREASURY_ADDRESS = "0xAcAD71e697Ef3bb148093b2DD2fCf0845e957627";

// ERC-20 Transfer event signature
export const TRANSFER_TOPIC = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef";

// Pricing constants (in USDC)
export const PRICING = {
  MEMBERSHIP: 2,
  STORAGE_PASS: 10,  // Unlimited Pass — renamed from "Unlimited Storage Pass", price $10
  STACK_UNLOCK: 5,
  GRID_UNLOCK: 2,
  STACK_CREATION_NON_MEMBER: 5,
  PREMIUM_UPLOAD_PER_MB: 1,
} as const;

// =============================================================================
// TYPES
// =============================================================================

export interface RegisteredAgent {
  id: string;              // Unique agent ID (e.g., "cheryl", "archiver-bot")
  name: string;            // Display name
  username?: string;       // Handle/username (e.g. "cheryl" without the @)
  /**
   * Legacy agents (pre-C20): full key stored here (plaintext, v1 scheme).
   * C20+ agents: always "" (empty sentinel) or absent — full key lives ONLY
   * in api-key-lookup:{fullKey} → agentId. DO NOT check truthiness to test
   * whether a key exists; use apiKeyPrefix presence or member.apiKeyAgentId.
   * Fix F in authenticateAgent migrates "" → undefined on each write-back.
   */
  apiKey?: string;
  fid?: number;            // Farcaster ID if the agent has one
  address?: string;        // Wallet address if the agent has one
  pfpUrl?: string;         // Profile picture URL
  permissions: AgentPermission[];
  createdAt: number;
  lastActiveAt?: number;
  updatedAt?: number;      // Last update timestamp
  isActive?: boolean;      // Optional for backward compat — missing = active
  // ERC-8004 verification fields
  erc8004TokenId?: number;      // Token ID on the Base Identity Registry
  erc8004Verified?: boolean;    // True if verified on ERC-8004
  erc8004CheckedAt?: number;    // Timestamp of last verification check
}

export type AgentPermission =
  | "library:write"        // Can add items to the library (register URLs)
  | "library:archive"      // Can archive social posts
  | "stacks:create"        // Can create stacks
  | "stacks:write"         // Can add/remove items from stacks
  | "stacks:delete"        // Can delete stacks they own
  | "admin";               // Full access (for the library owner)

export interface MemberEntry {
  memberId: number;
  address: string;
  ensSubname: string;
  fid?: number;
  username?: string;
  joinedAt: string | number;        // Data has both formats
  txHash?: string;
  signupPlatform?: "farcaster" | "base-app" | "web" | "self-register" | "agent-purchase";
  isAgent?: boolean;
  agentId?: string;
  grantedBy?: string;
  grantType?: "paid" | "admin" | "promo";
  paymentTxHash?: string;
  paymentAmount?: number;
  linkedAddresses?: string[];
  hasStackPass?: boolean;
  hasUnlimitedPass?: boolean;           // Canonical field name (replaces hasStackPass/hasUnlimitedStoragePass)
  /** @deprecated use hasUnlimitedPass */
  hasUnlimitedStoragePass?: boolean;    // kept for KV backwards compatibility — do not write
  unlimitedPassTxHash?: string;
  unlimitedPassPurchasedAt?: number;
  // NFT mint fields (set when minted via 0xCe559A2A6b64504bE00aa7aA85C5C31AA93a16BB)
  unlimitedPassTokenId?: number;        // ERC-721 token ID on Base
  unlimitedPassTier?: string;           // "we are so early" | "early-ish"
  unlimitedPassMintTx?: string;         // Mint transaction hash on Base
  unlimitedPassVerified?: boolean;      // true = on-chain verified; false/undefined = pending verification
  pfpUrl?: string;
  displayName?: string;
  farcasterUsername?: string;
  wid?: string;
  customUsername?: string;          // User-editable username (web only)
  customPfpUrl?: string;            // User-uploaded PFP URL (web only)
  hasGridPass?: boolean;            // Legacy Grid Pass for large grids
  // ERC-8004 verification fields
  erc8004Verified?: boolean;        // True if verified on ERC-8004 Base Identity Registry
  erc8004TokenId?: number;          // Token ID on the registry
  erc8004CheckedAt?: number;        // Timestamp of last verification check
  // Self-service API key fields (C20)
  apiKeyAgentId?: string;           // Agent record ID for the member's self-service API key
  apiKeyCreatedAt?: number;         // Timestamp when API key was last generated
}

export interface MemberRegistry {
  members: MemberEntry[];
  nextMemberId: number;
  lastUpdated: number;
}

export interface AuthResult {
  agentId: string;
  agent: RegisteredAgent;
}

export interface PaymentVerification {
  valid: boolean;
  amount?: number;
  from?: string;
  to?: string;
  error?: string;
}

// =============================================================================
// CORS HELPERS
// =============================================================================

export const CORS_HEADERS = {
  "Access-Control-Allow-Origin": "*",
  "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
  "Access-Control-Allow-Headers": "Content-Type, Authorization",
};

/**
 * Return a JSON response with CORS headers
 */
export function corsResponse(data: unknown, status = 200): NextResponse {
  return NextResponse.json(data, { status, headers: CORS_HEADERS });
}

/**
 * Return an error response with CORS headers
 */
export function corsError(error: string, status: number): NextResponse {
  return NextResponse.json({ success: false, error }, { status, headers: CORS_HEADERS });
}

/**
 * Handle OPTIONS preflight requests
 */
export function handleOptions(): NextResponse {
  return new NextResponse(null, { status: 204, headers: CORS_HEADERS });
}

// =============================================================================
// KV STORAGE HELPERS
// =============================================================================

/**
 * Get a value from KV storage
 */
export async function getKV<T>(key: string): Promise<T | null> {
  try {
    const result = await db.select().from(kv).where(eq(kv.key, key)).limit(1);
    if (!result[0]?.value) return null;
    // Handle both JSON and plain string values
    try {
      return JSON.parse(result[0].value) as T;
    } catch {
      return result[0].value as T;
    }
  } catch (error) {
    console.error(`[getKV] Error fetching ${key}:`, error);
    return null;
  }
}

/**
 * Set a value in KV storage (upsert)
 */
export async function setKV(key: string, value: unknown): Promise<boolean> {
  try {
    const stringValue = typeof value === "string" ? value : JSON.stringify(value);
    await db.insert(kv).values({ key, value: stringValue }).onConflictDoUpdate({
      target: kv.key,
      set: { value: stringValue },
    });
    return true;
  } catch (error) {
    console.error(`[setKV] Error storing ${key}:`, error);
    return false;
  }
}

/**
 * Delete a value from KV storage
 */
export async function deleteKV(key: string): Promise<boolean> {
  try {
    await db.delete(kv).where(eq(kv.key, key));
    return true;
  } catch (error) {
    console.error(`[deleteKV] Error deleting ${key}:`, error);
    return false;
  }
}

// =============================================================================
// MEMBER REGISTRY HELPERS
// =============================================================================

/**
 * Get the member registry with proper defaults
 */
export async function getMemberRegistry(): Promise<MemberRegistry> {
  const registry = await getKV<MemberRegistry>(MEMBER_REGISTRY_KEY);
  return registry || {
    members: [],
    nextMemberId: 1,
    lastUpdated: Date.now(),
  };
}

/**
 * Save the member registry
 */
export async function saveMemberRegistry(registry: MemberRegistry): Promise<boolean> {
  registry.lastUpdated = Date.now();
  return setKV(MEMBER_REGISTRY_KEY, registry);
}

/**
 * Find a member by address (case-insensitive)
 */
export function findMemberByAddress(registry: MemberRegistry, address: string): MemberEntry | undefined {
  const lowerAddress = address.toLowerCase();
  return registry.members.find(m => m.address?.toLowerCase() === lowerAddress);
}

/**
 * Find a member by agent ID
 */
export function findMemberByAgentId(registry: MemberRegistry, agentId: string): MemberEntry | undefined {
  return registry.members.find(m => m.agentId === agentId);
}

/**
 * Find a member by FID
 */
export function findMemberByFid(registry: MemberRegistry, fid: number): MemberEntry | undefined {
  return registry.members.find(m => m.fid === fid);
}

// =============================================================================
// AGENT AUTHENTICATION
// =============================================================================

/**
 * Authenticate an agent via Bearer token
 *
 * Lookup chain:
 * 1. Extract API key from Authorization header
 * 2. api-key-lookup:{apiKey} → agentId
 * 3. api-agent:{agentId} → AgentRecord
 * 4. Check isActive (missing = active, only reject if === false)
 *
 * Returns AuthResult on success, NextResponse error on failure
 */
export async function authenticateAgent(
  request: NextRequest
): Promise<AuthResult | NextResponse> {
  const authHeader = request.headers.get("Authorization") || request.headers.get("authorization");

  if (!authHeader?.startsWith("Bearer ")) {
    return corsError("Missing or invalid Authorization header", 401);
  }

  const apiKey = authHeader.slice(7).trim();
  if (!apiKey) {
    return corsError("Empty API key", 401);
  }

  // Look up agentId from API key
  const agentId = await getKV<string>(`api-key-lookup:${apiKey}`);
  if (!agentId) {
    return corsError("Invalid API key", 401);
  }

  // Get agent record
  const agent = await getKV<RegisteredAgent>(`${AGENT_KEY_PREFIX}${agentId}`);
  if (!agent) {
    return corsError("Agent record not found", 401);
  }

  // Check if agent is deactivated
  // IMPORTANT: Only reject if isActive === false (explicit deactivation)
  // Missing isActive field means active (backward compatibility)
  if (agent.isActive === false) {
    return corsError("Agent account is deactivated", 403);
  }

  // Update last active timestamp (fire and forget).
  // Also migrate legacy records: if the full apiKey is stored on the record but
  // no apiKeyPrefix exists yet, compute the prefix and strip the full key.
  // This gradually migrates pre-C20 admin-created records to prefix-only storage.
  agent.lastActiveAt = Date.now();
  if (agent.apiKey && !("apiKeyPrefix" in agent)) {
    (agent as RegisteredAgent & { apiKeyPrefix?: string }).apiKeyPrefix =
      `nlk_${agent.apiKey.slice(4, 10)}`;
    delete (agent as unknown as Record<string, unknown>).apiKey;
  }
  setKV(`${AGENT_KEY_PREFIX}${agentId}`, agent).catch(() => {});

  return { agentId, agent };
}

/**
 * Check if auth result is an error response
 */
export function isAuthError(result: AuthResult | NextResponse): result is NextResponse {
  return result instanceof NextResponse;
}

/**
 * Check if an agent has a specific permission
 */
export function hasPermission(agent: RegisteredAgent, permission: AgentPermission): boolean {
  return agent.permissions.includes("admin") || agent.permissions.includes(permission);
}

// =============================================================================
// DUAL AUTH HELPERS (C21)
// =============================================================================

export type CallerType = "bearer" | "farcaster";

/**
 * Unified caller identity after authentication.
 * Bearer path: agentId + agent record available.
 * Farcaster/web path: fid and/or address from request body.
 */
export interface AuthenticatedCaller {
  type: CallerType;
  // Bearer path fields
  agentId?: string;
  agent?: RegisteredAgent;
  // Farcaster/web path fields
  fid?: number;
  address?: string;
}

/**
 * Unified auth: try Bearer first, then Farcaster/web identity from body.
 *
 * Path A — Bearer token (agents + web members who already have a key):
 *   Authorization: Bearer <nlk_key>
 *   If a Bearer header is present but invalid, return 401 immediately.
 *   Do NOT fall through to Path B.
 *
 * Path B — Farcaster frame / web user:
 *   Body: { fid: number } or { address: "0x..." }
 *   Consistent with all other non-agent routes in this codebase — identity
 *   comes from the client, no server-side Farcaster signer verification.
 *
 * @param request - Incoming request
 * @param body    - Parsed request body (null if not available, e.g. on GET)
 */
export async function authenticateCaller(
  request: NextRequest,
  body: Record<string, unknown> | null
): Promise<AuthenticatedCaller | NextResponse> {
  const authHeader =
    request.headers.get("Authorization") || request.headers.get("authorization");

  if (authHeader?.startsWith("Bearer ")) {
    // Bearer provided — validate it. Hard fail if invalid; do not fall through.
    const result = await authenticateAgent(request);
    if (isAuthError(result)) return result;
    return { type: "bearer", agentId: result.agentId, agent: result.agent };
  }

  // No Bearer header — try Farcaster/web identity from request body.
  const fid = body && typeof body.fid === "number" ? body.fid : undefined;
  const address =
    body && typeof body.address === "string" ? body.address.toLowerCase() : undefined;

  if (!fid && !address) {
    return corsError(
      "Authentication required — sign in via the app or provide a Bearer token.",
      401
    );
  }

  return { type: "farcaster", fid, address };
}

/**
 * Resolve an authenticated caller to a MemberEntry.
 * Registry must already be loaded.
 * Returns null if the caller is not a member.
 */
export function resolveCallerMember(
  caller: AuthenticatedCaller,
  registry: MemberRegistry
): MemberEntry | null {
  if (caller.type === "bearer") {
    let member: MemberEntry | undefined;
    if (caller.agentId) {
      member = findMemberByAgentId(registry, caller.agentId);
    }
    if (!member && caller.agent?.address) {
      member = findMemberByAddress(registry, caller.agent.address.toLowerCase());
    }
    if (!member && caller.agent?.fid) {
      member = findMemberByFid(registry, caller.agent.fid);
    }
    return member ?? null;
  }

  // Farcaster/web path
  let member: MemberEntry | undefined;
  if (caller.fid) {
    member = findMemberByFid(registry, caller.fid);
  }
  if (!member && caller.address) {
    member = findMemberByAddress(registry, caller.address);
  }
  return member ?? null;
}

/**
 * Generate a cryptographically secure random API key
 * Format: [REDACTED-API-KEY]
 */
export function generateApiKey(): string {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  const bytes = new Uint8Array(32);
  crypto.getRandomValues(bytes);
  const segments = [];
  for (let s = 0; s < 4; s++) {
    let segment = "";
    for (let i = 0; i < 8; i++) {
      segment += chars.charAt(bytes[s * 8 + i] % chars.length);
    }
    segments.push(segment);
  }
  return `nl_${segments.join("_")}`;
}

// =============================================================================
// ADMIN AUTHENTICATION
// =============================================================================

/**
 * Authenticate admin via environment variable key
 * Checks ADMIN_KEY or ADMIN_API_KEY from environment
 */
export function authenticateAdmin(request: NextRequest): boolean {
  const authHeader = request.headers.get("Authorization") || request.headers.get("authorization");

  if (!authHeader?.startsWith("Bearer ")) {
    return false;
  }

  const providedKey = authHeader.slice(7).trim();
  if (!providedKey) {
    return false;
  }

  // Check against environment variables
  const adminKey = process.env.ADMIN_KEY || process.env.ADMIN_API_KEY || process.env.ADMIN_SECRET;

  return adminKey ? providedKey === adminKey : false;
}

// =============================================================================
// USDC PAYMENT VERIFICATION
// =============================================================================

/**
 * Get the Base RPC URL from environment or use public default
 */
function getBaseRpcUrl(): string {
  return process.env.BASE_RPC_URL || "[REDACTED-RPC-URL]";
}

/**
 * Transaction log structure from RPC response
 */
interface TransactionLog {
  address: string;
  topics: string[];
  data: string;
}

/**
 * Transaction receipt structure from RPC response
 */
interface TransactionReceipt {
  status: string;
  logs: TransactionLog[];
  from: string;
  to: string;
  blockNumber: string;
}

/**
 * Verify a USDC payment on Base chain
 *
 * @param txHash - Transaction hash to verify
 * @param expectedAmount - Expected USDC amount (not wei, actual USDC)
 * @param expectedFrom - Optional: Expected sender address
 * @param expectedTo - Expected recipient address (defaults to TREASURY_ADDRESS)
 * @returns PaymentVerification result
 */
export async function verifyUsdcPayment(
  txHash: string,
  expectedAmount: number,
  expectedFrom?: string,
  expectedTo: string = TREASURY_ADDRESS
): Promise<PaymentVerification> {
  try {
    // 1. Check replay protection
    const existingTx = await getKV<string>(`purchase-tx:${txHash}`) ||
                       await getKV<boolean>(`membership-tx:${txHash}`);
    if (existingTx) {
      return { valid: false, error: "Transaction has already been used for a purchase" };
    }

    // 2. Fetch transaction receipt via RPC
    const rpcUrl = getBaseRpcUrl();
    const response = await fetch(rpcUrl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        jsonrpc: "2.0",
        method: "eth_getTransactionReceipt",
        params: [txHash],
        id: 1,
      }),
    });

    const rpcData = await response.json();

    if (!rpcData.result) {
      return { valid: false, error: "Transaction not found or not yet confirmed" };
    }

    const receipt: TransactionReceipt = rpcData.result;

    // 3. Verify transaction succeeded
    if (receipt.status !== "0x1") {
      return { valid: false, error: "Transaction failed on-chain" };
    }

    // 4. Find USDC Transfer log
    const usdcTransferLog = receipt.logs?.find((log: TransactionLog) => {
      const isUSDC = log.address.toLowerCase() === USDC_CONTRACT.toLowerCase();
      const isTransfer = log.topics[0] === TRANSFER_TOPIC;
      return isUSDC && isTransfer;
    });

    if (!usdcTransferLog) {
      return { valid: false, error: "No USDC transfer found in transaction" };
    }

    // 5. Decode from/to/amount from log
    // topics[1] = from (padded to 32 bytes)
    // topics[2] = to (padded to 32 bytes)
    // data = amount (uint256)
    const fromAddress = "0x" + usdcTransferLog.topics[1].slice(26);
    const toAddress = "0x" + usdcTransferLog.topics[2].slice(26);
    const amountRaw = BigInt(usdcTransferLog.data);
    const amountUSDC = Number(amountRaw) / 1e6; // USDC has 6 decimals

    // 6. Verify recipient matches expected
    if (toAddress.toLowerCase() !== expectedTo.toLowerCase()) {
      return {
        valid: false,
        error: `Payment sent to wrong address. Expected ${expectedTo}, got ${toAddress}`,
        from: fromAddress,
        to: toAddress,
        amount: amountUSDC
      };
    }

    // 7. Verify amount is sufficient
    if (amountUSDC < expectedAmount) {
      return {
        valid: false,
        error: `Insufficient payment. Sent ${amountUSDC} USDC, required ${expectedAmount} USDC`,
        from: fromAddress,
        to: toAddress,
        amount: amountUSDC
      };
    }

    // 8. Verify sender if specified
    if (expectedFrom && fromAddress.toLowerCase() !== expectedFrom.toLowerCase()) {
      return {
        valid: false,
        error: `Payment from wrong address. Expected ${expectedFrom}, got ${fromAddress}`,
        from: fromAddress,
        to: toAddress,
        amount: amountUSDC
      };
    }

    return {
      valid: true,
      from: fromAddress,
      to: toAddress,
      amount: amountUSDC
    };

  } catch (error) {
    console.error("[verifyUsdcPayment] Error:", error);
    return { valid: false, error: "Failed to verify transaction" };
  }
}

/**
 * Mark a transaction as used for replay protection
 *
 * @param txHash - Transaction hash
 * @param purchaseType - Type of purchase (e.g., "membership", "storage-pass", "stack-unlock")
 */
export async function markTxUsed(txHash: string, purchaseType: string): Promise<void> {
  await setKV(`purchase-tx:${txHash}`, purchaseType);
}

/**
 * Check if a transaction has already been used
 */
export async function isTxUsed(txHash: string): Promise<boolean> {
  const existingTx = await getKV<string>(`purchase-tx:${txHash}`) ||
                     await getKV<boolean>(`membership-tx:${txHash}`);
  return !!existingTx;
}

// =============================================================================
// LEGACY EXPORTS (for backward compatibility with existing routes)
// =============================================================================

/**
 * @deprecated Use authenticateAgent instead
 */
export async function validateApiKey(
  request: NextRequest,
  getKVFn: <T>(key: string) => Promise<T | null>,
  setKVFn: (key: string, value: unknown) => Promise<boolean>
): Promise<RegisteredAgent | null> {
  const authHeader = request.headers.get("authorization");
  if (!authHeader?.startsWith("Bearer ")) return null;

  const apiKey = authHeader.slice(7).trim();
  if (!apiKey) return null;

  const agentId = await getKVFn<string>(`api-key-lookup:${apiKey}`);
  if (!agentId) return null;

  const agent = await getKVFn<RegisteredAgent>(`${AGENT_KEY_PREFIX}${agentId}`);
  // IMPORTANT: Only reject if isActive === false (backward compat)
  if (!agent || agent.isActive === false) return null;

  agent.lastActiveAt = Date.now();
  setKVFn(`${AGENT_KEY_PREFIX}${agentId}`, agent).catch(() => {});

  return agent;
}

/**
 * @deprecated Use corsError instead
 */
export function unauthorizedResponse(message = "Invalid or missing API key") {
  return new Response(
    JSON.stringify({ success: false, error: message }),
    { status: 401, headers: { "Content-Type": "application/json" } }
  );
}

/**
 * @deprecated Use corsError instead
 */
export function forbiddenResponse(message = "Insufficient permissions") {
  return new Response(
    JSON.stringify({ success: false, error: message }),
    { status: 403, headers: { "Content-Type": "application/json" } }
  );
}

// =============================================================================
// ATOMIC DISCOVERY INDEX HELPERS
// =============================================================================

/**
 * Atomically add an entry to the discovery index.
 *
 * Thin re-export of addDiscoveryEntry from @/lib/discovery-ops — the single
 * source of truth for all discovery index mutations.  Both the full index blob
 * and the per-entry fast-lookup key (discovery:{contentKey}) are written in
 * the same PostgreSQL transaction.
 *
 * @param entry   - The discovery entry to add
 * @param prepend - If true (default), insert at front. If false, append to end.
 */
export { addDiscoveryEntry as addEntryAtomically } from "@/lib/discovery-ops";

// =============================================================================
// ATOMIC MEMBER REGISTRY HELPERS
// =============================================================================

/**
 * Atomically add a member to the registry with FOR UPDATE row locking.
 *
 * RACE CONDITION FIX: Uses PostgreSQL transaction with row-level locking
 * to prevent two simultaneous registrations from getting the same member ID.
 */
export async function addMemberAtomically(
  buildEntry: (memberId: number) => MemberEntry
): Promise<{
  success: boolean;
  isDuplicate: boolean;
  member?: MemberEntry;
  error?: string;
}> {
  const maxRetries = 3;
  const retryDelayMs = 100;

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const result = await connection.begin(async (tx) => {
        // Step 1: Lock the row for update
        const rows = await tx`
          SELECT value FROM kv
          WHERE key = ${MEMBER_REGISTRY_KEY}
          FOR UPDATE
        `;

        // Step 2: Parse current registry
        let registry: MemberRegistry = {
          members: [],
          nextMemberId: 1,
          lastUpdated: Date.now(),
        };
        if (rows[0]?.value) {
          try {
            registry = JSON.parse(rows[0].value);
          } catch {
            console.error("[addMemberAtomically] Failed to parse existing registry");
          }
        }

        // Step 3: Build the new member entry with guaranteed unique ID
        const memberId = registry.nextMemberId;
        const newMember = buildEntry(memberId);

        // Step 4: Check for duplicate by address or agentId
        const existingByAddress = registry.members.find(
          m => m.address?.toLowerCase() === newMember.address?.toLowerCase()
        );
        const existingByAgent = newMember.agentId
          ? registry.members.find(m => m.agentId === newMember.agentId)
          : undefined;

        if (existingByAddress || existingByAgent) {
          return {
            success: true,
            isDuplicate: true,
            member: existingByAddress || existingByAgent
          };
        }

        // Step 5: Add new member and increment ID
        registry.members.push(newMember);
        registry.nextMemberId = memberId + 1;
        registry.lastUpdated = Date.now();

        const newValue = JSON.stringify(registry);

        // Step 6: Update or insert
        if (rows.length > 0) {
          await tx`
            UPDATE kv SET value = ${newValue}
            WHERE key = ${MEMBER_REGISTRY_KEY}
          `;
        } else {
          await tx`
            INSERT INTO kv (key, value)
            VALUES (${MEMBER_REGISTRY_KEY}, ${newValue})
            ON CONFLICT (key) DO UPDATE SET value = ${newValue}
          `;
        }

        return { success: true, isDuplicate: false, member: newMember };
      });

      return result;
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : String(error);
      console.error(`[addMemberAtomically] Attempt ${attempt}/${maxRetries} failed:`, errMsg);

      if (errMsg.includes("could not obtain lock") || errMsg.includes("deadlock")) {
        if (attempt < maxRetries) {
          await new Promise((resolve) => setTimeout(resolve, retryDelayMs * attempt));
          continue;
        }
      }

      if (attempt === maxRetries) {
        return { success: false, isDuplicate: false, error: errMsg };
      }
    }
  }

  return { success: false, isDuplicate: false, error: "Max retries exceeded" };
}

// =============================================================================
// ATOMIC KV ARRAY OPERATIONS
// =============================================================================

/**
 * Generic atomic array update with FOR UPDATE row locking.
 *
 * @param key - KV key to update
 * @param updateFn - Function that receives current array and returns { updated, result }
 *                   where updated is the new array and result is any value to return
 */
export async function atomicArrayUpdate<T, R>(
  key: string,
  updateFn: (current: T[]) => { updated: T[]; result: R } | { abort: true; result: R }
): Promise<{ success: boolean; result?: R; error?: string }> {
  const maxRetries = 3;
  const retryDelayMs = 100;

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const txResult = await connection.begin(async (tx) => {
        // Step 1: Lock the row for update
        const rows = await tx`
          SELECT value FROM kv
          WHERE key = ${key}
          FOR UPDATE
        `;

        // Step 2: Parse current array
        let current: T[] = [];
        if (rows[0]?.value) {
          try {
            current = JSON.parse(rows[0].value);
          } catch {
            console.error(`[atomicArrayUpdate] Failed to parse ${key}`);
          }
        }

        // Step 3: Run the update function
        const fnResult = updateFn(current);

        // Check if operation should abort (e.g., validation failed)
        if ('abort' in fnResult && fnResult.abort) {
          return { success: true, result: fnResult.result };
        }

        // Type guard: at this point we know it has 'updated'
        const updateResult = fnResult as { updated: T[]; result: R };

        // Step 4: Save the updated array
        const newValue = JSON.stringify(updateResult.updated);

        if (rows.length > 0) {
          await tx`
            UPDATE kv SET value = ${newValue}
            WHERE key = ${key}
          `;
        } else {
          await tx`
            INSERT INTO kv (key, value)
            VALUES (${key}, ${newValue})
            ON CONFLICT (key) DO UPDATE SET value = ${newValue}
          `;
        }

        return { success: true, result: updateResult.result };
      });

      return txResult;
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : String(error);
      console.error(`[atomicArrayUpdate] Attempt ${attempt}/${maxRetries} failed:`, errMsg);

      if (errMsg.includes("could not obtain lock") || errMsg.includes("deadlock")) {
        if (attempt < maxRetries) {
          await new Promise((resolve) => setTimeout(resolve, retryDelayMs * attempt));
          continue;
        }
      }

      if (attempt === maxRetries) {
        return { success: false, error: errMsg };
      }
    }
  }

  return { success: false, error: "Max retries exceeded" };
}

// =============================================================================
// ATOMIC KV UPDATE (SINGLE KEY)
// =============================================================================

/**
 * Generic atomic KV update with FOR UPDATE row locking.
 *
 * RACE CONDITION FIX: Uses PostgreSQL transaction with row-level locking
 * to prevent concurrent read-check-write operations from racing.
 *
 * @param key - KV key to update
 * @param updateFn - Function that receives current value and returns { updated, result } or { abort, result }
 * @returns Result with success status and the operation result
 */
export async function atomicKVUpdate<T, R>(
  key: string,
  updateFn: (current: T | null) => { updated: T; result: R } | { abort: true; result: R }
): Promise<{ success: boolean; result?: R; error?: string }> {
  const maxRetries = 3;
  const retryDelayMs = 100;

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const txResult = await connection.begin(async (tx) => {
        // Step 1: Lock the row for update (or create if not exists)
        const rows = await tx`
          SELECT value FROM kv
          WHERE key = ${key}
          FOR UPDATE
        `;

        // Step 2: Parse current value
        let current: T | null = null;
        if (rows[0]?.value) {
          try {
            current = JSON.parse(rows[0].value);
          } catch {
            console.error(`[atomicKVUpdate] Failed to parse ${key}`);
          }
        }

        // Step 3: Run the update function
        const fnResult = updateFn(current);

        // Check if operation should abort (e.g., validation failed)
        if ('abort' in fnResult && fnResult.abort) {
          return { success: true, result: fnResult.result };
        }

        // Type guard: at this point we know it has 'updated'
        const updateResult = fnResult as { updated: T; result: R };

        // Step 4: Save the updated value
        const newValue = JSON.stringify(updateResult.updated);

        if (rows.length > 0) {
          await tx`
            UPDATE kv SET value = ${newValue}
            WHERE key = ${key}
          `;
        } else {
          await tx`
            INSERT INTO kv (key, value)
            VALUES (${key}, ${newValue})
            ON CONFLICT (key) DO UPDATE SET value = ${newValue}
          `;
        }

        return { success: true, result: updateResult.result };
      });

      return txResult;
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : String(error);
      console.error(`[atomicKVUpdate] Attempt ${attempt}/${maxRetries} failed:`, errMsg);

      if (errMsg.includes("could not obtain lock") || errMsg.includes("deadlock")) {
        if (attempt < maxRetries) {
          await new Promise((resolve) => setTimeout(resolve, retryDelayMs * attempt));
          continue;
        }
      }

      if (attempt === maxRetries) {
        return { success: false, error: errMsg };
      }
    }
  }

  return { success: false, error: "Max retries exceeded" };
}

// =============================================================================
// ATOMIC MEMBER REGISTRY UPDATE
// =============================================================================

/**
 * Atomically update a member in the registry with FOR UPDATE row locking.
 *
 * RACE CONDITION FIX: Uses PostgreSQL transaction with row-level locking
 * to prevent concurrent updates from clobbering each other.
 *
 * @param findMember - Function to find the target member in the registry
 * @param updateMember - Function to update the found member (mutates in place)
 * @returns Result with success status and the updated member
 */
export async function updateMemberAtomically<R>(
  findMember: (registry: MemberRegistry) => MemberEntry | undefined,
  updateMember: (member: MemberEntry, registry: MemberRegistry) => R
): Promise<{ success: boolean; member?: MemberEntry; result?: R; error?: string }> {
  const maxRetries = 3;
  const retryDelayMs = 100;

  for (let attempt = 1; attempt <= maxRetries; attempt++) {
    try {
      const txResult = await connection.begin(async (tx) => {
        // Step 1: Lock the row for update
        const rows = await tx`
          SELECT value FROM kv
          WHERE key = ${MEMBER_REGISTRY_KEY}
          FOR UPDATE
        `;

        // Step 2: Parse current registry
        let registry: MemberRegistry = {
          members: [],
          nextMemberId: 1,
          lastUpdated: Date.now(),
        };
        if (rows[0]?.value) {
          try {
            registry = JSON.parse(rows[0].value);
          } catch {
            console.error("[updateMemberAtomically] Failed to parse existing registry");
          }
        }

        // Step 3: Find the target member
        const member = findMember(registry);
        if (!member) {
          return { success: false, member: undefined, result: undefined, error: "Member not found" };
        }

        // Step 4: Apply the update (mutates member in place)
        const result = updateMember(member, registry);

        // Step 5: Update timestamp and save
        registry.lastUpdated = Date.now();
        const newValue = JSON.stringify(registry);

        if (rows.length > 0) {
          await tx`
            UPDATE kv SET value = ${newValue}
            WHERE key = ${MEMBER_REGISTRY_KEY}
          `;
        } else {
          await tx`
            INSERT INTO kv (key, value)
            VALUES (${MEMBER_REGISTRY_KEY}, ${newValue})
            ON CONFLICT (key) DO UPDATE SET value = ${newValue}
          `;
        }

        return { success: true, member, result };
      });

      return txResult;
    } catch (error) {
      const errMsg = error instanceof Error ? error.message : String(error);
      console.error(`[updateMemberAtomically] Attempt ${attempt}/${maxRetries} failed:`, errMsg);

      if (errMsg.includes("could not obtain lock") || errMsg.includes("deadlock")) {
        if (attempt < maxRetries) {
          await new Promise((resolve) => setTimeout(resolve, retryDelayMs * attempt));
          continue;
        }
      }

      if (attempt === maxRetries) {
        return { success: false, error: errMsg };
      }
    }
  }

  return { success: false, error: "Max retries exceeded" };
}

// =============================================================================
// ENS SUBNAME MINTING (SHARED)
// =============================================================================

// NameStone API configuration
const NAMESTONE_API_URL = "https://namestone.com/api/public_v1/set-name";
const NAMESTONE_GET_URL = "https://namestone.com/api/public_v1/get-names";
const NAMESTONE_API_KEY = process.env.NAMESTONE_API_KEY || "";
const PARENT_DOMAIN = "netlibrary.eth";

/**
 * Check if an ENS subname already exists via NameStone single-name lookup
 */
export async function checkEnsSubnameExists(
  memberId: number
): Promise<{ exists: boolean; address?: string; error?: string }> {
  if (!NAMESTONE_API_KEY) {
    return { exists: false, error: "NAMESTONE_API_KEY not configured" };
  }

  try {
    // Use single-name lookup instead of fetching all names
    const url = new URL(NAMESTONE_GET_URL);
    url.searchParams.set("domain", PARENT_DOMAIN);
    url.searchParams.set("name", String(memberId));

    const response = await fetch(url.toString(), {
      method: "GET",
      headers: {
        Authorization: NAMESTONE_API_KEY,
      },
    });

    if (!response.ok) {
      console.error("[checkEnsSubnameExists] NameStone GET error:", response.status);
      return { exists: false, error: `NameStone error: ${response.status}` };
    }

    const names = await response.json() as Array<{
      name: string;
      address: string;
      domain: string;
    }>;

    // With single-name lookup, array will have 0 or 1 entries
    if (names.length > 0 && names[0].name === String(memberId)) {
      return { exists: true, address: names[0].address };
    }

    return { exists: false };
  } catch (error) {
    console.error("[checkEnsSubnameExists] Error:", error);
    return { exists: false, error: "Failed to check ENS subname" };
  }
}

/**
 * Mint ENS subname via NameStone API
 *
 * @param memberId - The member ID to use as the subdomain
 * @param walletAddress - The wallet address to resolve the subname to
 * @param isAgent - Whether this is an agent (affects description text)
 */
export async function mintEnsSubname(
  memberId: number,
  walletAddress: string,
  isAgent: boolean = false
): Promise<{ success: boolean; error?: string }> {
  if (!NAMESTONE_API_KEY) {
    console.error("[mintEnsSubname] NAMESTONE_API_KEY not configured");
    return { success: false, error: "ENS minting not configured" };
  }

  try {
    const response = await fetch(NAMESTONE_API_URL, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: NAMESTONE_API_KEY,
      },
      body: JSON.stringify({
        domain: PARENT_DOMAIN,
        name: String(memberId),
        address: walletAddress,
        text_records: {
          description: `Net Library Member #${memberId}${isAgent ? " (Agent)" : ""}`,
          "com.farcaster": "Net Library",
        },
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error("[mintEnsSubname] NameStone API error:", errorText);
      return { success: false, error: `NameStone error: ${response.status}` };
    }

    console.log(`[mintEnsSubname] Successfully minted ${memberId}.${PARENT_DOMAIN}`);
    return { success: true };
  } catch (error) {
    console.error("[mintEnsSubname] NameStone API call failed:", error);
    return { success: false, error: "Failed to mint ENS subname" };
  }
}

// =============================================================================
// ERC-8004 BASE IDENTITY REGISTRY VERIFICATION
// =============================================================================

// ERC-8004 Base Identity Registry contract
export const ERC8004_REGISTRY = "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432";

// Cache duration for ERC-8004 verification (1 hour)
const ERC8004_CACHE_DURATION_MS = 60 * 60 * 1000;

export interface Erc8004VerificationResult {
  verified: boolean;
  tokenId?: number;
  error?: string;
}

/**
 * Verify if an address is registered on the ERC-8004 Base Identity Registry.
 *
 * Verification flow:
 * 1. If tokenId is provided, call ownerOf(tokenId) and compare to address
 * 2. If tokenId is not provided, call balanceOf(address) to check if they have any token
 *
 * Results are cached in KV for 1 hour.
 *
 * @param address - Wallet address to verify
 * @param tokenId - Optional token ID (if agent provided one)
 * @returns Verification result with verified status and optional tokenId
 */
export async function verifyErc8004(
  address: string,
  tokenId?: number
): Promise<Erc8004VerificationResult> {
  const normalizedAddress = address.toLowerCase();
  const cacheKey = `erc8004-status:${normalizedAddress}`;

  // Check cache first
  const cached = await getKV<{
    verified: boolean;
    tokenId?: number;
    checkedAt: number;
  }>(cacheKey);

  if (cached && Date.now() - cached.checkedAt < ERC8004_CACHE_DURATION_MS) {
    // Cache is still valid
    return {
      verified: cached.verified,
      tokenId: cached.tokenId,
    };
  }

  try {
    const rpcUrl = process.env.BASE_RPC_URL || "[REDACTED-RPC-URL]";

    if (tokenId !== undefined) {
      // Verify by checking ownerOf(tokenId)
      // ownerOf selector: 0x6352211e
      // ABI encode tokenId as uint256 (32 bytes, padded)
      const tokenIdHex = tokenId.toString(16).padStart(64, "0");
      const callData = `0x6352211e${tokenIdHex}`;

      const response = await fetch(rpcUrl, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          jsonrpc: "2.0",
          method: "eth_call",
          params: [
            { to: ERC8004_REGISTRY, data: callData },
            "latest"
          ],
          id: 1,
        }),
      });

      const rpcData = await response.json();

      if (rpcData.error) {
        // Token doesn't exist or other error
        console.error("[verifyErc8004] RPC error:", rpcData.error);
        const result = { verified: false, checkedAt: Date.now() };
        await setKV(cacheKey, result);
        return { verified: false };
      }

      // Result is an address padded to 32 bytes
      const ownerHex = rpcData.result;
      if (!ownerHex || ownerHex === "0x" || ownerHex.length < 42) {
        // No owner found
        const result = { verified: false, checkedAt: Date.now() };
        await setKV(cacheKey, result);
        return { verified: false };
      }

      // Extract address from padded result (last 40 chars)
      const ownerAddress = "0x" + ownerHex.slice(-40);

      if (ownerAddress.toLowerCase() === normalizedAddress) {
        // Verified! Owner matches
        const result = { verified: true, tokenId, checkedAt: Date.now() };
        await setKV(cacheKey, result);
        return { verified: true, tokenId };
      } else {
        // Token exists but owned by someone else
        const result = { verified: false, checkedAt: Date.now() };
        await setKV(cacheKey, result);
        return { verified: false, error: "Token is owned by a different address" };
      }
    } else {
      // No tokenId provided - use balanceOf to check if they have any token
      // balanceOf selector: 0x70a08231
      // ABI encode address (padded to 32 bytes)
      const addressPadded = normalizedAddress.slice(2).padStart(64, "0");
      const callData = `0x70a08231${addressPadded}`;

      const response = await fetch(rpcUrl, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          jsonrpc: "2.0",
          method: "eth_call",
          params: [
            { to: ERC8004_REGISTRY, data: callData },
            "latest"
          ],
          id: 1,
        }),
      });

      const rpcData = await response.json();

      if (rpcData.error) {
        console.error("[verifyErc8004] RPC error:", rpcData.error);
        const result = { verified: false, checkedAt: Date.now() };
        await setKV(cacheKey, result);
        return { verified: false };
      }

      // Result is uint256 balance
      const balanceHex = rpcData.result;
      const balance = parseInt(balanceHex, 16);

      if (balance > 0) {
        // Has at least one token - verified but no specific tokenId
        const result = { verified: true, checkedAt: Date.now() };
        await setKV(cacheKey, result);
        return { verified: true };
      } else {
        // No tokens
        const result = { verified: false, checkedAt: Date.now() };
        await setKV(cacheKey, result);
        return { verified: false };
      }
    }
  } catch (error) {
    console.error("[verifyErc8004] Error:", error);
    // On error, return unverified but don't cache (so we retry next time)
    return { verified: false, error: "Failed to verify ERC-8004 status" };
  }
}

/**
 * Check if the cached ERC-8004 verification is stale (>1 hour old)
 */
export function isErc8004CacheStale(checkedAt?: number): boolean {
  if (!checkedAt) return true;
  return Date.now() - checkedAt > ERC8004_CACHE_DURATION_MS;
}

/**
 * Update a member's ERC-8004 verification status in the registry.
 * Uses atomic update to prevent race conditions.
 *
 * @param address - Member's wallet address
 * @param verification - Verification result to store
 */
export async function updateMemberErc8004Status(
  address: string,
  verification: Erc8004VerificationResult
): Promise<boolean> {
  const result = await updateMemberAtomically(
    (registry) => findMemberByAddress(registry, address),
    (member) => {
      member.erc8004Verified = verification.verified;
      if (verification.tokenId !== undefined) {
        member.erc8004TokenId = verification.tokenId;
      }
      member.erc8004CheckedAt = Date.now();
      return true;
    }
  );

  return result.success;
}
src/lib/api-auth.ts
/**
 * API Auth - Backward Compatibility Re-exports
 *
 * This file re-exports from agent-auth.ts for backward compatibility
 * with existing code that imports from @/lib/api-auth.
 *
 * New code should import directly from @/lib/agent-auth.
 */

// Re-export everything from agent-auth for backward compatibility
export {
  // Types
  type RegisteredAgent,
  type AgentPermission,
  type MemberEntry,
  type MemberRegistry,
  type AuthResult,
  type PaymentVerification,

  // Constants
  AGENTS_REGISTRY_KEY,
  AGENT_KEY_PREFIX,
  MEMBER_REGISTRY_KEY,
  USDC_CONTRACT,
  TREASURY_ADDRESS,
  TRANSFER_TOPIC,
  PRICING,
  CORS_HEADERS,

  // KV helpers
  getKV,
  setKV,
  deleteKV,

  // CORS helpers
  corsResponse,
  corsError,
  handleOptions,

  // Auth helpers
  authenticateAgent,
  isAuthError,
  hasPermission,
  generateApiKey,
  authenticateAdmin,
  validateApiKey, // Legacy

  // Member registry helpers
  getMemberRegistry,
  saveMemberRegistry,
  findMemberByAddress,
  findMemberByAgentId,
  findMemberByFid,

  // Payment helpers
  verifyUsdcPayment,
  markTxUsed,
  isTxUsed,

  // Legacy response helpers
  unauthorizedResponse,
  forbiddenResponse,
} from "@/lib/agent-auth";
src/lib/app-mode.ts
"use client";

/**
 * App Mode Detection & Tri-Mode Utilities
 *
 * Enables Net Library to work as:
 * 1. Farcaster Mini App - accessed via Warpcast, uses FID for identity
 * 2. Base App - accessed via Coinbase Wallet, uses wallet for identity
 * 3. Web - accessed directly via browser, uses WalletConnect for identity
 */

import { atom, useAtomValue, useSetAtom } from "jotai";
import { isCoinbaseWalletUA } from "@/lib/ua-utils";

// App mode types - now includes "web" for direct browser access
export type AppMode = "farcaster" | "base-app" | "web" | "detecting";

// Atom to store detected app mode
export const appModeAtom = atom<AppMode>("detecting");

// Atom to track if we're in a Farcaster frame context
export const isFarcasterFrameAtom = atom<boolean>(false);

/**
 * Detect if we're running inside a Farcaster frame/mini app
 *
 * Checks for:
 * - window.parent !== window (in iframe)
 * - Farcaster-specific context signals
 * - URL parameters that indicate frame context
 */
export function detectFarcasterFrame(): boolean {
  if (typeof window === "undefined") return false;

  try {
    // Check if we're in an iframe (Farcaster frames run in iframes)
    const inIframe = window.parent !== window;

    // Check for Farcaster-specific URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    const hasFarcasterParams = urlParams.has("fc_action") ||
                                urlParams.has("fid") ||
                                urlParams.has("frame");

    // Check for Farcaster user agent hints
    const userAgent = navigator.userAgent.toLowerCase();
    const isFarcasterClient = userAgent.includes("warpcast") ||
                              userAgent.includes("farcaster");

    // IMPORTANT: Only consider it a Farcaster frame if we're ACTUALLY in an iframe
    // OR we're in the Warpcast client itself. Don't rely on referrer alone because
    // users may open links from Warpcast in their external browser.
    // The referrer check was causing issues where opening in Safari/Chrome from
    // Warpcast would still show "@anon" instead of the Connect button.

    return inIframe || hasFarcasterParams || isFarcasterClient;
  } catch {
    return false;
  }
}

/**
 * Detect if we're running inside Coinbase Wallet's in-app browser
 *
 * Checks for:
 * - Coinbase Wallet user agent
 * - Coinbase Wallet injected provider
 */
export function detectCoinbaseWallet(): boolean {
  if (typeof window === "undefined") return false;

  try {
    const userAgent = navigator.userAgent.toLowerCase();

    // Check for Coinbase Wallet in-app browser via shared UA utility.
    if (isCoinbaseWalletUA(userAgent)) {
      return true;
    }

    // Check for Coinbase Wallet injected provider
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const ethereum = (window as any).ethereum;
    if (ethereum?.isCoinbaseWallet || ethereum?.isCoinbaseBrowser) {
      return true;
    }

    return false;
  } catch {
    return false;
  }
}

/**
 * Detect the app mode based on environment
 *
 * Priority:
 * 1. Farcaster frame/client → "farcaster"
 * 2. Coinbase Wallet browser → "base-app"
 * 3. Direct browser access → "web"
 */
export function detectAppMode(): AppMode {
  // Server-side: return detecting
  if (typeof window === "undefined") return "detecting";

  // Priority 1: Farcaster
  if (detectFarcasterFrame()) return "farcaster";

  // Priority 2: Coinbase Wallet (Base App)
  if (detectCoinbaseWallet()) return "base-app";

  // Priority 3: Direct browser access (Web)
  return "web";
}

/**
 * Hook to get current app mode
 */
export function useAppMode() {
  return useAtomValue(appModeAtom);
}

/**
 * Hook to check if running in Farcaster frame
 */
export function useIsFarcasterFrame() {
  return useAtomValue(isFarcasterFrameAtom);
}

/**
 * Hook to set app mode (used during initialization)
 */
export function useSetAppMode() {
  const setMode = useSetAtom(appModeAtom);
  const setIsFarcasterFrame = useSetAtom(isFarcasterFrameAtom);

  return (mode: AppMode) => {
    setMode(mode);
    setIsFarcasterFrame(mode === "farcaster");
  };
}

/**
 * Wrapper for Farcaster SDK actions that gracefully degrades in Base App mode
 */
export async function safeComposeCast(options: {
  text: string;
  embeds?: string[];
  channelKey?: string;
}): Promise<boolean> {
  const isFarcaster = detectFarcasterFrame();

  if (isFarcaster) {
    try {
      const sdk = (await import("@farcaster/miniapp-sdk")).default;

      // Validate embeds before sending - Farcaster has limits
      const validatedEmbeds = options.embeds?.filter(embed => {
        if (!embed || typeof embed !== "string") return false;
        // Check URL is valid
        try {
          new URL(embed);
          return true;
        } catch {
          console.warn("[safeComposeCast] Invalid embed URL:", embed);
          return false;
        }
      });

      // Log what we're sending for debugging
      console.log("[safeComposeCast] Composing cast:", {
        textLength: options.text.length,
        embedCount: validatedEmbeds?.length || 0,
        embedUrls: validatedEmbeds?.map(e => e.substring(0, 100) + (e.length > 100 ? "..." : "")),
      });

      // Type assertion needed for embeds as SDK expects specific tuple type
      await sdk.actions.composeCast({
        text: options.text,
        embeds: validatedEmbeds as [] | [string] | [string, string] | undefined,
        channelKey: options.channelKey,
      });
      return true;
    } catch (err) {
      console.error("[safeComposeCast] Farcaster SDK error:", err);
      // Re-throw so caller can handle - don't silently fail in Farcaster context
      throw err;
    }
  }

  // Fallback for non-Farcaster: Use native share or copy to clipboard
  const shareText = options.text + (options.embeds?.length ? `\n\n${options.embeds.join("\n")}` : "");

  if (navigator.share) {
    try {
      await navigator.share({
        text: shareText,
        url: options.embeds?.[0],
      });
      return true;
    } catch {
      // User cancelled or share failed
    }
  }

  // Final fallback: copy to clipboard
  try {
    await navigator.clipboard.writeText(shareText);
    alert("Copied to clipboard!");
    return true;
  } catch {
    return false;
  }
}

/**
 * Detect if we're running on a desktop browser (not a mobile app context)
 *
 * Returns true if:
 * - Not in Farcaster frame
 * - Not on a mobile device (no touch, desktop user agent)
 * - Not in standalone PWA mode
 *
 * This is used to skip welcome/linking popups on desktop since those
 * flows require proper mobile app contexts to work.
 */
export function detectDesktopBrowser(): boolean {
  if (typeof window === "undefined") return false;

  try {
    // If we're in a Farcaster frame, definitely not desktop browser
    if (detectFarcasterFrame()) return false;

    const userAgent = navigator.userAgent;
    const userAgentLower = userAgent.toLowerCase();

    // === iOS DETECTION ===
    // Note: iPad on iOS 13+ reports as Mac, so we also check maxTouchPoints
    const isIOS = /iPhone|iPod/.test(userAgent) ||
                  /iPad/.test(userAgent) ||
                  (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);

    // === ANDROID DETECTION ===
    const isAndroid = /Android/.test(userAgent);

    // === WINDOWS MOBILE/TABLET DETECTION ===
    // Windows Phone (legacy but still out there)
    const isWindowsPhone = /Windows Phone|IEMobile|WPDesktop/.test(userAgent);
    // Windows tablet (Surface, etc.) - has touch and "Touch" in UA
    const isWindowsTablet = /Windows/.test(userAgent) &&
                            /Touch/.test(userAgent) &&
                            navigator.maxTouchPoints > 0;

    // === CHROME OS TABLET DETECTION ===
    // Chromebook tablets report "CrOS" with touch
    const isChromeOSTablet = /CrOS/.test(userAgent) &&
                             navigator.maxTouchPoints > 0 &&
                             window.innerWidth < 1024;

    // === GENERAL MOBILE UA PATTERNS ===
    // Catches various mobile browsers and devices
    const isMobileUA = /webos|blackberry|opera mini|mobile|tablet|silk|kindle|playbook/i.test(userAgent);

    // === MOBILE BROWSER DETECTION ===
    // Samsung Internet (very popular on Android)
    const isSamsungBrowser = /SamsungBrowser/.test(userAgent);
    // UC Browser (popular in Asia)
    const isUCBrowser = /UCBrowser|UCWEB/.test(userAgent);
    // Opera Mobile/Mini
    const isOperaMobile = /OPR.*Mobile|Opera.*Mini|Opera.*Mobi/.test(userAgent);

    // === PWA / STANDALONE MODE ===
    const isStandalone = window.matchMedia("(display-mode: standalone)").matches ||
                         // @ts-expect-error - Safari-specific property
                         window.navigator.standalone === true;

    // === CRYPTO WALLET IN-APP BROWSERS ===
    const isWalletBrowser = userAgentLower.includes("coinbasewallet") ||
                            userAgentLower.includes("coinbase") ||
                            userAgentLower.includes("metamask") ||
                            userAgentLower.includes("metamaskmobile") ||
                            userAgentLower.includes("trust") ||
                            userAgentLower.includes("rainbow") ||
                            userAgentLower.includes("brave") ||
                            userAgentLower.includes("opera") && userAgentLower.includes("opr") ||
                            userAgentLower.includes("phantom") ||
                            userAgentLower.includes("zerion") ||
                            userAgentLower.includes("1inch");

    // === FARCASTER CLIENTS ===
    const isFarcasterClient = userAgentLower.includes("warpcast") ||
                              userAgentLower.includes("farcaster");

    // === TOUCH + SCREEN SIZE HEURISTIC ===
    const hasTouch = "ontouchstart" in window || navigator.maxTouchPoints > 0;
    const isSmallScreen = window.innerWidth < 768;
    const isMediumTouchScreen = hasTouch && window.innerWidth < 1024;

    // === FINAL MOBILE DETERMINATION ===
    const isMobile = isIOS ||
                     isAndroid ||
                     isWindowsPhone ||
                     isWindowsTablet ||
                     isChromeOSTablet ||
                     isMobileUA ||
                     isSamsungBrowser ||
                     isUCBrowser ||
                     isOperaMobile ||
                     isStandalone ||
                     isWalletBrowser ||
                     isFarcasterClient ||
                     (hasTouch && isSmallScreen) ||
                     // Medium screens with touch are likely tablets
                     (isMediumTouchScreen && !(/Windows NT/.test(userAgent) && !/Touch/.test(userAgent)));

    // Desktop = NOT mobile
    return !isMobile;
  } catch {
    return false;
  }
}

/**
 * Trigger haptic feedback if available (Farcaster SDK)
 *
 * @param type - Type of haptic: "light", "medium", "heavy", "success", "warning", "error", "selection"
 */
export async function triggerHaptic(
  type: "light" | "medium" | "heavy" | "success" | "warning" | "error" | "selection" = "medium"
): Promise<void> {
  const isFarcaster = detectFarcasterFrame();

  if (!isFarcaster) return;

  try {
    const sdk = (await import("@farcaster/miniapp-sdk")).default;

    if (type === "selection") {
      sdk.haptics.selectionChanged();
    } else if (type === "success" || type === "warning" || type === "error") {
      sdk.haptics.notificationOccurred(type);
    } else {
      // light, medium, heavy
      sdk.haptics.impactOccurred(type);
    }
  } catch (err) {
    console.error("[triggerHaptic] Haptic feedback error:", err);
  }
}

/**
 * Wrapper for opening URLs that works in both modes
 */
export async function safeOpenUrl(url: string): Promise<void> {
  const isFarcaster = detectFarcasterFrame();

  if (isFarcaster) {
    try {
      const sdk = (await import("@farcaster/miniapp-sdk")).default;
      await sdk.actions.openUrl(url);
      return;
    } catch (err) {
      console.error("[safeOpenUrl] Farcaster SDK error:", err);
      // Fall through to fallback
    }
  }

  // Fallback: standard window.open
  window.open(url, "_blank", "noopener,noreferrer");
}

/**
 * Open URL in external browser (bypasses in-app browser on mobile)
 *
 * This is specifically for cases where we want to ensure the URL opens
 * in the user's default browser, not the Farcaster/Warpcast in-app browser.
 *
 * Uses Farcaster SDK's openUrl with external browser flag on mobile.
 */
export async function openInExternalBrowser(url: string): Promise<void> {
  const isFarcaster = detectFarcasterFrame();

  if (isFarcaster) {
    try {
      const sdk = (await import("@farcaster/miniapp-sdk")).default;
      // Use openUrl - Farcaster SDK handles external browser opening
      // The SDK should prompt user to open in Safari/Chrome on mobile
      await sdk.actions.openUrl(url);
      return;
    } catch (err) {
      console.error("[openInExternalBrowser] Farcaster SDK error:", err);
      // Fall through to fallback
    }
  }

  // For non-Farcaster contexts or as fallback:
  // On iOS, using a special URL scheme or window.open may help
  // But the most reliable cross-platform method is still window.open

  // Try to force external browser on iOS by using a slight delay
  // This sometimes helps bypass in-app browser interception
  if (/iPhone|iPad|iPod/.test(navigator.userAgent)) {
    // Create a temporary link and click it - sometimes works better on iOS
    const link = document.createElement("a");
    link.href = url;
    link.target = "_blank";
    link.rel = "noopener noreferrer";
    // Some iOS browsers respect this attribute for external opening
    link.setAttribute("data-external", "true");
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } else {
    window.open(url, "_blank", "noopener,noreferrer");
  }
}
src/lib/batch-upload-recovery.ts
/**
 * Batch Upload Recovery System
 * Enhanced recovery specifically for EIP-5792 batch transactions
 * Persists batch ID and state for crash recovery
 */

export interface BatchUploadState {
  // File info (stored as base64 for recovery)
  fileName: string;
  fileSize: number;
  fileType: string;
  fileDataBase64?: string; // Only stored if small enough

  // Metadata
  title: string;
  author: string;
  categories: string[];
  coverUrl?: string;

  // Batch transaction info
  batchId?: string;
  storageKey: string;
  storageType: "regular" | "chunked" | "xml";
  totalChunks: number;

  // XML chunk keys (for XML storage)
  xmlChunkKeys?: string[];

  // Wallet info
  walletAddress: string;

  // Status tracking
  status: "preparing" | "waiting-signature" | "processing" | "metadata" | "indexing" | "complete" | "error";
  lastError?: string;

  // Timestamps
  startedAt: number;
  lastUpdatedAt: number;
}

const BATCH_RECOVERY_KEY = "net-library-batch-upload-recovery";

/**
 * Save batch upload state for recovery
 */
export function saveBatchUploadState(state: BatchUploadState): void {
  try {
    localStorage.setItem(BATCH_RECOVERY_KEY, JSON.stringify(state));
  } catch (e) {
    console.error("[batch-recovery] Failed to save state:", e);
  }
}

/**
 * Update batch status
 */
export function updateBatchStatus(
  status: BatchUploadState["status"],
  updates?: Partial<BatchUploadState>
): void {
  try {
    const saved = localStorage.getItem(BATCH_RECOVERY_KEY);
    if (!saved) return;

    const state: BatchUploadState = JSON.parse(saved);
    state.status = status;
    state.lastUpdatedAt = Date.now();

    if (updates) {
      Object.assign(state, updates);
    }

    localStorage.setItem(BATCH_RECOVERY_KEY, JSON.stringify(state));
  } catch (e) {
    console.error("[batch-recovery] Failed to update status:", e);
  }
}

/**
 * Set batch ID when transaction is initiated
 */
export function setBatchId(batchId: string): void {
  try {
    const saved = localStorage.getItem(BATCH_RECOVERY_KEY);
    if (!saved) return;

    const state: BatchUploadState = JSON.parse(saved);
    state.batchId = batchId;
    state.status = "processing";
    state.lastUpdatedAt = Date.now();

    localStorage.setItem(BATCH_RECOVERY_KEY, JSON.stringify(state));
  } catch (e) {
    console.error("[batch-recovery] Failed to set batch ID:", e);
  }
}

/**
 * Get saved batch upload state
 */
export function getBatchUploadState(): BatchUploadState | null {
  try {
    const saved = localStorage.getItem(BATCH_RECOVERY_KEY);
    if (!saved) return null;

    const state: BatchUploadState = JSON.parse(saved);

    // Check if state is stale (older than 24 hours)
    const maxAge = 24 * 60 * 60 * 1000;
    if (Date.now() - state.lastUpdatedAt > maxAge) {
      clearBatchUploadState();
      return null;
    }

    return state;
  } catch (e) {
    console.error("[batch-recovery] Failed to get state:", e);
    return null;
  }
}

/**
 * Check if there's a recoverable batch upload
 */
export function hasRecoverableBatchUpload(walletAddress: string): boolean {
  const state = getBatchUploadState();
  if (!state) return false;

  return (
    state.walletAddress.toLowerCase() === walletAddress.toLowerCase() &&
    state.batchId !== undefined &&
    state.status === "processing"
  );
}

/**
 * Clear batch upload state (on completion or user dismissal)
 */
export function clearBatchUploadState(): void {
  try {
    localStorage.removeItem(BATCH_RECOVERY_KEY);
  } catch (e) {
    console.error("[batch-recovery] Failed to clear state:", e);
  }
}

/**
 * Get human-readable recovery info
 */
export function getBatchRecoveryInfo(state: BatchUploadState): {
  statusText: string;
  timeAgo: string;
  canResume: boolean;
} {
  const statusTexts: Record<BatchUploadState["status"], string> = {
    "preparing": "Preparing upload...",
    "waiting-signature": "Waiting for signature...",
    "processing": "Processing batch transaction...",
    "metadata": "Storing metadata...",
    "indexing": "Updating index...",
    "complete": "Upload complete!",
    "error": state.lastError || "Error occurred",
  };

  const minutesAgo = Math.floor((Date.now() - state.lastUpdatedAt) / (60 * 1000));
  const hoursAgo = Math.floor(minutesAgo / 60);
  const timeAgo = hoursAgo > 0
    ? `${hoursAgo} hour${hoursAgo !== 1 ? "s" : ""} ago`
    : minutesAgo > 0
    ? `${minutesAgo} minute${minutesAgo !== 1 ? "s" : ""} ago`
    : "just now";

  // Can only resume if batch was submitted and is still processing
  const canResume = state.status === "processing" && !!state.batchId;

  return {
    statusText: statusTexts[state.status],
    timeAgo,
    canResume,
  };
}
src/lib/constants.ts
/**
 * Net Library — Shared Application Constants
 */

// =============================================================================
// ERC-8021 BUILDER CODE (Base Attribution)
// =============================================================================

/**
 * Builder Code for Net Library, registered at base.dev.
 * Included in transaction calldata via dataSuffix for onchain attribution.
 *
 * Verify: https://builder-code-checker.vercel.app/
 * Directory: https://base.dev
 */
export const NET_LIBRARY_BUILDER_CODE = "bc_d7041lf9";

/**
 * ERC-8021 dataSuffix encoding for Net Library (Schema 0 — Canonical Registry).
 *
 * Encoding layout:
 *   0b                                = codesLength (11 bytes — length of "bc_d7041lf9")
 *   62635f64373034316c6639            = "bc_d7041lf9" in ASCII hex
 *   00                                = schemaId (0 = canonical registry)
 *   80218021802180218021802180218021  = fixed ERC-8021 marker (16 bytes)
 *
 * The optional: true capability flag means wallets that don't support dataSuffix
 * will process the transaction normally without the attribution data.
 */
export const NET_LIBRARY_DATA_SUFFIX =
  "0x0b62635f64373034316c66390080218021802180218021802180218021" as `0x${string}`;
src/lib/cover-art-cache.ts
import "server-only";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry } from "@/lib/net-protocol";

// Fast cover art lookup by content key
// Reads directly from discovery-index (single source of truth)

const DISCOVERY_KEY = "discovery-index";

export type CoverCacheEntry = {
  coverUrl: string;
  title: string;
  author: string;
  mediaType?: string;
  // Social receipt specific fields
  isSocialReceipt?: boolean;
  socialPlatform?: "farcaster" | "twitter" | "youtube" | "instagram" | "tiktok" | "reddit" | "bluesky" | "threads" | "linkedin" | "paragraph";
  originalUrl?: string;
  socialText?: string;
  socialAuthor?: string;
  socialTimestamp?: string;
};

// In-memory cache to avoid repeated DB calls within same request cycle
// This gets invalidated on each new request since it's module-level
let memoryCache: Map<string, CoverCacheEntry> | null = null;
let memoryCacheTimestamp = 0;
const MEMORY_CACHE_TTL = 5000; // 5 seconds - short TTL for freshness

/**
 * Look up book info by content key - direct database access for server components
 * Reads directly from discovery-index (the single source of truth)
 */
export async function getBookInfoByContentKey(
  contentKey: string
): Promise<CoverCacheEntry | null> {
  try {
    const normalizedKey = contentKey.toLowerCase();
    const now = Date.now();

    // Check in-memory cache first (very fast for multiple lookups in same request)
    if (memoryCache && (now - memoryCacheTimestamp) < MEMORY_CACHE_TTL) {
      const cached = findInCache(memoryCache, normalizedKey);
      if (cached) return cached;
    }

    // Fetch discovery index from DB (single source of truth)
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    if (!result[0]?.value) {
      return null;
    }

    const entries = JSON.parse(result[0].value) as DiscoveryEntry[];

    // Build in-memory cache for fast lookups
    memoryCache = new Map();
    memoryCacheTimestamp = now;

    for (const entry of entries) {
      if (!entry.contentKey) continue;
      const key = entry.contentKey.toLowerCase();
      memoryCache.set(key, {
        coverUrl: entry.coverUrl || "",
        title: entry.title || "Untitled",
        author: entry.author || "Unknown",
        mediaType: entry.mediaType,
        // Social receipt specific fields
        isSocialReceipt: entry.isSocialReceipt,
        socialPlatform: entry.socialPlatform,
        originalUrl: entry.originalUrl,
        socialText: entry.socialText,
        socialAuthor: entry.socialAuthor,
        socialTimestamp: entry.socialTimestamp,
      });
    }

    // Look up the requested key
    return findInCache(memoryCache, normalizedKey);
  } catch (error) {
    console.error("getBookInfoByContentKey error:", error);
    return null;
  }
}

/**
 * Find entry in cache, handling 0x prefix variations
 */
function findInCache(cache: Map<string, CoverCacheEntry>, key: string): CoverCacheEntry | null {
  // Try exact match first
  let data = cache.get(key);
  if (data) return data;

  // Try with 0x prefix removed
  if (key.startsWith("0x")) {
    data = cache.get(key.slice(2));
    if (data) return data;
  }

  // Try with 0x prefix added
  if (!key.startsWith("0x")) {
    data = cache.get(`0x${key}`);
    if (data) return data;
  }

  return null;
}
src/lib/cover-url-resolver.ts
import "server-only";
import { db } from "@/neynar-db-sdk/src/db";
import { kv } from "@/db/schema";
import { eq } from "drizzle-orm";
import type { DiscoveryEntry } from "@/lib/net-protocol";

const DISCOVERY_KEY = "discovery-index";
const COVER_PREFIX = "cover:";
const MAX_COVER_SIZE = 500 * 1024; // 500KB max per cover

/**
 * Resolves a cover URL for sharing - converts base64 data URLs to hosted URLs
 *
 * This is the "image bank" system - when we encounter a base64 cover during sharing,
 * we store it in our KV database and return a URL to our /api/covers/[key] endpoint.
 * This approach:
 * 1. Doesn't require external blob storage (Vercel Blob)
 * 2. Uses our existing database infrastructure
 * 3. Provides reliable, fast cover serving
 *
 * @param contentKey - The content key of the book
 * @param coverUrl - The current cover URL (may be base64 or hosted)
 * @param host - Optional host for building the cover URL
 * @returns A hosted URL suitable for OG images, or empty string if no cover
 */
export async function resolveShareableCoverUrl(
  contentKey: string,
  coverUrl: string | undefined,
  host?: string
): Promise<string> {
  // No cover at all
  if (!coverUrl) {
    return "";
  }

  // Already a hosted URL - use it directly
  if (coverUrl.startsWith("http://") || coverUrl.startsWith("https://")) {
    return coverUrl;
  }

  // It's a base64 data URL - need to convert to hosted URL
  if (coverUrl.startsWith("data:image/")) {
    const safeKey = contentKey.replace(/[^a-zA-Z0-9]/g, "").slice(0, 32);
    console.log(`[cover-resolver] Converting base64 cover to hosted URL for ${safeKey}...`);

    try {
      // Parse the data URL
      const matches = coverUrl.match(/^data:image\/(png|jpeg|jpg|webp|gif);base64,(.+)$/);
      if (!matches) {
        console.error("[cover-resolver] Could not parse data URL format");
        return "";
      }

      const imageType = matches[1] === "jpg" ? "jpeg" : matches[1];
      const base64Data = matches[2];

      // Check size
      const sizeBytes = Math.ceil(base64Data.length * 0.75);
      if (sizeBytes > MAX_COVER_SIZE) {
        console.warn(`[cover-resolver] Cover too large (${Math.round(sizeBytes/1024)}KB), skipping storage`);
        // Still can't use it for OG images, but don't fail completely
        return "";
      }

      // Store in KV database
      const coverKey = `${COVER_PREFIX}${safeKey}`;
      const coverData = {
        base64: base64Data,
        contentType: `image/${imageType}`,
        contentKey: contentKey,
        storedAt: Date.now(),
      };

      await db.insert(kv).values({
        key: coverKey,
        value: JSON.stringify(coverData),
      }).onConflictDoUpdate({
        target: kv.key,
        set: { value: JSON.stringify(coverData) },
      });

      // Build the URL to our cover API using the actual host
      // This ensures the URL works regardless of which domain the app is deployed to
      const actualHost = host || "netlibrary.neynar.com";
      const protocol = actualHost.includes("localhost") ? "http" : "https";
      const hostedUrl = `${protocol}://${actualHost}/api/covers/${safeKey}`;

      console.log(`[cover-resolver] Stored cover in KV (${Math.round(sizeBytes/1024)}KB) -> ${hostedUrl}`);

      // Update the discovery entry with the hosted URL (fire and forget)
      updateDiscoveryEntryCover(contentKey, hostedUrl).catch(err => {
        console.error("[cover-resolver] Failed to update discovery entry:", err);
      });

      return hostedUrl;
    } catch (error) {
      console.error("[cover-resolver] Failed to store cover:", error);
      return "";
    }
  }

  // Unknown format
  console.warn(`[cover-resolver] Unknown cover URL format: ${coverUrl.slice(0, 50)}...`);
  return "";
}

/**
 * Updates the discovery entry with a new hosted cover URL
 */
async function updateDiscoveryEntryCover(contentKey: string, hostedUrl: string): Promise<void> {
  try {
    // Fetch current discovery index
    const result = await db.select().from(kv).where(eq(kv.key, DISCOVERY_KEY)).limit(1);
    if (!result[0]?.value) {
      console.error("[cover-resolver] Discovery index not found");
      return;
    }

    const entries: DiscoveryEntry[] = JSON.parse(result[0].value);
    const normalizedKey = contentKey.toLowerCase();

    // Find the entry (handle 0x prefix variations)
    const entryIndex = entries.findIndex(e => {
      const eKey = (e.contentKey || '').toLowerCase();
      return eKey === normalizedKey ||
             eKey === normalizedKey.replace(/^0x/, "") ||
             eKey === `0x${normalizedKey.replace(/^0x/, "")}`;
    });

    if (entryIndex === -1) {
      console.error(`[cover-resolver] Entry not found for contentKey: ${contentKey}`);
      return;
    }

    // Update the cover URL
    entries[entryIndex].coverUrl = hostedUrl;

    // Save back to DB
    await db.insert(kv).values({
      key: DISCOVERY_KEY,
      value: JSON.stringify(entries)
    }).onConflictDoUpdate({
      target: kv.key,
      set: { value: JSON.stringify(entries) }
    });

    console.log(`[cover-resolver] Updated discovery entry with hosted cover URL`);
  } catch (error) {
    console.error("[cover-resolver] Failed to update discovery entry:", error);
    throw error;
  }
}
src/lib/cover-url-utils.ts
/**
 * Client-side utilities for cover URL handling
 */

/**
 * Normalize cover URL to work in both dev and production environments.
 * Production URLs pointing to our /api/covers/ endpoint become relative paths
 * so they work locally too. External URLs (storedon.net, etc.) are kept as-is.
 */
export function normalizeCoverUrl(url: string | undefined): string | undefined {
  if (!url) return undefined;

  // Convert any Neynar app domain URLs to relative paths for local development
  // This handles:
  // - https://netlibrary.neynar.com/api/covers/xxx
  // - https://miniapp-generator-fid-*.neynar.app/api/covers/xxx
  // - Any other *.neynar.com or *.neynar.app domain with /api/covers/
  if (url.includes("/api/covers/") && (url.includes(".neynar.com") || url.includes(".neynar.app"))) {
    // Extract just the /api/covers/xxx part
    const match = url.match(/\/api\/covers\/[^/]+$/);
    if (match) {
      return match[0];
    }
  }

  return url;
}
src/lib/crypto.ts
/**
 * Net Library — Client-Side Content Encryption
 *
 * Password-based AES-256-GCM encryption using the Web Crypto API.
 * Zero external dependencies — uses only the built-in SubtleCrypto interface.
 *
 * SECURITY INVARIANTS:
 * - All encrypt/decrypt operations run in the browser only.
 * - Plaintext content and passwords never leave the client.
 * - Each encrypt call generates a fresh random salt (16 bytes) and IV (12 bytes).
 * - PBKDF2 with 100,000 iterations derives the AES key from the password + salt.
 *
 * WIRE FORMAT (base64-encoded):
 *   [16-byte salt][12-byte IV][ciphertext + 16-byte GCM auth tag]
 *
 * The GCM auth tag is appended automatically by SubtleCrypto.encrypt and
 * verified automatically by SubtleCrypto.decrypt — wrong password → throws.
 */

const PBKDF2_ITERATIONS = 100_000;
const SALT_BYTES = 16;
const IV_BYTES = 12;

/**
 * Derive an AES-256-GCM CryptoKey from a password and salt using PBKDF2.
 *
 * @param password - User-provided password string
 * @param salt     - Random salt (SALT_BYTES long)
 */
export async function deriveKey(password: string, salt: Uint8Array): Promise<CryptoKey> {
  const enc = new TextEncoder();
  const keyMaterial = await crypto.subtle.importKey(
    "raw",
    enc.encode(password),
    { name: "PBKDF2" },
    false,
    ["deriveKey"]
  );

  // Cast to ArrayBuffer to satisfy strict SubtleCrypto typings (BufferSource)
  const saltBuffer = salt.buffer instanceof ArrayBuffer
    ? salt.buffer.slice(salt.byteOffset, salt.byteOffset + salt.byteLength) as ArrayBuffer
    : new Uint8Array(salt).buffer as ArrayBuffer;

  return crypto.subtle.deriveKey(
    {
      name: "PBKDF2",
      salt: saltBuffer,
      iterations: PBKDF2_ITERATIONS,
      hash: "SHA-256",
    },
    keyMaterial,
    { name: "AES-GCM", length: 256 },
    false,
    ["encrypt", "decrypt"]
  );
}

/**
 * Encrypt content with a password.
 *
 * Generates a fresh random salt and IV for every call — the same password
 * encrypting the same content twice will produce different ciphertext.
 *
 * @param content  - Plaintext content as a string or ArrayBuffer
 * @param password - User-provided password
 * @returns        Base64 string: [16-byte salt][12-byte IV][ciphertext+tag]
 */
export async function encryptContent(
  content: string | ArrayBuffer,
  password: string
): Promise<string> {
  const salt = crypto.getRandomValues(new Uint8Array(SALT_BYTES));
  const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));
  const key = await deriveKey(password, salt);

  const plaintext: ArrayBuffer =
    typeof content === "string"
      ? new TextEncoder().encode(content).buffer
      : content;

  const ciphertext = await crypto.subtle.encrypt(
    { name: "AES-GCM", iv },
    key,
    plaintext
  );

  // Concatenate: salt || iv || ciphertext+tag
  const combined = new Uint8Array(salt.byteLength + iv.byteLength + ciphertext.byteLength);
  combined.set(salt, 0);
  combined.set(iv, salt.byteLength);
  combined.set(new Uint8Array(ciphertext), salt.byteLength + iv.byteLength);

  // Encode to base64 for storage/transport.
  // Use chunked String.fromCharCode to avoid call-stack overflow on large files
  // (spreading a large Uint8Array as function arguments exceeds JS engine arg limits ~65k).
  let binary = "";
  const chunkSize = 8192;
  for (let i = 0; i < combined.length; i += chunkSize) {
    binary += String.fromCharCode(...combined.subarray(i, i + chunkSize));
  }
  return btoa(binary);
}

/**
 * Decrypt a base64-encoded encrypted blob with a password.
 *
 * @param encryptedBase64 - Output of encryptContent()
 * @param password        - The password used during encryption
 * @returns               Decrypted content as an ArrayBuffer
 * @throws                If the password is wrong or the data is corrupt
 *                        (SubtleCrypto throws DOMException on auth tag failure)
 */
export async function decryptContent(
  encryptedBase64: string,
  password: string
): Promise<ArrayBuffer> {
  // Decode base64 → Uint8Array
  const binaryStr = atob(encryptedBase64);
  const combined = new Uint8Array(binaryStr.length);
  for (let i = 0; i < binaryStr.length; i++) {
    combined[i] = binaryStr.charCodeAt(i);
  }

  // Slice out the three components, then extract plain ArrayBuffers so SubtleCrypto
  // strict typings (BufferSource → ArrayBuffer, not ArrayBufferLike) are satisfied.
  const toArrayBuffer = (u8: Uint8Array): ArrayBuffer =>
    u8.buffer instanceof ArrayBuffer
      ? u8.buffer.slice(u8.byteOffset, u8.byteOffset + u8.byteLength) as ArrayBuffer
      : new Uint8Array(u8).buffer as ArrayBuffer;

  const salt = combined.slice(0, SALT_BYTES);
  const iv = combined.slice(SALT_BYTES, SALT_BYTES + IV_BYTES);
  const ciphertext = combined.slice(SALT_BYTES + IV_BYTES);

  const ivBuffer = toArrayBuffer(iv);
  const ciphertextBuffer = toArrayBuffer(ciphertext);

  const key = await deriveKey(password, salt);

  // SubtleCrypto.decrypt throws DOMException if auth tag check fails (wrong password)
  return crypto.subtle.decrypt({ name: "AES-GCM", iv: ivBuffer }, key, ciphertextBuffer);
}

/**
 * Convenience helper: decrypt and return plaintext as a UTF-8 string.
 * Use this for text content; use decryptContent() directly for binary files.
 *
 * @throws If the password is wrong or the data is corrupt
 */
export async function decryptContentToString(
  encryptedBase64: string,
  password: string
): Promise<string> {
  const buffer = await decryptContent(encryptedBase64, password);
  return new TextDecoder().decode(buffer);
}
src/lib/data-url-utils.ts
/**
 * Data URL utility functions
 *
 * Safari/iOS/WKWebView (used by Base App) can throw "Load failed" when fetch() is called
 * on data: URLs due to WebKit security policies. These utilities provide safer alternatives.
 */

/**
 * Convert a data URL to a Blob without using fetch()
 *
 * This is safer than `fetch(dataUrl).then(r => r.blob())` because Safari/iOS/Base App
 * can throw "Load failed" on data: URL fetches due to WebKit security policies.
 *
 * @param dataUrl - A valid data URL (e.g., "data:image/png;base64,...")
 * @returns A Blob containing the decoded data
 * @throws Error if the data URL is invalid or decoding fails
 *
 * @example
 * ```ts
 * const blob = dataUrlToBlob("data:image/png;base64,iVBORw0KGgo...");
 * const file = new File([blob], "image.png", { type: blob.type });
 * ```
 */
export function dataUrlToBlob(dataUrl: string): Blob {
  if (!dataUrl.startsWith("data:")) {
    throw new Error("Invalid data URL: must start with 'data:'");
  }

  const [header, base64Data] = dataUrl.split(",");
  if (!base64Data) {
    throw new Error("Invalid data URL: missing base64 data after comma");
  }

  // Extract MIME type from header (e.g., "data:image/png;base64" -> "image/png")
  const mimeMatch = header.match(/data:([^;]+)/);
  const mimeType = mimeMatch ? mimeMatch[1] : "application/octet-stream";

  // Decode base64 to binary
  const binaryString = atob(base64Data);
  const bytes = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }

  return new Blob([bytes], { type: mimeType });
}

/**
 * Convert a data URL to a Blob with automatic fallback to fetch() if decoding fails
 *
 * This tries the safe manual decoding first, then falls back to fetch() if needed.
 * Use this when you want maximum compatibility but still want to avoid the
 * Safari/iOS "Load failed" error in most cases.
 *
 * @param dataUrl - A data URL or regular URL
 * @returns Promise resolving to a Blob
 *
 * @example
 * ```ts
 * const blob = await safeDataUrlToBlob(someUrl);
 * ```
 */
export async function safeDataUrlToBlob(dataUrl: string): Promise<Blob> {
  if (dataUrl.startsWith("data:")) {
    try {
      return dataUrlToBlob(dataUrl);
    } catch (decodeError) {
      console.warn("[dataUrlUtils] Manual decode failed, falling back to fetch:", decodeError);
      // Fallback to fetch - this may fail on Safari/iOS but is our last resort
      const response = await fetch(dataUrl);
      return response.blob();
    }
  }

  // Not a data URL - use fetch directly
  const response = await fetch(dataUrl);
  return response.blob();
}

/**
 * Convert a data URL to a File object
 *
 * @param dataUrl - A valid data URL
 * @param fileName - Name for the resulting file
 * @returns A File object containing the decoded data
 *
 * @example
 * ```ts
 * const file = dataUrlToFile("data:image/png;base64,...", "screenshot.png");
 * ```
 */
export function dataUrlToFile(dataUrl: string, fileName: string): File {
  const blob = dataUrlToBlob(dataUrl);
  return new File([blob], fileName, { type: blob.type });
}
src/lib/diagnostics.ts
import { isCoinbaseWalletUA } from "@/lib/ua-utils";

// =============================================================================
// COMPREHENSIVE DIAGNOSTICS SYSTEM
// Tracks all user actions for debugging and analytics
// =============================================================================

export type ActionCategory =
  | "upload"           // File uploads to Net Protocol
  | "membership"       // Membership signup, linking addresses
  | "wallet"           // Wallet connections, signatures
  | "transaction"      // Blockchain transactions (tips, payments)
  | "engagement"       // Upvotes, reading progress, streaks
  | "comment"          // Comments (onchain and offchain)
  | "collection"       // Collections management
  | "discovery"        // Search, recommendations, browsing
  | "auth"             // Authentication, SIWE, verification
  | "error";           // Uncategorized errors

export type ActionOutcome = "success" | "error" | "cancelled" | "pending";

export interface DiagnosticEvent {
  // Identification
  eventId: string;
  sessionId?: string;  // Groups related events (e.g., multi-step flow)
  category: ActionCategory;
  action: string;      // Specific action name (e.g., "membership-signup", "upvote")

  // Timing
  timestamp: number;
  durationMs?: number;

  // User context
  walletAddress?: string;
  walletConnector?: string;  // "farcaster" | "coinbase-wallet" | etc.
  fid?: number;
  chainId?: number;

  // Action details
  outcome: ActionOutcome;
  errorMessage?: string;
  errorCode?: string;

  // Metadata (action-specific data)
  metadata?: Record<string, unknown>;

  // Environment
  userAgent?: string;
  platform?: "farcaster" | "base-app" | "web" | "unknown";
}

// Generate unique event ID
export function generateEventId(): string {
  return `evt_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
}

// Generate session ID for multi-step flows
export function generateSessionId(prefix: string = "session"): string {
  return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
}

// Detect platform from user agent or context
export function detectPlatform(): "farcaster" | "base-app" | "web" | "unknown" {
  if (typeof window === "undefined") return "unknown";

  const userAgent = navigator.userAgent.toLowerCase();

  // Check for Farcaster mini app context
  if (window.location.href.includes("warpcast") ||
      userAgent.includes("warpcast") ||
      // @ts-expect-error - Farcaster SDK may inject this
      window.farcaster) {
    return "farcaster";
  }

  // Check for Base App / Coinbase Wallet in-app browser via shared UA utility.
  if (isCoinbaseWalletUA(userAgent)) {
    return "base-app";
  }

  return "web";
}

// Client-side: Send diagnostic event to server
export async function trackEvent(event: Omit<DiagnosticEvent, "eventId" | "timestamp" | "userAgent" | "platform">): Promise<void> {
  try {
    const fullEvent: DiagnosticEvent = {
      ...event,
      eventId: generateEventId(),
      timestamp: Date.now(),
      userAgent: typeof navigator !== "undefined" ? navigator.userAgent : undefined,
      platform: detectPlatform(),
    };

    // Fire and forget - don't block on diagnostics
    fetch("/api/diagnostics", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(fullEvent),
    }).catch(e => {
      console.warn("[diagnostics] Failed to send event:", e);
    });

    // Also log to console in development
    // eslint-disable-next-line @neynar/no-process-env
    if (process.env.NODE_ENV === "development") {
      console.log(`[DIAG] ${event.category}/${event.action}: ${event.outcome}`, event.metadata || "");
    }
  } catch (e) {
    console.warn("[diagnostics] trackEvent error:", e);
  }
}

// Helper: Track action start (returns function to call on completion)
export function trackActionStart(
  category: ActionCategory,
  action: string,
  context?: {
    walletAddress?: string;
    walletConnector?: string;
    fid?: number;
    chainId?: number;
    sessionId?: string;
    metadata?: Record<string, unknown>;
  }
): (outcome: ActionOutcome, errorMessage?: string, additionalMetadata?: Record<string, unknown>) => void {
  const startTime = Date.now();
  const sessionId = context?.sessionId || generateSessionId(action);

  // Track the start event
  trackEvent({
    category,
    action: `${action}-start`,
    outcome: "pending",
    sessionId,
    ...context,
  });

  // Return completion function
  return (outcome: ActionOutcome, errorMessage?: string, additionalMetadata?: Record<string, unknown>) => {
    trackEvent({
      category,
      action: `${action}-complete`,
      outcome,
      errorMessage,
      sessionId,
      durationMs: Date.now() - startTime,
      ...context,
      metadata: {
        ...context?.metadata,
        ...additionalMetadata,
      },
    });
  };
}

// =============================================================================
// CATEGORY-SPECIFIC TRACKING HELPERS
// =============================================================================

// Membership actions
export const trackMembership = {
  signupStart: (walletAddress: string, connector: string, fid?: number) =>
    trackActionStart("membership", "signup", { walletAddress, walletConnector: connector, fid }),

  linkAddress: (walletAddress: string, memberId: number, outcome: ActionOutcome, error?: string) =>
    trackEvent({
      category: "membership",
      action: "link-address",
      outcome,
      errorMessage: error,
      walletAddress,
      metadata: { memberId },
    }),

  checkStatus: (walletAddress: string, isMember: boolean, memberId?: number) =>
    trackEvent({
      category: "membership",
      action: "check-status",
      outcome: "success",
      walletAddress,
      metadata: { isMember, memberId },
    }),
};

// Wallet actions
export const trackWallet = {
  connect: (connector: string, address: string, chainId: number, outcome: ActionOutcome, error?: string) =>
    trackEvent({
      category: "wallet",
      action: "connect",
      outcome,
      errorMessage: error,
      walletAddress: address,
      walletConnector: connector,
      chainId,
    }),

  disconnect: (address: string) =>
    trackEvent({
      category: "wallet",
      action: "disconnect",
      outcome: "success",
      walletAddress: address,
    }),

  switchChain: (address: string, fromChain: number, toChain: number, outcome: ActionOutcome, error?: string) =>
    trackEvent({
      category: "wallet",
      action: "switch-chain",
      outcome,
      errorMessage: error,
      walletAddress: address,
      metadata: { fromChain, toChain },
    }),
};

// Transaction actions
export const trackTransaction = {
  start: (txType: string, walletAddress: string, connector: string, chainId: number, metadata?: Record<string, unknown>) =>
    trackActionStart("transaction", txType, { walletAddress, walletConnector: connector, chainId, metadata }),

  submit: (txType: string, txHash: string, walletAddress: string) =>
    trackEvent({
      category: "transaction",
      action: `${txType}-submitted`,
      outcome: "pending",
      walletAddress,
      metadata: { txHash },
    }),

  confirm: (txType: string, txHash: string, walletAddress: string, gasUsed?: string) =>
    trackEvent({
      category: "transaction",
      action: `${txType}-confirmed`,
      outcome: "success",
      walletAddress,
      metadata: { txHash, gasUsed },
    }),

  fail: (txType: string, walletAddress: string, error: string, txHash?: string) =>
    trackEvent({
      category: "transaction",
      action: `${txType}-failed`,
      outcome: "error",
      errorMessage: error,
      walletAddress,
      metadata: { txHash },
    }),
};

// Engagement actions
export const trackEngagement = {
  upvote: (contentKey: string, walletAddress: string, outcome: ActionOutcome, error?: string) =>
    trackEvent({
      category: "engagement",
      action: "upvote",
      outcome,
      errorMessage: error,
      walletAddress,
      metadata: { contentKey },
    }),

  readingProgress: (contentKey: string, walletAddress: string, progress: number) =>
    trackEvent({
      category: "engagement",
      action: "reading-progress",
      outcome: "success",
      walletAddress,
      metadata: { contentKey, progress },
    }),

  addToQueue: (contentKey: string, walletAddress: string) =>
    trackEvent({
      category: "engagement",
      action: "add-to-queue",
      outcome: "success",
      walletAddress,
      metadata: { contentKey },
    }),

  streakUpdate: (walletAddress: string, currentStreak: number, action: "maintain" | "break" | "start") =>
    trackEvent({
      category: "engagement",
      action: `streak-${action}`,
      outcome: "success",
      walletAddress,
      metadata: { currentStreak },
    }),
};

// Comment actions
export const trackComment = {
  post: (contentKey: string, walletAddress: string, isOnchain: boolean, outcome: ActionOutcome, error?: string) =>
    trackEvent({
      category: "comment",
      action: isOnchain ? "post-onchain" : "post-offchain",
      outcome,
      errorMessage: error,
      walletAddress,
      metadata: { contentKey, isOnchain },
    }),

  delete: (commentId: string, walletAddress: string, outcome: ActionOutcome, error?: string) =>
    trackEvent({
      category: "comment",
      action: "delete",
      outcome,
      errorMessage: error,
      walletAddress,
      metadata: { commentId },
    }),
};

// Collection actions
export const trackCollection = {
  create: (name: string, walletAddress: string, outcome: ActionOutcome, error?: string) =>
    trackEvent({
      category: "collection",
      action: "create",
      outcome,
      errorMessage: error,
      walletAddress,
      metadata: { name },
    }),

  addItem: (collectionId: string, contentKey: string, walletAddress: string, outcome: ActionOutcome) =>
    trackEvent({
      category: "collection",
      action: "add-item",
      outcome,
      walletAddress,
      metadata: { collectionId, contentKey },
    }),

  removeItem: (collectionId: string, contentKey: string, walletAddress: string, outcome: ActionOutcome) =>
    trackEvent({
      category: "collection",
      action: "remove-item",
      outcome,
      walletAddress,
      metadata: { collectionId, contentKey },
    }),
};

// Discovery actions
export const trackDiscovery = {
  search: (query: string, resultsCount: number, durationMs: number) =>
    trackEvent({
      category: "discovery",
      action: "search",
      outcome: "success",
      durationMs,
      metadata: { query: query.slice(0, 50), resultsCount },
    }),

  viewContent: (contentKey: string, walletAddress?: string) =>
    trackEvent({
      category: "discovery",
      action: "view-content",
      outcome: "success",
      walletAddress,
      metadata: { contentKey },
    }),

  browse: (category: string, page: number) =>
    trackEvent({
      category: "discovery",
      action: "browse",
      outcome: "success",
      metadata: { category, page },
    }),
};

// Auth actions
export const trackAuth = {
  siweStart: (walletAddress: string, connector: string) =>
    trackActionStart("auth", "siwe", { walletAddress, walletConnector: connector }),

  siweComplete: (walletAddress: string, outcome: ActionOutcome, error?: string) =>
    trackEvent({
      category: "auth",
      action: "siwe-complete",
      outcome,
      errorMessage: error,
      walletAddress,
    }),
};

// Error tracking (for uncategorized errors)
export const trackError = {
  unhandled: (error: Error, context?: Record<string, unknown>) =>
    trackEvent({
      category: "error",
      action: "unhandled",
      outcome: "error",
      errorMessage: error.message,
      errorCode: error.name,
      metadata: {
        stack: error.stack?.slice(0, 500),
        ...context,
      },
    }),

  api: (endpoint: string, statusCode: number, error: string) =>
    trackEvent({
      category: "error",
      action: "api-error",
      outcome: "error",
      errorMessage: error,
      errorCode: String(statusCode),
      metadata: { endpoint },
    }),
};
src/lib/discovery-ops.ts
/**
 * Discovery Index Operations
 *
 * Single source of truth for all read/write operations on the discovery index.
 * Every function that modifies the index MUST go through this module so that:
 *   1. The full index blob (discovery-index) and
 *   2. The per-entry fast-lookup key (discovery:{contentKey})
 *  are always written atomically in the same PostgreSQL transaction.
 *
 * Prior to this module, multiple independent copies of addEntryAtomically existed
 * in agent-auth.ts and discovery/route.ts, each needing to be kept in sync manually.
 *
 * Callers:
 *   - agent-auth.ts      → re-exports addDiscoveryEntry for upload/write/archive routes
 *   - discovery/route.ts → uses all four functions directly
 */

import { connection } from "@/neynar-db-sdk/src/db";
import type { DiscoveryEntry } from "@/lib/net-protocol";

// KV key for the full discovery index blob
export const DISCOVERY_INDEX_KEY = "discovery-index";

// Retry configuration for lock-contention scenarios
const MAX_RETRIES = 3;
const RETRY_DELAY_MS = 100;

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/** Sleep for `ms` milliseconds */
function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

/** Returns true if the error looks like a PostgreSQL lock contention or deadlock */
function isLockError(msg: string): boolean {
  return msg.includes("could not obtain lock") || msg.includes("deadlock");
}

/** Retry wrapper used by all four public functions */
async function withRetry<T>(
  label: string,
  fn: () => Promise<T>
): Promise<T> {
  for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
    try {
      return await fn();
    } catch (error) {
      const msg = error instanceof Error ? error.message : String(error);
      console.error(`[discovery-ops] ${label} attempt ${attempt}/${MAX_RETRIES} failed:`, msg);

      if (isLockError(msg) && attempt < MAX_RETRIES) {
        await sleep(RETRY_DELAY_MS * attempt);
        continue;
      }

      throw error;
    }
  }
  // TypeScript requires an explicit unreachable throw after the loop
  throw new Error(`[discovery-ops] ${label}: max retries exceeded`);
}

// ---------------------------------------------------------------------------
// addDiscoveryEntry
// ---------------------------------------------------------------------------

/**
 * Atomically add a new entry to the discovery index.
 *
 * RACE CONDITION FIX: Uses a PostgreSQL FOR UPDATE transaction so that two
 * concurrent uploads cannot overwrite each other.
 *
 * Writes both:
 *  - discovery-index  (full array blob)
 *  - discovery:{contentKey}  (per-entry fast-lookup key)
 *
 * @param entry   The DiscoveryEntry to add.
 * @param prepend If true (default), insert at the front of the index (newest first).
 *                If false, append to the end (used by the relay upload path).
 */
export async function addDiscoveryEntry(
  entry: DiscoveryEntry,
  prepend = true
): Promise<{ success: boolean; isDuplicate: boolean; count: number; error?: string }> {
  try {
    const result = await withRetry("addDiscoveryEntry", () =>
      connection.begin(async (tx) => {
        // Step 1: Lock the index row for atomic read-modify-write
        const rows = await tx`
          SELECT value FROM kv
          WHERE key = ${DISCOVERY_INDEX_KEY}
          FOR UPDATE
        `;

        // Step 2: Parse current entries
        let currentEntries: DiscoveryEntry[] = [];
        if (rows[0]?.value) {
          try {
            currentEntries = JSON.parse(rows[0].value);
          } catch {
            console.error("[discovery-ops/addDiscoveryEntry] Failed to parse existing entries");
          }
        }

        // Step 3: Dedup check
        if (currentEntries.some((e) => e.contentKey === entry.contentKey)) {
          return { success: true, isDuplicate: true, count: currentEntries.length };
        }

        // Step 4: Insert at correct position
        const updatedEntries = prepend
          ? [entry, ...currentEntries]
          : [...currentEntries, entry];
        const newValue = JSON.stringify(updatedEntries);

        // Step 5: Persist the full index
        if (rows.length > 0) {
          await tx`UPDATE kv SET value = ${newValue} WHERE key = ${DISCOVERY_INDEX_KEY}`;
        } else {
          await tx`
            INSERT INTO kv (key, value)
            VALUES (${DISCOVERY_INDEX_KEY}, ${newValue})
            ON CONFLICT (key) DO UPDATE SET value = ${newValue}
          `;
        }

        // Step 6: Write the per-entry fast-lookup key (same transaction = atomic)
        const perEntryKey = `discovery:${entry.contentKey}`;
        const perEntryValue = JSON.stringify(entry);
        await tx`
          INSERT INTO kv (key, value)
          VALUES (${perEntryKey}, ${perEntryValue})
          ON CONFLICT (key) DO UPDATE SET value = ${perEntryValue}
        `;

        return { success: true, isDuplicate: false, count: updatedEntries.length };
      })
    );

    return result;
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return { success: false, isDuplicate: false, count: 0, error: msg };
  }
}

// ---------------------------------------------------------------------------
// updateDiscoveryEntry  (user path — ownership check required)
// ---------------------------------------------------------------------------

/**
 * Atomically update or remove an entry that belongs to the calling user.
 *
 * Ownership is verified by checking that the entry's uploaderAddress, operator,
 * or importerAddress matches one of the provided userAddresses.  Returns an
 * error if the entry is not found or not owned by the user.
 *
 * Writes both:
 *  - discovery-index  (full array blob)
 *  - discovery:{contentKey}  (per-entry key — deleted if entry is removed)
 *
 * @param contentKey    Content key of the entry to update.
 * @param userAddresses Addresses allowed to modify this entry (cross-platform support).
 * @param updateFn      Receives the existing entry; return updated entry or null to remove.
 */
export async function updateDiscoveryEntry(
  contentKey: string,
  userAddresses: string[],
  updateFn: (entry: DiscoveryEntry) => DiscoveryEntry | null
): Promise<{ success: boolean; entry?: DiscoveryEntry | null; removed?: boolean; error?: string }> {
  try {
    const result = await withRetry("updateDiscoveryEntry", () =>
      connection.begin(async (tx) => {
        // Step 1: Lock index row
        const rows = await tx`
          SELECT value FROM kv
          WHERE key = ${DISCOVERY_INDEX_KEY}
          FOR UPDATE
        `;

        // Step 2: Parse
        let currentEntries: DiscoveryEntry[] = [];
        if (rows[0]?.value) {
          try {
            currentEntries = JSON.parse(rows[0].value);
          } catch {
            console.error("[discovery-ops/updateDiscoveryEntry] Failed to parse existing entries");
          }
        }

        // Step 3: Find entry with ownership verification
        // IMPORTANT: For relay uploads, operator is the backend wallet, NOT the user's wallet.
        // uploaderAddress is the user's wallet for attribution and ownership.
        const entryIndex = currentEntries.findIndex(
          (e) =>
            e.contentKey === contentKey &&
            (
              (e.uploaderAddress && userAddresses.includes(e.uploaderAddress.toLowerCase())) ||
              (e.operator && userAddresses.includes(e.operator.toLowerCase())) ||
              (e.importerAddress && userAddresses.includes(e.importerAddress.toLowerCase()))
            )
        );

        if (entryIndex === -1) {
          return { success: false, error: "Entry not found or not owned by user" };
        }

        // Step 4: Apply update
        const updatedEntry = updateFn(currentEntries[entryIndex]);

        if (updatedEntry === null) {
          currentEntries.splice(entryIndex, 1);
        } else {
          currentEntries[entryIndex] = updatedEntry;
        }

        // Step 5: Persist full index
        const newValue = JSON.stringify(currentEntries);
        await tx`UPDATE kv SET value = ${newValue} WHERE key = ${DISCOVERY_INDEX_KEY}`;

        // Step 6: Sync per-entry key
        const perEntryKey = `discovery:${contentKey}`;
        if (updatedEntry === null) {
          await tx`DELETE FROM kv WHERE key = ${perEntryKey}`;
        } else {
          const perEntryValue = JSON.stringify(updatedEntry);
          await tx`
            INSERT INTO kv (key, value)
            VALUES (${perEntryKey}, ${perEntryValue})
            ON CONFLICT (key) DO UPDATE SET value = ${perEntryValue}
          `;
        }

        return { success: true, entry: updatedEntry, removed: updatedEntry === null };
      })
    );

    return result;
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return { success: false, error: msg };
  }
}

// ---------------------------------------------------------------------------
// adminUpdateDiscoveryEntry  (admin path — no ownership check)
// ---------------------------------------------------------------------------

/**
 * Atomically update or remove any entry by contentKey (admin-only).
 *
 * Unlike updateDiscoveryEntry, this does NOT check ownership — callers are
 * responsible for verifying admin credentials before calling this function.
 *
 * Writes both:
 *  - discovery-index  (full array blob)
 *  - discovery:{contentKey}  (per-entry key — deleted if entry is removed)
 *
 * Uses the same FOR UPDATE transaction as the user path, so admin updates are
 * now atomic (previously non-transactional via storeLocalIndex + separate drizzle call).
 *
 * @param contentKey  Content key of the entry to update.
 * @param updateFn    Receives the existing entry; return updated entry or null to remove.
 */
export async function adminUpdateDiscoveryEntry(
  contentKey: string,
  updateFn: (entry: DiscoveryEntry) => DiscoveryEntry | null
): Promise<{ success: boolean; entry?: DiscoveryEntry | null; removed?: boolean; error?: string }> {
  try {
    const result = await withRetry("adminUpdateDiscoveryEntry", () =>
      connection.begin(async (tx) => {
        // Step 1: Lock index row
        const rows = await tx`
          SELECT value FROM kv
          WHERE key = ${DISCOVERY_INDEX_KEY}
          FOR UPDATE
        `;

        // Step 2: Parse
        let currentEntries: DiscoveryEntry[] = [];
        if (rows[0]?.value) {
          try {
            currentEntries = JSON.parse(rows[0].value);
          } catch {
            console.error("[discovery-ops/adminUpdateDiscoveryEntry] Failed to parse existing entries");
          }
        }

        // Step 3: Find entry by contentKey (no ownership filter)
        const entryIndex = currentEntries.findIndex((e) => e.contentKey === contentKey);
        if (entryIndex === -1) {
          return { success: false, error: "Entry not found" };
        }

        // Step 4: Apply update
        const updatedEntry = updateFn(currentEntries[entryIndex]);

        if (updatedEntry === null) {
          currentEntries.splice(entryIndex, 1);
        } else {
          currentEntries[entryIndex] = updatedEntry;
        }

        // Step 5: Persist full index
        const newValue = JSON.stringify(currentEntries);
        await tx`UPDATE kv SET value = ${newValue} WHERE key = ${DISCOVERY_INDEX_KEY}`;

        // Step 6: Sync per-entry key
        const perEntryKey = `discovery:${contentKey}`;
        if (updatedEntry === null) {
          await tx`DELETE FROM kv WHERE key = ${perEntryKey}`;
        } else {
          const perEntryValue = JSON.stringify(updatedEntry);
          await tx`
            INSERT INTO kv (key, value)
            VALUES (${perEntryKey}, ${perEntryValue})
            ON CONFLICT (key) DO UPDATE SET value = ${perEntryValue}
          `;
        }

        return { success: true, entry: updatedEntry, removed: updatedEntry === null };
      })
    );

    return result;
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return { success: false, error: msg };
  }
}

// ---------------------------------------------------------------------------
// seedDiscoveryEntries
// ---------------------------------------------------------------------------

/**
 * Atomically seed the discovery index with multiple entries.
 *
 * Entries whose contentKey already exists in the index are silently skipped
 * (no duplicates). All new entries are prepended in a single transaction.
 * Per-entry fast-lookup keys are written for every newly-added entry.
 *
 * @param entries  Array of DiscoveryEntry objects to seed.
 */
export async function seedDiscoveryEntries(
  entries: DiscoveryEntry[]
): Promise<{ success: boolean; added: number; total: number; error?: string }> {
  if (entries.length === 0) {
    return { success: true, added: 0, total: 0 };
  }

  try {
    const result = await withRetry("seedDiscoveryEntries", () =>
      connection.begin(async (tx) => {
        // Step 1: Lock index row
        const rows = await tx`
          SELECT value FROM kv
          WHERE key = ${DISCOVERY_INDEX_KEY}
          FOR UPDATE
        `;

        // Step 2: Parse current entries
        let currentEntries: DiscoveryEntry[] = [];
        if (rows[0]?.value) {
          try {
            currentEntries = JSON.parse(rows[0].value);
          } catch {
            console.error("[discovery-ops/seedDiscoveryEntries] Failed to parse existing entries");
          }
        }

        // Step 3: Filter to only truly new entries (dedup by contentKey)
        const existingKeys = new Set(currentEntries.map((e) => e.contentKey));
        const newEntries = entries.filter((e) => !existingKeys.has(e.contentKey));

        if (newEntries.length === 0) {
          return { success: true, added: 0, total: currentEntries.length };
        }

        // Step 4: Prepend all new entries (seed data goes to the front)
        const updatedEntries = [...newEntries, ...currentEntries];
        const newValue = JSON.stringify(updatedEntries);

        // Step 5: Persist full index
        if (rows.length > 0) {
          await tx`UPDATE kv SET value = ${newValue} WHERE key = ${DISCOVERY_INDEX_KEY}`;
        } else {
          await tx`
            INSERT INTO kv (key, value)
            VALUES (${DISCOVERY_INDEX_KEY}, ${newValue})
            ON CONFLICT (key) DO UPDATE SET value = ${newValue}
          `;
        }

        // Step 6: Write per-entry key for every newly-seeded entry
        for (const entry of newEntries) {
          const perEntryKey = `discovery:${entry.contentKey}`;
          const perEntryValue = JSON.stringify(entry);
          await tx`
            INSERT INTO kv (key, value)
            VALUES (${perEntryKey}, ${perEntryValue})
            ON CONFLICT (key) DO UPDATE SET value = ${perEntryValue}
          `;
        }

        return { success: true, added: newEntries.length, total: updatedEntries.length };
      })
    );

    return result;
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    return { success: false, added: 0, total: 0, error: msg };
  }
}
src/lib/emoji-font.ts
/**
 * Emoji font loader for Satori/next-og image generation
 *
 * Fetches Noto Color Emoji font on-demand and caches it in memory.
 * Use this in any ImageResponse to render emojis properly.
 *
 * Usage:
 *   const fonts = await getEmojiFonts();
 *   new ImageResponse(<div>Hello 👋</div>, { fonts });
 */

// Cache the font data in memory after first fetch
let emojiFont: ArrayBuffer | null = null;
let fontLoadPromise: Promise<ArrayBuffer> | null = null;

// Noto Color Emoji from Google Fonts CDN
// This is a subset that covers most common emojis (~1.5MB)
const EMOJI_FONT_URL = 'https://cdn.jsdelivr.net/npm/@fontsource/noto-color-emoji@5.0.0/files/noto-color-emoji-emoji-400-normal.woff';

// Fallback to Twemoji if Noto fails
const TWEMOJI_FONT_URL = 'https://cdn.jsdelivr.net/npm/twemoji-colr-font@14.0.2/twemoji.woff2';

async function fetchFont(url: string): Promise<ArrayBuffer> {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`Failed to fetch font: ${response.status}`);
  }
  return response.arrayBuffer();
}

/**
 * Load emoji font with caching
 * First call fetches from CDN (~100-200ms), subsequent calls return cached data instantly
 */
export async function loadEmojiFont(): Promise<ArrayBuffer> {
  // Return cached font if available
  if (emojiFont) {
    return emojiFont;
  }

  // If already loading, wait for that promise
  if (fontLoadPromise) {
    return fontLoadPromise;
  }

  // Start loading
  fontLoadPromise = (async () => {
    try {
      console.log('[EmojiFont] Fetching Noto Color Emoji...');
      emojiFont = await fetchFont(EMOJI_FONT_URL);
      console.log('[EmojiFont] Loaded Noto Color Emoji');
      return emojiFont;
    } catch (error) {
      console.warn('[EmojiFont] Noto failed, trying Twemoji fallback...', error);
      try {
        emojiFont = await fetchFont(TWEMOJI_FONT_URL);
        console.log('[EmojiFont] Loaded Twemoji fallback');
        return emojiFont;
      } catch (fallbackError) {
        console.error('[EmojiFont] All emoji fonts failed to load', fallbackError);
        throw fallbackError;
      }
    }
  })();

  return fontLoadPromise;
}

/**
 * Get fonts array for ImageResponse options
 * Includes emoji font for proper emoji rendering
 *
 * Usage:
 *   const fonts = await getEmojiFonts();
 *   new ImageResponse(<Component />, { width: 800, height: 600, fonts });
 */
export async function getEmojiFonts(): Promise<{ name: string; data: ArrayBuffer; style: 'normal'; weight: 400 }[]> {
  try {
    const data = await loadEmojiFont();
    return [
      {
        name: 'Noto Color Emoji',
        data,
        style: 'normal' as const,
        weight: 400 as const,
      },
    ];
  } catch {
    // Return empty array if font loading fails - emojis will show as boxes but app won't crash
    console.warn('[EmojiFont] Proceeding without emoji font');
    return [];
  }
}
src/lib/empty-stub.js
// Empty stub module for aliasing problematic test dependencies
module.exports = {};
src/lib/epub-to-pdf.ts
"use client";

// EPUB to PDF conversion - client-side only
// Uses dynamic imports to avoid SSR bundling issues with jspdf/jszip

export interface EpubConversionProgress {
  stage: "extracting" | "parsing" | "rendering" | "complete" | "error";
  percent: number;
  message: string;
}

export interface EpubConversionResult {
  success: boolean;
  pdfFile?: File;
  error?: string;
  pageCount?: number;
}

interface EpubChapter {
  title: string;
  content: string;
  order: number;
}

/**
 * Convert EPUB file to PDF
 *
 * EPUBs are ZIP files containing:
 * - META-INF/container.xml (points to content.opf)
 * - content.opf (manifest of all files, spine order)
 * - XHTML/HTML chapter files
 * - CSS, images, fonts
 *
 * This converter extracts text content and renders it as a formatted PDF.
 */
export async function convertEpubToPdf(
  epubFile: File,
  onProgress?: (progress: EpubConversionProgress) => void
): Promise<EpubConversionResult> {
  // Ensure we're in browser environment
  if (typeof window === "undefined") {
    return {
      success: false,
      error: "EPUB conversion is only available in browser",
    };
  }

  try {
    // Stage 1: Extract ZIP contents
    onProgress?.({ stage: "extracting", percent: 10, message: "Extracting EPUB contents..." });

    // Dynamic imports - these packages are client-only
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    let JSZip: any;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    let jsPDF: any;

    try {
      JSZip = (await import("jszip")).default;
      const jspdfModule = await import("jspdf");
      jsPDF = jspdfModule.jsPDF;
    } catch (importError) {
      console.error("[epub-to-pdf] Failed to load dependencies:", importError);
      return {
        success: false,
        error: "Failed to load EPUB converter libraries",
      };
    }

    const zip = new JSZip();
    const contents = await zip.loadAsync(epubFile);

    // Stage 2: Parse EPUB structure
    onProgress?.({ stage: "parsing", percent: 30, message: "Parsing EPUB structure..." });

    // Find container.xml to locate the OPF file
    const containerXml = await contents.file("META-INF/container.xml")?.async("string");
    if (!containerXml) {
      throw new Error("Invalid EPUB: Missing container.xml");
    }

    // Extract OPF path from container.xml
    const opfPathMatch = containerXml.match(/full-path="([^"]+\.opf)"/i);
    if (!opfPathMatch) {
      throw new Error("Invalid EPUB: Cannot find OPF file path");
    }

    const opfPath = opfPathMatch[1];
    const opfDir = opfPath.substring(0, opfPath.lastIndexOf("/") + 1);

    // Parse OPF file
    const opfContent = await contents.file(opfPath)?.async("string");
    if (!opfContent) {
      throw new Error("Invalid EPUB: Cannot read OPF file");
    }

    // Extract metadata
    const titleMatch = opfContent.match(/<dc:title[^>]*>([^<]+)<\/dc:title>/i);
    const title = titleMatch ? titleMatch[1].trim() : epubFile.name.replace(/\.epub$/i, "");

    // Extract manifest items (id -> href mapping)
    // Handle both attribute orders: id first or href first
    const manifestItems = new Map<string, string>();
    const itemRegex = /<item\s+([^>]+)>/gi;
    let match;
    while ((match = itemRegex.exec(opfContent)) !== null) {
      const attrs = match[1];
      const idMatch = attrs.match(/id="([^"]+)"/i);
      const hrefMatch = attrs.match(/href="([^"]+)"/i);
      if (idMatch && hrefMatch) {
        // URL-decode the href in case it has encoded characters
        const decodedHref = decodeURIComponent(hrefMatch[1]);
        manifestItems.set(idMatch[1], decodedHref);
      }
    }

    // Extract spine order (reading order of chapters)
    const spineItems: string[] = [];
    const spineRegex = /<itemref[^>]+idref="([^"]+)"[^>]*>/gi;
    while ((match = spineRegex.exec(opfContent)) !== null) {
      spineItems.push(match[1]);
    }

    // Stage 3: Extract chapter content
    onProgress?.({ stage: "parsing", percent: 50, message: "Extracting chapters..." });

    const chapters: EpubChapter[] = [];

    // Helper to resolve paths - handles relative paths, ../, and absolute paths
    const resolvePath = (base: string, href: string): string => {
      // If href starts with /, it's absolute from root
      if (href.startsWith("/")) {
        return href.substring(1);
      }

      // If href has no directory component and base is empty, just use href
      if (!base && !href.includes("/")) {
        return href;
      }

      // Handle ../ in the href
      let baseParts = base.split("/").filter(p => p);
      const hrefParts = href.split("/");

      for (const part of hrefParts) {
        if (part === "..") {
          baseParts.pop();
        } else if (part !== ".") {
          baseParts.push(part);
        }
      }

      return baseParts.join("/");
    };

    // Get all file paths in the ZIP for fallback matching
    const allFilePaths = Object.keys(contents.files).filter(p => !contents.files[p].dir);

    for (let i = 0; i < spineItems.length; i++) {
      const itemId = spineItems[i];
      const href = manifestItems.get(itemId);
      if (!href) continue;

      // Try to find the file using resolved path
      let chapterPath = resolvePath(opfDir, href);
      let chapterContent = await contents.file(chapterPath)?.async("string");

      // Fallback: Try just the href (in case it's already a full path)
      if (!chapterContent && href !== chapterPath) {
        chapterContent = await contents.file(href)?.async("string");
      }

      // Fallback: Search for a file that ends with the href filename
      if (!chapterContent) {
        const hrefFilename = href.split("/").pop() || href;
        const matchingPath = allFilePaths.find(p => p.endsWith(hrefFilename));
        if (matchingPath) {
          chapterContent = await contents.file(matchingPath)?.async("string");
        }
      }

      if (!chapterContent) continue;

      // Extract text from HTML/XHTML
      const text = extractTextFromHtml(chapterContent);
      if (text.trim()) {
        // Try to extract chapter title from h1/h2/h3
        const chapterTitleMatch = chapterContent.match(/<h[123][^>]*>([^<]+)<\/h[123]>/i);
        chapters.push({
          title: chapterTitleMatch ? chapterTitleMatch[1].trim() : `Chapter ${i + 1}`,
          content: text,
          order: i,
        });
      }
    }

    // If spine-based extraction failed, try direct content extraction from all HTML/XHTML files
    if (chapters.length === 0) {
      console.log("[epub-to-pdf] Spine extraction failed, trying direct content extraction...");

      const htmlFiles = allFilePaths.filter(p =>
        p.endsWith(".html") || p.endsWith(".xhtml") || p.endsWith(".htm")
      ).sort();

      for (let i = 0; i < htmlFiles.length; i++) {
        const content = await contents.file(htmlFiles[i])?.async("string");
        if (!content) continue;

        const text = extractTextFromHtml(content);
        if (text.trim() && text.length > 100) { // Minimum content threshold
          const titleMatch = content.match(/<h[123][^>]*>([^<]+)<\/h[123]>/i);
          chapters.push({
            title: titleMatch ? titleMatch[1].trim() : `Section ${i + 1}`,
            content: text,
            order: i,
          });
        }
      }
    }

    if (chapters.length === 0) {
      throw new Error("No readable content found in EPUB");
    }

    // Stage 4: Render to PDF
    onProgress?.({ stage: "rendering", percent: 70, message: "Generating PDF..." });

    const pdf = new jsPDF({
      orientation: "portrait",
      unit: "pt",  // Use points for precise typography
      format: "letter",  // 612x792 pt - better for reading
      putOnlyUsedFonts: true,
      compress: true,
    });

    const pageWidth = pdf.internal.pageSize.getWidth();  // 612 pt
    const pageHeight = pdf.internal.pageSize.getHeight(); // 792 pt
    const margin = 72; // 1 inch margins
    const contentWidth = pageWidth - margin * 2; // ~468 pt
    const fontSize = 12; // Standard readable size
    const lineHeight = fontSize * 1.5; // 18pt - comfortable line spacing
    const titleFontSize = 24;
    const chapterFontSize = 18;
    const paragraphSpacing = fontSize * 0.8; // Space between paragraphs

    // Add title page
    pdf.setFontSize(titleFontSize);
    pdf.setFont("helvetica", "bold");
    const titleLines = pdf.splitTextToSize(title, contentWidth);
    pdf.text(titleLines, pageWidth / 2, pageHeight / 3, { align: "center" });

    pdf.setFontSize(11);
    pdf.setFont("helvetica", "italic");
    pdf.text("Converted from EPUB", pageWidth / 2, pageHeight / 3 + 50, { align: "center" });

    // Render each chapter
    for (let chapterIdx = 0; chapterIdx < chapters.length; chapterIdx++) {
      const chapter = chapters[chapterIdx];

      // Update progress
      const progressPercent = 70 + Math.floor((chapterIdx / chapters.length) * 25);
      onProgress?.({
        stage: "rendering",
        percent: progressPercent,
        message: `Rendering chapter ${chapterIdx + 1} of ${chapters.length}...`
      });

      // New page for each chapter
      pdf.addPage();

      let y = margin;

      // Chapter title
      pdf.setFontSize(chapterFontSize);
      pdf.setFont("helvetica", "bold");
      const chapterTitleLines = pdf.splitTextToSize(chapter.title, contentWidth);
      pdf.text(chapterTitleLines, margin, y);
      y += chapterTitleLines.length * chapterFontSize * 1.3 + 24; // Proper title spacing

      // Chapter content
      pdf.setFontSize(fontSize);
      pdf.setFont("helvetica", "normal");

      // Split content into paragraphs
      const paragraphs = chapter.content.split(/\n\n+/);

      for (const paragraph of paragraphs) {
        if (!paragraph.trim()) continue;

        const lines = pdf.splitTextToSize(paragraph.trim(), contentWidth);

        for (const line of lines) {
          // Check if we need a new page
          if (y + lineHeight > pageHeight - margin) {
            pdf.addPage();
            y = margin;
          }

          pdf.text(line, margin, y);
          y += lineHeight;
        }

        // Paragraph spacing
        y += paragraphSpacing;
      }
    }

    // Add page numbers
    const totalPages = pdf.getNumberOfPages();
    for (let i = 1; i <= totalPages; i++) {
      pdf.setPage(i);
      pdf.setFontSize(10);
      pdf.setFont("helvetica", "normal");
      pdf.text(`${i} / ${totalPages}`, pageWidth / 2, pageHeight - 36, { align: "center" });
    }

    // Convert to Blob and File
    const pdfBlob = pdf.output("blob");
    const pdfFileName = epubFile.name.replace(/\.epub$/i, ".pdf");
    const pdfFile = new File([pdfBlob], pdfFileName, { type: "application/pdf" });

    onProgress?.({ stage: "complete", percent: 100, message: "Conversion complete!" });

    return {
      success: true,
      pdfFile,
      pageCount: totalPages,
    };

  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "Unknown error during conversion";
    onProgress?.({ stage: "error", percent: 0, message: errorMessage });
    return {
      success: false,
      error: errorMessage,
    };
  }
}

/**
 * Extract plain text from HTML/XHTML content
 */
function extractTextFromHtml(html: string): string {
  // Remove script and style tags completely
  let text = html.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "");
  text = text.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "");

  // Convert common block elements to line breaks
  text = text.replace(/<\/?(p|div|br|h[1-6]|li|tr)[^>]*>/gi, "\n");

  // Convert list items with bullet
  text = text.replace(/<li[^>]*>/gi, "\n• ");

  // Remove remaining HTML tags
  text = text.replace(/<[^>]+>/g, "");

  // Decode HTML entities
  text = decodeHtmlEntities(text);

  // Clean up whitespace
  text = text.replace(/[ \t]+/g, " ");
  text = text.replace(/\n{3,}/g, "\n\n");
  text = text.trim();

  return text;
}

/**
 * Decode common HTML entities
 */
function decodeHtmlEntities(text: string): string {
  const entities: Record<string, string> = {
    "&nbsp;": " ",
    "&amp;": "&",
    "&lt;": "<",
    "&gt;": ">",
    "&quot;": '"',
    "&apos;": "'",
    "&#39;": "'",
    "&mdash;": "—",
    "&ndash;": "–",
    "&hellip;": "...",
    "&ldquo;": '"',
    "&rdquo;": '"',
    "&lsquo;": "'",
    "&rsquo;": "'",
    "&copy;": "©",
    "&reg;": "®",
    "&trade;": "™",
    "&deg;": "°",
    "&frac12;": "½",
    "&frac14;": "¼",
    "&frac34;": "¾",
  };

  let result = text;
  for (const [entity, char] of Object.entries(entities)) {
    result = result.replace(new RegExp(entity, "gi"), char);
  }

  // Handle numeric entities
  result = result.replace(/&#(\d+);/g, (_, code) => String.fromCharCode(parseInt(code, 10)));
  result = result.replace(/&#x([0-9a-f]+);/gi, (_, code) => String.fromCharCode(parseInt(code, 16)));

  return result;
}

/**
 * Check if a file is an EPUB
 */
export function isEpubFile(file: File): boolean {
  return file.name.toLowerCase().endsWith(".epub") ||
         file.type === "application/epub+zip";
}
src/lib/error-codes.ts
/**
 * Error Code System for Net Library
 *
 * User-friendly error messages with error codes for debugging.
 * When a user reports an error, the code helps identify the issue quickly.
 *
 * Format: NL-XXXX where XX is category and XX is specific error
 * - NL-01XX: Upload errors
 * - NL-02XX: Content loading errors
 * - NL-03XX: Wallet/transaction errors
 * - NL-04XX: Network/API errors
 * - NL-05XX: Storage errors
 */

import { createLogger } from "@/lib/logger";

export interface AppError {
  code: string;
  message: string; // User-friendly message
  technicalDetails?: string; // For console logging
}

// Error code mappings - add patterns to match and their friendly messages
const ERROR_PATTERNS: Array<{
  pattern: RegExp | string;
  code: string;
  message: string;
}> = [
  // Upload errors (NL-01XX)
  { pattern: /file.*too large/i, code: "NL-0101", message: "File is too large. Maximum size is 80MB." },
  { pattern: /insufficient.*usdc/i, code: "NL-0102", message: "Not enough USDC to complete upload." },
  { pattern: /upload.*cancelled/i, code: "NL-0103", message: "Upload was cancelled." },
  { pattern: /session.*failed/i, code: "NL-0104", message: "Failed to start upload session. Try again." },
  { pattern: /session.*expired/i, code: "NL-0105", message: "Upload session expired. Try again." },
  { pattern: /duplicate/i, code: "NL-0106", message: "This file has already been uploaded." },

  // Content loading errors (NL-02XX)
  { pattern: /failed to fetch.*pdf/i, code: "NL-0201", message: "Unable to load PDF. Try again." },
  { pattern: /failed to load.*content/i, code: "NL-0202", message: "Unable to load content. Try again." },
  { pattern: /content.*not found/i, code: "NL-0203", message: "Content not found. It may have been removed." },
  { pattern: /failed to fetch.*metadata/i, code: "NL-0204", message: "Unable to load file info. Try again." },
  { pattern: /chunk.*failed/i, code: "NL-0205", message: "Unable to load part of the file. Try again." },

  // Wallet/transaction errors (NL-03XX)
  { pattern: /wallet.*not.*connected/i, code: "NL-0301", message: "Please connect your wallet." },
  { pattern: /user.*rejected/i, code: "NL-0302", message: "Transaction was cancelled." },
  { pattern: /user.*denied/i, code: "NL-0302", message: "Transaction was cancelled." },
  { pattern: /user.*cancelled/i, code: "NL-0302", message: "Transaction was cancelled." },
  { pattern: /insufficient.*funds/i, code: "NL-0303", message: "Not enough funds in wallet." },
  { pattern: /transaction.*failed/i, code: "NL-0304", message: "Transaction failed. Try again." },
  { pattern: /funding.*failed/i, code: "NL-0305", message: "Unable to add funds. Try again." },
  { pattern: /funding.*timed out/i, code: "NL-0306", message: "Funding timed out. Check wallet balance." },

  // Network/API errors (NL-04XX)
  { pattern: /network.*error/i, code: "NL-0401", message: "Network error. Check your connection." },
  { pattern: /failed to fetch/i, code: "NL-0402", message: "Unable to connect. Try again." },
  { pattern: /timeout/i, code: "NL-0403", message: "Request timed out. Try again." },
  { pattern: /503|service unavailable/i, code: "NL-0404", message: "Service temporarily unavailable. Try again later." },
  { pattern: /500|internal server/i, code: "NL-0405", message: "Server error. Try again later." },
  { pattern: /429|too many requests/i, code: "NL-0406", message: "Too many requests. Wait a moment and try again." },

  // Storage errors (NL-05XX)
  { pattern: /storage.*full/i, code: "NL-0501", message: "Storage is full." },
  { pattern: /indexer.*slow/i, code: "NL-0502", message: "Content is being processed. Try again shortly." },
  { pattern: /verification.*failed/i, code: "NL-0503", message: "Unable to verify upload. Try again." },
];

/**
 * Convert a technical error to a user-friendly error with code
 */
export function createAppError(error: unknown): AppError {
  const technicalDetails = error instanceof Error ? error.message : String(error);

  // Try to match against known patterns
  for (const { pattern, code, message } of ERROR_PATTERNS) {
    const regex = typeof pattern === "string" ? new RegExp(pattern, "i") : pattern;
    if (regex.test(technicalDetails)) {
      return { code, message, technicalDetails };
    }
  }

  // Default error for unmatched cases
  return {
    code: "NL-0000",
    message: "Something went wrong. Please try again.",
    technicalDetails,
  };
}

/**
 * Format error for display - shows user message with error code subtitle
 */
export function formatErrorForDisplay(error: AppError): { title: string; subtitle: string } {
  return {
    title: error.message,
    subtitle: `Error code: ${error.code}`,
  };
}

/**
 * Log error with technical details (for debugging)
 */
export function logAppError(context: string, error: AppError): void {
  const log = createLogger(context);
  log.error(`${error.code}: ${error.message}`, error.technicalDetails);
}

/**
 * Quick helper to convert and log an error in one call
 */
export function handleError(context: string, error: unknown): AppError {
  const appError = createAppError(error);
  logAppError(context, appError);
  return appError;
}
src/lib/logger.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Simple logging utility for consistent log output across the app.
 *
 * Benefits:
 * - Consistent prefix format: [MODULE] message
 * - Log levels that can be controlled via environment
 * - Structured data logging
 * - Easy to grep/filter logs
 *
 * Usage:
 *   import { createLogger } from "@/lib/logger";
 *   const log = createLogger("upload-tab");
 *   log.info("Upload started", { fileName: "test.pdf" });
 *   log.error("Upload failed", error);
 *   log.warn("Low balance");
 *   log.debug("Chunk uploaded", { chunkIndex: 5 });
 */

type LogLevel = "debug" | "info" | "warn" | "error";

// Log level hierarchy for filtering
const LOG_LEVELS: Record<LogLevel, number> = {
  debug: 0,
  info: 1,
  warn: 2,
  error: 3,
};

// Get minimum log level from environment (default: info in prod, debug in dev)
function getMinLevel(): LogLevel {
  if (typeof window !== "undefined") {
    // Client-side: check localStorage for debug override
    try {
      const override = localStorage.getItem("NET_LOG_LEVEL");
      if (override && override in LOG_LEVELS) {
        return override as LogLevel;
      }
    } catch {
      // localStorage not available
    }
  }

  // Default: debug in development, info in production
  return process.env.NODE_ENV === "development" ? "debug" : "info";
}

// Check if we should log at this level
function shouldLog(level: LogLevel): boolean {
  const minLevel = getMinLevel();
  return LOG_LEVELS[level] >= LOG_LEVELS[minLevel];
}

// Format log message with module prefix
function formatMessage(module: string, message: string): string {
  return `[${module}] ${message}`;
}

// Format data for logging (handle errors, objects, etc.)
function formatData(data?: unknown): unknown {
  if (data === undefined) return undefined;

  if (data instanceof Error) {
    return {
      name: data.name,
      message: data.message,
      stack: data.stack?.split("\n").slice(0, 3).join("\n"),
    };
  }

  return data;
}

export interface Logger {
  debug: (message: string, data?: unknown) => void;
  info: (message: string, data?: unknown) => void;
  warn: (message: string, data?: unknown) => void;
  error: (message: string, data?: unknown) => void;
  /** Create a child logger with a sub-module prefix */
  child: (subModule: string) => Logger;
}

/**
 * Create a logger instance for a module.
 *
 * @param module - Module name (e.g., "upload-tab", "relay", "discovery")
 * @returns Logger instance with debug, info, warn, error methods
 */
export function createLogger(module: string): Logger {
  const log = (level: LogLevel, message: string, data?: unknown) => {
    if (!shouldLog(level)) return;

    const formatted = formatMessage(module, message);
    const formattedData = formatData(data);

    switch (level) {
      case "debug":
        if (formattedData !== undefined) {
          console.log(formatted, formattedData);
        } else {
          console.log(formatted);
        }
        break;
      case "info":
        if (formattedData !== undefined) {
          console.log(formatted, formattedData);
        } else {
          console.log(formatted);
        }
        break;
      case "warn":
        if (formattedData !== undefined) {
          console.warn(formatted, formattedData);
        } else {
          console.warn(formatted);
        }
        break;
      case "error":
        if (formattedData !== undefined) {
          console.error(formatted, formattedData);
        } else {
          console.error(formatted);
        }
        break;
    }
  };

  return {
    debug: (message: string, data?: unknown) => log("debug", message, data),
    info: (message: string, data?: unknown) => log("info", message, data),
    warn: (message: string, data?: unknown) => log("warn", message, data),
    error: (message: string, data?: unknown) => log("error", message, data),
    child: (subModule: string) => createLogger(`${module}:${subModule}`),
  };
}

/**
 * Quick one-off logging with a module prefix.
 * Use createLogger() for repeated logging in a module.
 */
export const log = {
  debug: (module: string, message: string, data?: unknown) =>
    createLogger(module).debug(message, data),
  info: (module: string, message: string, data?: unknown) =>
    createLogger(module).info(message, data),
  warn: (module: string, message: string, data?: unknown) =>
    createLogger(module).warn(message, data),
  error: (module: string, message: string, data?: unknown) =>
    createLogger(module).error(message, data),
};
src/lib/media-type-detector.ts
// Media Type Detection Utility
// Detects the actual file type from raw content, handling multiple encodings (hex, base64, raw binary)

export type DetectedMediaType = "pdf" | "image" | "audio" | "video" | "text" | "unknown";

interface MagicBytes {
  bytes: number[];
  offset?: number;
  type: DetectedMediaType;
  subCheck?: (buffer: Buffer) => DetectedMediaType | null;
}

// Magic byte signatures for common file types
const MAGIC_SIGNATURES: MagicBytes[] = [
  // PDF: %PDF
  { bytes: [0x25, 0x50, 0x44, 0x46], type: "pdf" },

  // Audio formats
  // MP3: ID3 tag
  { bytes: [0x49, 0x44, 0x33], type: "audio" },
  // MP3: MPEG frame sync (various forms)
  { bytes: [0xFF, 0xFB], type: "audio" },
  { bytes: [0xFF, 0xFA], type: "audio" },
  { bytes: [0xFF, 0xF3], type: "audio" },
  { bytes: [0xFF, 0xF2], type: "audio" },
  { bytes: [0xFF, 0xE3], type: "audio" },
  // WAV: RIFF + WAVE
  {
    bytes: [0x52, 0x49, 0x46, 0x46],
    type: "audio",
    subCheck: (buffer) => {
      if (buffer.length > 11) {
        const subtype = buffer.slice(8, 12).toString("ascii");
        if (subtype === "WAVE") return "audio";
        if (subtype === "WEBP") return "image";
        if (subtype === "AVI ") return "video";
      }
      return null;
    },
  },
  // OGG: OggS (can be audio or video)
  { bytes: [0x4F, 0x67, 0x67, 0x53], type: "audio" },
  // FLAC: fLaC
  { bytes: [0x66, 0x4C, 0x61, 0x43], type: "audio" },

  // Video formats
  // MP4/M4A/MOV: ftyp at offset 4
  {
    bytes: [0x66, 0x74, 0x79, 0x70],
    offset: 4,
    type: "video",
    subCheck: (buffer) => {
      if (buffer.length > 11) {
        const subtype = buffer.slice(8, 12).toString("ascii");
        // M4A is audio, everything else is video
        if (subtype.includes("M4A") || subtype.includes("mp4a") || subtype.toLowerCase().includes("m4a")) {
          return "audio";
        }
      }
      return "video";
    },
  },
  // WebM: EBML header
  { bytes: [0x1A, 0x45, 0xDF, 0xA3], type: "video" },

  // Image formats
  // PNG
  { bytes: [0x89, 0x50, 0x4E, 0x47], type: "image" },
  // JPEG
  { bytes: [0xFF, 0xD8, 0xFF], type: "image" },
  // GIF87a/GIF89a
  { bytes: [0x47, 0x49, 0x46, 0x38], type: "image" },
  // BMP
  { bytes: [0x42, 0x4D], type: "image" },
  // WebP is handled by RIFF subCheck above
];

/**
 * Try to decode data from various encodings to get raw bytes
 * Handles: hex (0x...), base64, and raw binary
 */
export function decodeToBuffer(data: string): Buffer | null {
  if (!data || data.length === 0) return null;

  // Check if hex encoded (starts with 0x)
  if (data.startsWith("0x")) {
    try {
      const cleanHex = data.slice(2);
      return Buffer.from(cleanHex, "hex");
    } catch {
      return null;
    }
  }

  // Check if it looks like base64 (no spaces, alphanumeric + /+=)
  const looksLikeBase64 = /^[A-Za-z0-9+/]+=*$/.test(data.trim()) && !data.includes(" ");
  if (looksLikeBase64 && data.length > 20) {
    try {
      const decoded = Buffer.from(data.trim(), "base64");
      // Validate it decoded to something reasonable
      if (decoded.length > 0 && decoded.length < data.length) {
        return decoded;
      }
    } catch {
      // Not valid base64
    }
  }

  // Try as raw binary (string to buffer)
  try {
    return Buffer.from(data, "binary");
  } catch {
    return null;
  }
}

/**
 * Detect media type from a Buffer using magic bytes
 */
export function detectFromBuffer(buffer: Buffer): DetectedMediaType {
  if (!buffer || buffer.length < 4) {
    return "unknown";
  }

  // Check each magic signature
  for (const sig of MAGIC_SIGNATURES) {
    const offset = sig.offset || 0;
    if (buffer.length < offset + sig.bytes.length) continue;

    let matches = true;
    for (let i = 0; i < sig.bytes.length; i++) {
      if (buffer[offset + i] !== sig.bytes[i]) {
        matches = false;
        break;
      }
    }

    if (matches) {
      // If there's a subCheck, use it for more specific detection
      if (sig.subCheck) {
        const subResult = sig.subCheck(buffer);
        if (subResult) return subResult;
      }
      return sig.type;
    }
  }

  // Check if it's readable text
  const sample = buffer.slice(0, Math.min(1000, buffer.length));
  const printableCount = sample.filter(
    (b) => (b >= 0x20 && b <= 0x7E) || b === 0x0A || b === 0x0D || b === 0x09
  ).length;
  const printableRatio = printableCount / sample.length;

  if (printableRatio > 0.85) {
    return "text";
  }

  return "unknown";
}

/**
 * Detect media type from raw data string (handles any encoding)
 */
export function detectMediaType(data: string): DetectedMediaType {
  const buffer = decodeToBuffer(data);
  if (!buffer) return "unknown";
  return detectFromBuffer(buffer);
}

/**
 * Check if data starts with common base64 prefixes for specific file types
 * This is a quick check before full decoding
 */
export function quickDetectFromBase64Prefix(data: string): DetectedMediaType | null {
  const trimmed = data.trim();

  // PDF in base64 starts with "JVBERi" (%PDF)
  if (trimmed.startsWith("JVBERi")) return "pdf";

  // PNG in base64 starts with "iVBORw0KGgo" (‰PNG)
  if (trimmed.startsWith("iVBORw0KGgo")) return "image";

  // JPEG in base64 starts with "/9j/" (ÿØÿ)
  if (trimmed.startsWith("/9j/")) return "image";

  // GIF in base64 starts with "R0lGOD" (GIF8)
  if (trimmed.startsWith("R0lGOD")) return "image";

  // MP3 with ID3 tag in base64 starts with "SUQz" (ID3)
  if (trimmed.startsWith("SUQz")) return "audio";

  // WAV in base64 starts with "UklGR" (RIFF)
  if (trimmed.startsWith("UklGR")) {
    // Could be WAV, WEBP, or AVI - need to decode to check
    return null;
  }

  return null;
}
src/lib/net-protocol.ts
// Net Protocol SDK - Official library integration
import {
  StorageClient,
  STORAGE_CONTRACT,
  CHUNKED_STORAGE_CONTRACT,
  getStorageKeyBytes,
  chunkDataForStorage,
  // New in v0.1.7 - file type detection utilities
  fileToDataUri,
  detectFileTypeFromBase64,
  base64ToDataUri,
} from "@net-protocol/storage";
import {
  NetClient,
} from "@net-protocol/core";
import { keccak256, encodePacked, stringToHex } from "viem";

// Base chain ID
export const BASE_CHAIN_ID = 8453;

// Re-export contract info from official SDK
export const STORAGE_CONTRACT_ADDRESS = STORAGE_CONTRACT.address;
export const CHUNKED_STORAGE_ADDRESS = CHUNKED_STORAGE_CONTRACT.address;
export const STORAGE_ABI = STORAGE_CONTRACT.abi;
export const CHUNKED_STORAGE_ABI = CHUNKED_STORAGE_CONTRACT.abi;

// Initialize clients
export function createStorageClient(chainId: number = BASE_CHAIN_ID) {
  return new StorageClient({ chainId });
}

export function createNetClient(chainId: number = BASE_CHAIN_ID) {
  return new NetClient({ chainId });
}

// Generate a storage key from a string (using official SDK)
export function generateStorageKey(keyString: string): `0x${string}` {
  return getStorageKeyBytes(keyString, "raw") as `0x${string}`;
}

// Media type detection from MIME type
export type MediaType = "pdf" | "image" | "audio" | "video" | "text" | "unknown";

/**
 * Detect media type from a file's MIME type
 * Used to properly handle multimedia content (audio, video, images, etc.)
 */
export function detectMediaTypeFromMime(mimeType: string): MediaType {
  if (!mimeType) return "unknown";

  if (mimeType === "application/pdf") return "pdf";
  if (mimeType.startsWith("image/")) return "image";
  if (mimeType.startsWith("audio/")) return "audio";
  if (mimeType.startsWith("video/")) return "video";
  if (mimeType.startsWith("text/") || mimeType === "application/json" || mimeType === "application/xml") return "text";

  // EPUB → converted to PDF before upload
  if (mimeType === "application/epub+zip") return "pdf";

  // Microsoft Office / open XML — all converted to HTML/text before upload
  if (mimeType === "application/msword") return "text"; // .doc
  if (mimeType === "application/vnd.openxmlformats-officedocument.wordprocessingml.document") return "text"; // .docx
  if (mimeType === "application/vnd.ms-excel") return "text"; // .xls
  if (mimeType === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") return "text"; // .xlsx
  if (mimeType === "application/vnd.ms-powerpoint") return "text"; // .ppt
  if (mimeType === "application/vnd.openxmlformats-officedocument.presentationml.presentation") return "text"; // .pptx
  if (mimeType === "application/rtf" || mimeType === "text/rtf") return "text"; // .rtf

  return "unknown";
}

/**
 * Detect media type from a file's extension (fallback if MIME type isn't reliable)
 */
export function detectMediaTypeFromExtension(filename: string): MediaType {
  const ext = filename.toLowerCase().split(".").pop() || "";

  // Audio extensions
  if (["mp3", "wav", "ogg", "flac", "m4a", "aac", "wma", "aiff"].includes(ext)) return "audio";

  // Video extensions
  if (["mp4", "webm", "mov", "avi", "mkv", "wmv", "flv", "m4v"].includes(ext)) return "video";

  // Image extensions
  if (["png", "jpg", "jpeg", "gif", "webp", "svg", "bmp", "ico", "tiff"].includes(ext)) return "image";

  // Text / document extensions (including Office formats converted to text/html before storage)
  if (["txt", "md", "markdown", "html", "htm", "json", "xml", "csv", "log", "rtf",
       "doc", "docx", "xls", "xlsx", "ppt", "pptx"].includes(ext)) return "text";

  // PDF
  if (ext === "pdf") return "pdf";

  return "unknown";
}

// Generate a unique key for a book based on title and uploader
export function generateBookKey(title: string, uploaderAddress: string): `0x${string}` {
  const normalized = title.toLowerCase().trim();
  return keccak256(encodePacked(["string", "address"], [normalized, uploaderAddress as `0x${string}`]));
}

// Generate CDN URL for stored content - USER-FACING format
// Uses /storage/load/ endpoint which returns actual file content (not JSON)
// This is the correct format for sharing and displaying content to users
export function getCdnUrl(
  chainId: number,
  operatorAddress: string,
  key: string,
  storageType: "regular" | "chunked" | "xml" = "regular",
  filename?: string
): string {
  // Chunked storage uses a different endpoint
  if (storageType === "chunked") {
    // For chunked storage, use /chunked-storage/file/ which returns actual content
    return `https://storedon.net/net/${chainId}/chunked-storage/file/${operatorAddress}/${key}`;
  }

  // For regular/XML storage with filename, use /storage/load/ (user-friendly, returns actual file)
  // This is the correct format that works - tested with Aspyn's example
  if (filename) {
    const encodedFilename = encodeURIComponent(filename);
    return `https://storedon.net/net/${chainId}/storage/load/${operatorAddress}/${encodedFilename}`;
  }

  // For hex-encoded keys (relay uploads via relay-upload.ts), the content is stored as
  // base64 inside a JSON envelope at /storage/raw/{operator}/{hexKey}.
  // /storage/load/ with the decoded filename 404s for these — the storage contract
  // indexes by the original hex key, not by the human-readable decoded name.
  // book-content/route.ts fetches and decodes these correctly via storage/raw/.
  if (key.startsWith("0x") && /^0x[0-9a-fA-F]+$/.test(key)) {
    return `https://storedon.net/net/${chainId}/storage/raw/${operatorAddress}/${key}`;
  }

  // For non-hex keys stored via API (e.g. "netlib-api-ref-v2"), try decoding to a
  // human-readable filename and use /storage/load/ which returns actual file content.
  const decodedKey = decodeBytes32Key(key);
  if (decodedKey) {
    return `https://storedon.net/net/${chainId}/storage/load/${operatorAddress}/${encodeURIComponent(decodedKey)}`;
  }

  // Final fallback: /storage/raw/
  return `https://storedon.net/net/${chainId}/storage/raw/${operatorAddress}/${key}`;
}

// Generate user-friendly CDN URL using filename
// PREFERRED: Use this for all user-facing URLs (sharing, display, etc.)
export function getUserFriendlyCdnUrl(
  chainId: number,
  operatorAddress: string,
  filename: string
): string {
  const encodedFilename = encodeURIComponent(filename);
  return `https://storedon.net/net/${chainId}/storage/load/${operatorAddress}/${encodedFilename}`;
}

// Get raw storage URL (returns JSON with key, text, data)
export function getRawStorageUrl(
  chainId: number,
  operatorAddress: string,
  key: string
): string {
  return `https://storedon.net/net/${chainId}/storage/raw/${operatorAddress}/${key}`;
}

/**
 * Attempt to decode a bytes32 hex key back to a human-readable storage key.
 *
 * When items are stored with a key ≤ 32 chars (e.g. "netlib-api-ref-v2"), the protocol
 * encodes the key as a right-zero-padded bytes32 hex string.  The content is accessible
 * via /storage/load/{operator}/{key} but NOT via /storage/raw/{operator}/{bytes32hex}.
 *
 * Returns the decoded string if it is valid printable ASCII, length 1-32.
 * Returns null if the input is not a recognisable bytes32 or doesn't decode cleanly.
 */
export function decodeBytes32Key(key: string): string | null {
  // Must look like a bytes32 hex string: 0x + 64 hex chars
  if (!/^0x[0-9a-f]{64}$/i.test(key)) return null;

  const hex = key.slice(2); // strip 0x
  let decoded = "";
  for (let i = 0; i < 64; i += 2) {
    const code = parseInt(hex.slice(i, i + 2), 16);
    if (code === 0) continue; // skip null padding
    // Only allow printable ASCII (0x20–0x7e)
    if (code < 0x20 || code > 0x7e) return null;
    decoded += String.fromCharCode(code);
  }

  // Valid: 1-32 printable ASCII characters, no leading/trailing whitespace
  if (decoded.length === 0 || decoded.length > 32) return null;
  if (decoded !== decoded.trim()) return null;

  return decoded;
}

// Determine which storage type to use based on file size
export function getStorageType(fileSize: number): "regular" | "chunked" | "xml" {
  if (fileSize < 20000) {
    return "regular";
  }
  if (fileSize < 80000) {
    return "chunked";
  }
  return "xml";
}

// XML chunk for large file storage
export interface XmlChunk {
  key: `0x${string}`;
  // Store as hex strings directly to avoid double-conversion
  compressedChunks: `0x${string}`[];
}

// Helper to convert binary data to base64 for SDK chunking
function uint8ArrayToBase64(data: Uint8Array): string {
  let binary = '';
  for (let i = 0; i < data.length; i++) {
    binary += String.fromCharCode(data[i]);
  }
  return btoa(binary);
}

// Free tier limits - tiered by membership
export const FREE_TIER_MEMBER_MAX_SIZE = 15 * 1024 * 1024; // 15MB for members
export const FREE_TIER_NON_MEMBER_MAX_SIZE = 200 * 1024; // 200KB for non-members

// Premium upload limit (100MB) - paid tier for members uploading files over 15MB
export const PREMIUM_MAX_SIZE = 100 * 1024 * 1024; // 100MB

// Premium upload pricing (members only - non-members must become members first)
export const PREMIUM_PRICE_PER_MB = 1; // $1 per MB over 15MB for members

// Legacy exports for compatibility
export const FREE_TIER_MAX_SIZE = FREE_TIER_MEMBER_MAX_SIZE;
export const MAX_FILE_SIZE = PREMIUM_MAX_SIZE;

// Get the free tier limit based on membership status
export function getFreeTierLimit(isMember: boolean): number {
  return isMember ? FREE_TIER_MEMBER_MAX_SIZE : FREE_TIER_NON_MEMBER_MAX_SIZE;
}

// Calculate premium upload fee in USD (only applies to members for files over 15MB)
export function calculatePremiumFee(fileSize: number): number {
  if (fileSize <= FREE_TIER_MEMBER_MAX_SIZE) {
    return 0;
  }
  const excessBytes = fileSize - FREE_TIER_MEMBER_MAX_SIZE;
  const excessMB = excessBytes / (1024 * 1024);
  return Math.ceil(excessMB) * PREMIUM_PRICE_PER_MB;
}

// Check if file requires premium upload (paid) - only for members with files over 15MB
export function requiresPremiumUpload(fileSize: number, isMember: boolean): boolean {
  // Non-members can't upload over 200KB at all (must become member)
  // Members can upload up to 15MB free, then pay for larger
  if (!isMember) {
    return false; // Non-members don't pay premium - they just can't upload large files
  }
  return fileSize > FREE_TIER_MEMBER_MAX_SIZE;
}

// Check if file exceeds non-member limit (requires membership)
export function requiresMembership(fileSize: number, isMember: boolean): boolean {
  if (isMember) return false;
  return fileSize > FREE_TIER_NON_MEMBER_MAX_SIZE;
}

// Treasury address for premium upload payments (same as membership treasury)
export const PREMIUM_UPLOAD_TREASURY = "0xAcAD71e697Ef3bb148093b2DD2fCf0845e957627" as const;

// Transaction config for uploads (matches SDK WriteTransactionConfig)
export interface UploadTransactionConfig {
  to: `0x${string}`;
  functionName: string;
  args: unknown[];
  // For tracking which chunk this is (XML uploads have multiple txs)
  chunkIndex?: number;
  isMetadata?: boolean;
}

// Prepared upload result - ready to be executed
export interface PreparedUpload {
  storageType: "regular" | "chunked" | "xml";
  // Top-level storage key (use this to retrieve content later)
  topLevelKey: `0x${string}`;
  // Filename for display
  filename: string;
  // Raw file data
  data: Uint8Array;
  // Transaction configs to execute (in order)
  transactionConfigs: UploadTransactionConfig[];
  // For XML storage: chunk keys for progress tracking (derived from content hash, deterministic)
  chunkKeys?: `0x${string}`[];
  // XML metadata string (for reference)
  xmlMetadata?: string;
}

// Prepare file for upload using official SDK
// Returns transaction configs ready to be executed
export async function prepareFileForUpload(
  file: File,
  operatorAddress: string
): Promise<PreparedUpload> {
  // Check file size limit
  if (file.size > MAX_FILE_SIZE) {
    throw new Error(`File too large. Maximum size is ${MAX_FILE_SIZE / 1024 / 1024}MB. Your file is ${(file.size / 1024 / 1024).toFixed(1)}MB.`);
  }

  const arrayBuffer = await file.arrayBuffer();
  const data = new Uint8Array(arrayBuffer);
  const storageType = getStorageType(data.length);

  // For binary files (like PDFs), convert to base64 for SDK chunking
  const dataAsBase64 = uint8ArrayToBase64(data);

  // Create storage client
  const storageClient = createStorageClient(BASE_CHAIN_ID);

  if (storageType === "regular") {
    // Small files: single Storage.put() call
    const timestamp = Date.now();
    const key = generateStorageKey(`netlib-${file.name}-${timestamp}`);
    const valueHex = stringToHex(dataAsBase64);

    const config = storageClient.preparePut({
      key,
      text: file.name,
      value: valueHex,
    });

    return {
      storageType,
      topLevelKey: key,
      filename: file.name,
      data,
      transactionConfigs: [{
        to: config.to,
        functionName: config.functionName,
        args: config.args,
        isMetadata: true,
      }],
    };
  }

  if (storageType === "chunked") {
    // Medium files: single ChunkedStorage.put() call with compressed chunks
    const timestamp = Date.now();
    const key = generateStorageKey(`netlib-${file.name}-${timestamp}`);
    const chunks = chunkDataForStorage(dataAsBase64);

    const config = storageClient.prepareChunkedPut({
      key,
      text: file.name,
      chunks,
    });

    return {
      storageType,
      topLevelKey: key,
      filename: file.name,
      data,
      transactionConfigs: [{
        to: config.to,
        functionName: config.functionName,
        args: config.args,
        isMetadata: true,
      }],
    };
  }

  // XML Storage for large files (>80KB)
  // Use SDK's prepareXmlStorage which:
  // 1. Splits data into 80KB chunks
  // 2. Compresses each chunk via gzip
  // 3. Generates content-hash-based keys (deterministic!)
  // 4. Creates proper transaction configs
  const result = storageClient.prepareXmlStorage({
    data: dataAsBase64,
    operatorAddress: operatorAddress as `0x${string}`,
    filename: file.name,
    useChunkedStorageBackend: true, // Use ChunkedStorage for each XML chunk
  });

  // Extract chunk keys from transaction configs for progress tracking
  // The first tx is metadata, rest are chunk uploads
  const chunkKeys: `0x${string}`[] = [];
  const transactionConfigs: UploadTransactionConfig[] = [];

  for (let i = 0; i < result.transactionConfigs.length; i++) {
    const config = result.transactionConfigs[i];
    const isMetadata = i === 0; // First tx is metadata

    transactionConfigs.push({
      to: config.to,
      functionName: config.functionName,
      args: config.args,
      chunkIndex: isMetadata ? undefined : i - 1, // 0-indexed chunk number
      isMetadata,
    });

    // Extract chunk key from args (first arg is the key)
    if (!isMetadata && config.args[0]) {
      chunkKeys.push(config.args[0] as `0x${string}`);
    }
  }

  return {
    storageType: "xml",
    topLevelKey: result.topLevelHash as `0x${string}`,
    filename: file.name,
    data,
    transactionConfigs,
    chunkKeys,
    xmlMetadata: result.metadata,
  };
}

// Legacy function for backward compatibility
// TODO: Remove once use-net-upload.ts is refactored to use prepareFileForUpload
export async function prepareFileForUploadLegacy(
  file: File,
  operatorAddress?: string,
  resumeWithKeys?: {
    storageKey: `0x${string}`;
    chunkKeys: `0x${string}`[];
  }
): Promise<{
  storageType: "regular" | "chunked" | "xml";
  key: `0x${string}`;
  text: string;
  data: Uint8Array;
  dataHex?: `0x${string}`; // Hex-encoded base64 data for regular storage
  chunks?: string[];
  xmlChunks?: XmlChunk[];
}> {
  // Check file size limit
  if (file.size > MAX_FILE_SIZE) {
    throw new Error(`File too large. Maximum size is ${MAX_FILE_SIZE / 1024 / 1024}MB. Your file is ${(file.size / 1024 / 1024).toFixed(1)}MB.`);
  }

  const arrayBuffer = await file.arrayBuffer();
  const data = new Uint8Array(arrayBuffer);
  const storageType = getStorageType(data.length);
  const timestamp = Date.now();

  // Use resume keys if provided (for upload recovery), otherwise generate new
  const key = resumeWithKeys?.storageKey ?? generateStorageKey(`netlib-${file.name}-${timestamp}`);

  // For binary files (like PDFs), convert to base64 for SDK chunking
  const dataAsBase64 = uint8ArrayToBase64(data);

  if (storageType === "regular") {
    // For regular storage, encode base64 data as hex for the contract
    const dataHex = stringToHex(dataAsBase64) as `0x${string}`;
    return {
      storageType,
      key,
      text: file.name,
      data,
      dataHex,
    };
  }

  if (storageType === "chunked") {
    const chunks = chunkDataForStorage(dataAsBase64);
    return {
      storageType,
      key,
      text: file.name,
      data,
      chunks,
    };
  }

  // XML Storage - Use SDK's 80KB chunk size (per Net Protocol spec)
  const XML_CHUNK_SIZE = 80000; // Official Net Protocol chunk size
  const xmlChunks: XmlChunk[] = [];

  // Split base64 data into chunks, then compress each
  let chunkIndex = 0;
  for (let i = 0; i < dataAsBase64.length; i += XML_CHUNK_SIZE) {
    const chunkString = dataAsBase64.slice(i, i + XML_CHUNK_SIZE);
    const compressedChunks = chunkDataForStorage(chunkString) as `0x${string}`[];

    // Generate DETERMINISTIC key based on content hash (matches SDK behavior)
    // This allows resume to work because same content = same key
    let chunkKey: `0x${string}`;
    if (resumeWithKeys?.chunkKeys?.[chunkIndex]) {
      // Use provided key for resume
      chunkKey = resumeWithKeys.chunkKeys[chunkIndex];
    } else {
      // Generate content-hash based key (deterministic)
      const contentForHash = chunkString + (operatorAddress || '').toLowerCase();
      chunkKey = keccak256(stringToHex(contentForHash));
    }

    xmlChunks.push({
      key: chunkKey,
      compressedChunks,
    });
    chunkIndex++;
  }

  return {
    storageType: "xml",
    key,
    text: file.name,
    data,
    xmlChunks,
  };
}

// Book metadata structure
export interface BookMetadata {
  title: string;
  author: string;
  categories: string[];
  fileName: string;
  fileSize: number;
  uploadedAt: number;
  contentKey: string;
}

// Generate metadata JSON for a book
export function createBookMetadata(
  title: string,
  author: string,
  categories: string[],
  fileName: string,
  fileSize: number,
  contentKey: string,
  operatorAddress: string,
  storageType: "regular" | "chunked" | "xml"
): BookMetadata & { operator: string; storageType: string } {
  return {
    title,
    author,
    categories,
    fileName,
    fileSize,
    uploadedAt: Date.now(),
    contentKey,
    operator: operatorAddress,
    storageType,
  };
}

// ============================================
// DISCOVERY INDEX - Stored on Net Protocol
// ============================================

export const DISCOVERY_INDEX_KEY = generateStorageKey("net-library-discovery-index-v1");
export const DISCOVERY_INDEX_OPERATOR = "0x0000000000000000000000000000000000000000" as const;

export interface DiscoveryEntry {
  contentKey: string;
  metadataKey: string;
  // Technical operator: the wallet that wrote to the blockchain
  // For relay uploads: this is the BACKEND WALLET (needed for CDN URL generation)
  // For direct uploads: this is the user's wallet
  operator: string;
  // Attribution address: the USER's wallet who uploaded the content
  // This is used for: attribution, upvotes, "uploaded by" display
  // Falls back to operator for backwards compatibility with older entries
  uploaderAddress?: string;
  title: string;
  author: string;
  categories: string[];
  fileSize: number;
  uploadedAt: number;
  storageType: "regular" | "chunked" | "xml";
  coverUrl?: string;
  // Original filename - REQUIRED for generating correct CDN URLs
  // Used with /storage/load/{operator}/{filename} format
  fileName?: string;
  // For regular uploads: uploader's Farcaster info
  // For CDN imports: importer's Farcaster info (who added it to Net Library)
  uploaderFid?: number;
  uploaderUsername?: string;
  uploaderPfpUrl?: string; // Profile picture URL
  // Membership info - for unified identity across all platforms
  // This links uploads to memberships regardless of which wallet was used
  uploaderMemberId?: number;
  uploaderEnsSubname?: string; // e.g., "123.netlibrary.eth" (kept for internal tracking)
  // Unified identity: The Farcaster username stored at signup - THIS is the social identity
  // If @geaux.eth signed up via Farcaster, this stores "geaux.eth" so it shows everywhere
  uploaderStoredUsername?: string;
  // Optional metadata fields
  publicationYear?: number;
  publisher?: string;
  isbn?: string; // ISBN or DOI
  // Content hash for deduplication (SHA-256)
  contentHash?: string;
  // CDN link support - for multimedia content that's already on Net Protocol
  cdnUrl?: string; // Direct URL to the content
  mediaType?: "pdf" | "image" | "audio" | "video" | "text" | "unknown"; // Type of multimedia content
  // For CDN imports: the address of the person who imported the content to Net Library
  // This is separate from 'operator' which is the original content creator
  importerAddress?: string;
  // Hidden from library feed (content still exists on Net Protocol, just not shown in feed)
  hidden?: boolean;
  hiddenAt?: number;
  // Social receipt specific metadata (for archived social posts)
  isSocialReceipt?: boolean;
  socialPlatform?: "farcaster" | "twitter" | "youtube" | "instagram" | "tiktok" | "reddit" | "bluesky" | "threads" | "linkedin" | "paragraph";
  originalUrl?: string; // Original URL of the social post (legacy field — same as sourceUrl)
  sourceUrl?: string;   // Source URL of the social post (e.g. Warpcast cast URL)
  socialText?: string; // Text content of the social post
  socialAuthor?: string; // Username of the original author
  socialTimestamp?: string; // When the original post was created
  // Farcaster-specific social receipt fields
  castHash?: string;            // Farcaster cast hash (0x…)
  castAuthorFid?: number;       // Author's Farcaster FID
  castAuthorUsername?: string;  // Author's Farcaster username
  castAuthorPfpUrl?: string;    // Author's profile picture URL
  castEmbeds?: unknown;         // Cast embed objects (images, URLs, etc.)
  castTimestamp?: number | string; // Original cast timestamp
  // Agent identity - for items uploaded by registered AI agents
  isAgentUploaded?: boolean; // True if this item was uploaded by a registered agent
  agentId?: string; // The agent's registered ID (e.g., "cheryl")
  // Encryption — content is AES-256-GCM encrypted; password shared out-of-band
  // Title, description, categories, and all other metadata remain plaintext/public.
  encrypted?: boolean;
  // Partner import attribution — set to the partner's siteName when imported via partner API.
  // Null/undefined for items uploaded directly through Net Library.
  source?: string;
}

export function createDiscoveryEntry(
  contentKey: string,
  metadataKey: string,
  operator: string,
  title: string,
  author: string,
  categories: string[],
  fileSize: number,
  storageType: "regular" | "chunked" | "xml",
  coverUrl?: string,
  extraMetadata?: {
    publicationYear?: number;
    publisher?: string;
    isbn?: string;
    uploaderFid?: number;
    uploaderUsername?: string;
    uploaderMemberId?: number;
    uploaderEnsSubname?: string;
    uploaderStoredUsername?: string; // Farcaster username stored at signup - the social identity
    uploaderAddress?: string; // User's wallet address for attribution (separate from operator)
    contentHash?: string;
    mediaType?: "pdf" | "image" | "audio" | "video" | "text" | "unknown";
    cdnUrl?: string;
    fileName?: string; // Original filename for CDN URL generation
    // Social receipt metadata (for archived social posts)
    isSocialReceipt?: boolean;
    socialPlatform?: "farcaster" | "twitter" | "youtube" | "instagram" | "tiktok" | "reddit" | "bluesky" | "threads" | "linkedin" | "paragraph";
    originalUrl?: string;
    socialText?: string;
    socialAuthor?: string;
    socialTimestamp?: string;
    // Agent identity
    isAgentUploaded?: boolean;
    agentId?: string;
    // Encryption flag
    encrypted?: boolean;
  }
): DiscoveryEntry {
  const entry: DiscoveryEntry = {
    contentKey,
    metadataKey,
    operator,
    title,
    author,
    categories,
    fileSize,
    uploadedAt: Date.now(),
    storageType,
  };
  if (coverUrl) {
    entry.coverUrl = coverUrl;
  }
  if (extraMetadata?.publicationYear) {
    entry.publicationYear = extraMetadata.publicationYear;
  }
  if (extraMetadata?.publisher) {
    entry.publisher = extraMetadata.publisher;
  }
  if (extraMetadata?.isbn) {
    entry.isbn = extraMetadata.isbn;
  }
  if (extraMetadata?.uploaderFid) {
    entry.uploaderFid = extraMetadata.uploaderFid;
  }
  if (extraMetadata?.uploaderUsername) {
    entry.uploaderUsername = extraMetadata.uploaderUsername;
  }
  if (extraMetadata?.uploaderMemberId) {
    entry.uploaderMemberId = extraMetadata.uploaderMemberId;
  }
  if (extraMetadata?.uploaderEnsSubname) {
    entry.uploaderEnsSubname = extraMetadata.uploaderEnsSubname;
  }
  if (extraMetadata?.uploaderStoredUsername) {
    entry.uploaderStoredUsername = extraMetadata.uploaderStoredUsername;
  }
  if (extraMetadata?.uploaderAddress) {
    entry.uploaderAddress = extraMetadata.uploaderAddress;
  }
  if (extraMetadata?.contentHash) {
    entry.contentHash = extraMetadata.contentHash;
  }
  if (extraMetadata?.mediaType) {
    entry.mediaType = extraMetadata.mediaType;
  }
  if (extraMetadata?.cdnUrl) {
    entry.cdnUrl = extraMetadata.cdnUrl;
  }
  if (extraMetadata?.fileName) {
    entry.fileName = extraMetadata.fileName;
  }
  // Social receipt metadata
  if (extraMetadata?.isSocialReceipt) {
    entry.isSocialReceipt = extraMetadata.isSocialReceipt;
  }
  if (extraMetadata?.socialPlatform) {
    entry.socialPlatform = extraMetadata.socialPlatform;
  }
  if (extraMetadata?.originalUrl) {
    entry.originalUrl = extraMetadata.originalUrl;
  }
  if (extraMetadata?.socialText) {
    entry.socialText = extraMetadata.socialText;
  }
  if (extraMetadata?.socialAuthor) {
    entry.socialAuthor = extraMetadata.socialAuthor;
  }
  if (extraMetadata?.socialTimestamp) {
    entry.socialTimestamp = extraMetadata.socialTimestamp;
  }
  // Agent identity
  if (extraMetadata?.isAgentUploaded) {
    entry.isAgentUploaded = extraMetadata.isAgentUploaded;
  }
  if (extraMetadata?.agentId) {
    entry.agentId = extraMetadata.agentId;
  }
  // Encryption flag
  if (extraMetadata?.encrypted) {
    entry.encrypted = true;
  }
  return entry;
}

export function getDiscoveryIndexUrl(): string {
  return `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${DISCOVERY_INDEX_OPERATOR}/${DISCOVERY_INDEX_KEY}`;
}

export async function fetchDiscoveryIndex(): Promise<DiscoveryEntry[]> {
  try {
    const url = getDiscoveryIndexUrl();
    const response = await fetch(url);

    if (!response.ok) {
      return [];
    }

    const data = await response.json();
    if (data.data) {
      const dataStr = data.data as string;
      let decoded: string;

      if (dataStr.startsWith("0x")) {
        // Hex encoded
        decoded = hexToString(dataStr);
      } else if (/^[A-Za-z0-9+/=]+$/.test(dataStr) && dataStr.length > 20) {
        // Base64 encoded
        try {
          const buffer = Buffer.from(dataStr, "base64");
          decoded = buffer.toString("utf-8");
        } catch {
          decoded = dataStr;
        }
      } else {
        // Plain text
        decoded = dataStr;
      }

      return JSON.parse(decoded);
    }
    return [];
  } catch (error) {
    console.error("Failed to fetch discovery index:", error);
    return [];
  }
}

function hexToString(hex: string): string {
  const cleanHex = hex.startsWith("0x") ? hex.slice(2) : hex;
  const bytes = new Uint8Array(cleanHex.length / 2);
  for (let i = 0; i < cleanHex.length; i += 2) {
    bytes[i / 2] = parseInt(cleanHex.slice(i, i + 2), 16);
  }
  return new TextDecoder().decode(bytes);
}

// ============================================
// LEADERBOARD INDEX
// ============================================

export const LEADERBOARD_INDEX_KEY = generateStorageKey("net-library-leaderboard-v1");

export interface UserStats {
  address: string;
  totalUploads: number;
  totalBytesUploaded: number;
  totalDownloads: number;
  categoriesContributed: string[];
  firstUploadAt: number;
  lastUploadAt: number;
}

export interface BookStats {
  contentKey: string;
  title: string;
  author: string;
  operator: string;
  downloads: number;
  shares: number;
  addedToQueues: number;
  opens: number;
  currentlyReading: number;
  uploadedAt: number;
}

export interface CategoryStats {
  categoryId: string;
  totalBooks: number;
  totalBytes: number;
  totalDownloads: number;
}

export interface LeaderboardIndex {
  users: UserStats[];
  topBooks: BookStats[];
  categories: CategoryStats[];
  globalStats: {
    totalBooks: number;
    totalBytes: number;
    totalDownloads: number;
    totalUsers: number;
    lastUpdated: number;
  };
}

export function getLeaderboardIndexUrl(): string {
  return `https://storedon.net/net/${BASE_CHAIN_ID}/storage/raw/${DISCOVERY_INDEX_OPERATOR}/${LEADERBOARD_INDEX_KEY}`;
}

export async function fetchLeaderboardIndex(): Promise<LeaderboardIndex> {
  const emptyLeaderboard: LeaderboardIndex = {
    users: [],
    topBooks: [],
    categories: [],
    globalStats: {
      totalBooks: 0,
      totalBytes: 0,
      totalDownloads: 0,
      totalUsers: 0,
      lastUpdated: Date.now(),
    },
  };

  try {
    // Fetch discovery entries to compute stats locally
    const discoveryResponse = await fetch("/api/discovery");
    if (!discoveryResponse.ok) {
      return emptyLeaderboard;
    }
    const discoveryData = await discoveryResponse.json();
    const entries = discoveryData.entries as DiscoveryEntry[] || [];

    if (entries.length === 0) {
      return emptyLeaderboard;
    }

    // Fetch engagement data for all content keys
    // The engagement API requires contentKeys parameter for per-content stats
    const contentKeys = entries.map(e => e.contentKey).join(",");
    let contentStats: { [key: string]: { opens: number; currentlyReading: number; addedToQueues: number } } = {};

    if (contentKeys) {
      const engagementResponse = await fetch(`/api/engagement?contentKeys=${encodeURIComponent(contentKeys)}`);
      if (engagementResponse.ok) {
        const engagementData = await engagementResponse.json();
        contentStats = engagementData.stats || {};
      }
    }

    // Compute user stats
    const userMap = new Map<string, UserStats>();
    const categoryMap = new Map<string, CategoryStats>();
    const bookStats: BookStats[] = [];
    let totalBytes = 0;
    let totalOpens = 0;

    for (const entry of entries) {
      // Hidden items are excluded from all stats — they should not inflate counts.
      if (entry.hidden) continue;

      // Use uploaderAddress when available (relay uploads store the backend wallet as
      // `operator` and the actual user's wallet as `uploaderAddress`). Fall back to
      // `operator` for legacy entries that predate the uploaderAddress field.
      const addr = (entry.uploaderAddress || entry.operator).toLowerCase();
      totalBytes += entry.fileSize;

      // Get engagement stats for this content
      // Note: engagement tracks opens, not downloads. We'll use opens as a proxy metric.
      const engagement = contentStats[entry.contentKey] || { opens: 0, addedToQueues: 0, currentlyReading: 0 };
      totalOpens += engagement.opens || 0;

      // Update user stats
      const existing = userMap.get(addr);
      if (existing) {
        existing.totalUploads += 1;
        existing.totalBytesUploaded += entry.fileSize;
        existing.totalDownloads += engagement.opens || 0; // Use opens as proxy for engagement
        existing.lastUploadAt = Math.max(existing.lastUploadAt, entry.uploadedAt);
        existing.categoriesContributed = [...new Set([...existing.categoriesContributed, ...(entry.categories || [])])];
      } else {
        userMap.set(addr, {
          address: addr,
          totalUploads: 1,
          totalBytesUploaded: entry.fileSize,
          totalDownloads: engagement.opens || 0, // Use opens as proxy
          categoriesContributed: [...(entry.categories || [])],
          firstUploadAt: entry.uploadedAt,
          lastUploadAt: entry.uploadedAt,
        });
      }

      // Update category stats
      for (const cat of (entry.categories || [])) {
        const catStats = categoryMap.get(cat);
        if (catStats) {
          catStats.totalBooks += 1;
          catStats.totalBytes += entry.fileSize;
          catStats.totalDownloads += engagement.opens || 0;
        } else {
          categoryMap.set(cat, {
            categoryId: cat,
            totalBooks: 1,
            totalBytes: entry.fileSize,
            totalDownloads: engagement.opens || 0,
          });
        }
      }

      // Add book stats
      bookStats.push({
        contentKey: entry.contentKey,
        title: entry.title,
        author: entry.author,
        operator: (entry.uploaderAddress || entry.operator),
        downloads: engagement.opens || 0, // Use opens as proxy
        shares: 0,
        addedToQueues: engagement.addedToQueues || 0,
        opens: engagement.opens || 0,
        currentlyReading: engagement.currentlyReading || 0,
        uploadedAt: entry.uploadedAt,
      });
    }

    return {
      users: Array.from(userMap.values()),
      topBooks: bookStats.sort((a, b) => b.downloads - a.downloads),
      categories: Array.from(categoryMap.values()),
      globalStats: {
        totalBooks: entries.length,
        totalBytes,
        totalDownloads: totalOpens, // Use opens as proxy
        totalUsers: userMap.size,
        lastUpdated: Date.now(),
      },
    };
  } catch (error) {
    console.error("Failed to fetch leaderboard index:", error);
    return emptyLeaderboard;
  }
}

export function updateUserStats(
  currentStats: UserStats | undefined,
  address: string,
  fileSize: number,
  categories: string[]
): UserStats {
  const now = Date.now();

  const safeCategories = Array.isArray(categories) ? categories : [];

  if (!currentStats) {
    return {
      address,
      totalUploads: 1,
      totalBytesUploaded: fileSize,
      totalDownloads: 0,
      categoriesContributed: [...new Set(safeCategories)],
      firstUploadAt: now,
      lastUploadAt: now,
    };
  }

  const allCategories = new Set([...currentStats.categoriesContributed, ...safeCategories]);

  return {
    ...currentStats,
    totalUploads: currentStats.totalUploads + 1,
    totalBytesUploaded: currentStats.totalBytesUploaded + fileSize,
    categoriesContributed: [...allCategories],
    lastUploadAt: now,
  };
}

export function createBookStats(
  contentKey: string,
  title: string,
  author: string,
  operator: string
): BookStats {
  return {
    contentKey,
    title,
    author,
    operator,
    downloads: 0,
    shares: 0,
    addedToQueues: 0,
    opens: 0,
    currentlyReading: 0,
    uploadedAt: Date.now(),
  };
}

export function updateCategoryStats(
  currentStats: CategoryStats | undefined,
  categoryId: string,
  fileSize: number
): CategoryStats {
  if (!currentStats) {
    return {
      categoryId,
      totalBooks: 1,
      totalBytes: fileSize,
      totalDownloads: 0,
    };
  }

  return {
    ...currentStats,
    totalBooks: currentStats.totalBooks + 1,
    totalBytes: currentStats.totalBytes + fileSize,
  };
}

export function computeLeaderboardUpdate(
  currentLeaderboard: LeaderboardIndex,
  entry: DiscoveryEntry
): LeaderboardIndex {
  // Hidden items do not count toward any stats.
  if (entry.hidden) return currentLeaderboard;

  const { operator, contentKey, title, author, fileSize } = entry;
  const categories = Array.isArray(entry.categories) ? entry.categories : [];

  // For relay uploads the backend wallet is stored as `operator`, but the actual
  // user who uploaded the content is `uploaderAddress`.  Credit stats to the real
  // uploader, falling back to `operator` for legacy entries that predate this field.
  const uploaderAddress = entry.uploaderAddress || operator;

  const existingUserIndex = currentLeaderboard.users.findIndex(u => u.address === uploaderAddress);
  const existingUser = existingUserIndex >= 0 ? currentLeaderboard.users[existingUserIndex] : undefined;
  const updatedUser = updateUserStats(existingUser, uploaderAddress, fileSize, categories);

  const updatedUsers = existingUserIndex >= 0
    ? [...currentLeaderboard.users.slice(0, existingUserIndex), updatedUser, ...currentLeaderboard.users.slice(existingUserIndex + 1)]
    : [...currentLeaderboard.users, updatedUser];

  updatedUsers.sort((a, b) => b.totalUploads - a.totalUploads);

  const newBookStats = createBookStats(contentKey, title, author, uploaderAddress);
  const updatedTopBooks = [...currentLeaderboard.topBooks, newBookStats]
    .sort((a, b) => b.downloads - a.downloads)
    .slice(0, 50);

  const updatedCategories = [...currentLeaderboard.categories];
  for (const categoryId of categories) {
    const existingCatIndex = updatedCategories.findIndex(c => c.categoryId === categoryId);
    if (existingCatIndex >= 0) {
      updatedCategories[existingCatIndex] = updateCategoryStats(updatedCategories[existingCatIndex], categoryId, fileSize);
    } else {
      updatedCategories.push(updateCategoryStats(undefined, categoryId, fileSize));
    }
  }

  updatedCategories.sort((a, b) => b.totalBooks - a.totalBooks);

  const uniqueUsers = new Set(updatedUsers.map(u => u.address));

  return {
    users: updatedUsers,
    topBooks: updatedTopBooks,
    categories: updatedCategories,
    globalStats: {
      totalBooks: currentLeaderboard.globalStats.totalBooks + 1,
      totalBytes: currentLeaderboard.globalStats.totalBytes + fileSize,
      totalDownloads: currentLeaderboard.globalStats.totalDownloads,
      totalUsers: uniqueUsers.size,
      lastUpdated: Date.now(),
    },
  };
}

export function recordDownload(
  currentLeaderboard: LeaderboardIndex,
  contentKey: string,
  uploaderAddress: string
): LeaderboardIndex {
  const updatedTopBooks = currentLeaderboard.topBooks.map(book => {
    if (book.contentKey === contentKey) {
      return { ...book, downloads: book.downloads + 1 };
    }
    return book;
  });

  updatedTopBooks.sort((a, b) => b.downloads - a.downloads);

  const updatedUsers = currentLeaderboard.users.map(user => {
    if (user.address === uploaderAddress) {
      return { ...user, totalDownloads: user.totalDownloads + 1 };
    }
    return user;
  });

  return {
    ...currentLeaderboard,
    users: updatedUsers,
    topBooks: updatedTopBooks,
    globalStats: {
      ...currentLeaderboard.globalStats,
      totalDownloads: currentLeaderboard.globalStats.totalDownloads + 1,
      lastUpdated: Date.now(),
    },
  };
}

// ============================================================================
// MEMBER REGISTRY
// ============================================================================

export const MEMBER_REGISTRY_KEY = "net-library-member-registry-v1";

export type SignupPlatform = "farcaster" | "base-app" | "web";

export interface MemberEntry {
  memberId: number;
  address: string;
  ensSubname: string;
  fid?: number;
  username?: string;
  joinedAt: number;
  txHash?: string;
  signupPlatform?: SignupPlatform; // Track which platform user signed up on
  linkedAddresses?: string[]; // Additional wallet addresses linked to this membership

  // Web platform fields
  wid?: string;                    // Web ID - 6-char alphanumeric (e.g., "A7K2M9")
  customUsername?: string;         // User-editable username (web only)
  customPfpUrl?: string;           // User-uploaded PFP URL (web only)
  linkedFid?: number;              // FID linked after signup (for web users who link FC)
  linkedPlatforms?: SignupPlatform[]; // Track which platforms are linked

  // Unlimited Pass (legacy field name: hasStackPass) - $10 for unlimited stacks + items
  hasStackPass?: boolean;          // True if user purchased Unlimited Stack Pass
  stackPassTxHash?: string;        // Payment transaction hash for stack pass
  stackPassPurchasedAt?: number;   // Timestamp when pass was purchased

  // Legacy Grid Pass - $2 for unlimited large grids (6×6+)
  // Deprecated: Use hasUnlimitedPass instead
  hasGridPass?: boolean;           // True if user purchased Grid Pass (legacy)
  gridPassTxHash?: string;         // Payment transaction hash for grid pass
  gridPassPurchasedAt?: number;    // Timestamp when pass was purchased

  // Unlimited Pass ($10) - includes unlimited custom grids + unlimited items in stacks
  // Previously "Unlimited Storage Pass" — field renamed; old KV data is migrated by
  // reading both hasUnlimitedPass and hasUnlimitedStoragePass (backwards compat below).
  hasUnlimitedPass?: boolean;
  /** @deprecated use hasUnlimitedPass */
  hasUnlimitedStoragePass?: boolean; // kept for KV backwards compatibility — do not write
  unlimitedPassTxHash?: string;
  unlimitedPassPurchasedAt?: number;
  // NFT mint fields (set when minted via ERC-721 contract on Base)
  unlimitedPassTokenId?: number;     // ERC-721 token ID
  unlimitedPassTier?: string;        // "we are so early" | "early-ish"
  unlimitedPassMintTx?: string;      // Mint transaction hash on Base
  unlimitedPassVerified?: boolean;   // true = on-chain verified; false/undefined = pending verification

  // Per-grid unlocks (for users without Unlimited Pass)
  // Each custom grid (6×6+) costs $2
  gridUnlocks?: Array<{
    txHash: string;
    gridSize: number;
    purchasedAt: number;
  }>;

  // Agent identity - for registered AI agents
  isAgent?: boolean;               // True if this member is a registered agent
  agentId?: string;                // The agent's registered ID (e.g., "cheryl")

  // Display name vs Farcaster handle separation
  // username = display name (e.g., "Cheryl") - shown as primary name
  // farcasterUsername = Farcaster handle (e.g., "cherylfromnet") - shown as @handle
  farcasterUsername?: string;      // Farcaster handle (without @)
  pfpUrl?: string;                 // Profile picture URL (stored in registry, not just resolved)

  // ERC-8004 Base Identity Registry verification (C16)
  erc8004Verified?: boolean;       // True if verified on ERC-8004 Base Identity Registry
  erc8004TokenId?: number;         // Token ID on the registry
  erc8004CheckedAt?: number;       // Timestamp of last verification check
}

export interface MemberRegistry {
  members: MemberEntry[];
  nextMemberId: number;
  lastUpdated: number;
}

export function getMemberRegistryUrl(): string {
  // DEPRECATED: /content/ URLs return 404 - this function is no longer used
  // Member registry is now fetched via API routes that use KV storage
  return `https://storedon.net/content/${MEMBER_REGISTRY_KEY}`;
}

// Fetch member registry - uses API route which stores in KV
// baseUrl is required for server-side calls
export async function fetchMemberRegistry(baseUrl?: string): Promise<MemberRegistry> {
  const emptyRegistry: MemberRegistry = {
    members: [],
    nextMemberId: 1,
    lastUpdated: Date.now(),
  };

  try {
    // Construct full URL for server-side calls
    const apiUrl = baseUrl
      ? `${baseUrl}/api/member-registry`
      : '/api/member-registry';

    const response = await fetch(apiUrl, {
      cache: 'no-store', // Always get fresh data
    });

    if (!response.ok) {
      return emptyRegistry;
    }

    const data = await response.json();

    if (!data || typeof data.nextMemberId !== 'number') {
      return emptyRegistry;
    }

    return data as MemberRegistry;
  } catch (error) {
    console.error("Failed to fetch member registry:", error);
    return emptyRegistry;
  }
}

export function isMember(registry: MemberRegistry, address: string): MemberEntry | undefined {
  // Find ALL members with this address and return the one with the LOWEST memberId
  // This handles duplicates by preferring the original membership (first registered)
  const matches = registry.members.filter(m => m.address && m.address.toLowerCase() === address.toLowerCase());
  if (matches.length === 0) return undefined;
  return matches.reduce((lowest, current) =>
    current.memberId < lowest.memberId ? current : lowest
  );
}

// Check if a user is already a member by Farcaster ID (prevents duplicates when same user uses different wallets)
export function isMemberByFid(registry: MemberRegistry, fid: number): MemberEntry | undefined {
  if (!fid) return undefined;
  // Find ALL members with this FID and return the one with the LOWEST memberId
  const matches = registry.members.filter(m => m.fid === fid);
  if (matches.length === 0) return undefined;
  return matches.reduce((lowest, current) =>
    current.memberId < lowest.memberId ? current : lowest
  );
}

// Check if an address is linked to any existing membership
export function isMemberByLinkedAddress(registry: MemberRegistry, address: string): MemberEntry | undefined {
  const lowerAddress = address.toLowerCase();
  // Find ALL members with this linked address and return the one with the LOWEST memberId
  const matches = registry.members.filter(m =>
    m.linkedAddresses?.some(linked => linked.toLowerCase() === lowerAddress)
  );
  if (matches.length === 0) return undefined;
  return matches.reduce((lowest, current) =>
    current.memberId < lowest.memberId ? current : lowest
  );
}

// Find ALL membership entries for a user (handles duplicates)
// Returns array of all member IDs sorted lowest to highest
// Uses transitive lookup: if membership A has linked address B, and B is primary of membership C, both are returned
// verifiedAddresses: Extra addresses to check (e.g., Farcaster verified addresses from Neynar)
export function findAllMemberships(registry: MemberRegistry, address: string, fid?: number, verifiedAddresses?: string[]): MemberEntry[] {
  const found: MemberEntry[] = [];
  const seenIds = new Set<number>();

  // Collect all addresses associated with this user (will grow as we find memberships)
  const userAddresses = new Set<string>();
  userAddresses.add(address.toLowerCase());

  // Add Farcaster verified addresses (these are cryptographically proven to belong to this user)
  if (verifiedAddresses) {
    verifiedAddresses.forEach(addr => userAddresses.add(addr.toLowerCase()));
  }

  // Find by address (including verified addresses)
  for (const m of registry.members) {
    if (m.address && userAddresses.has(m.address.toLowerCase()) && !seenIds.has(m.memberId)) {
      found.push(m);
      seenIds.add(m.memberId);
      // Add this membership's linked addresses to our address pool
      m.linkedAddresses?.forEach(linked => linked && userAddresses.add(linked.toLowerCase()));
    }
  }

  // Find by FID
  if (fid) {
    for (const m of registry.members) {
      if (m.fid === fid && !seenIds.has(m.memberId)) {
        found.push(m);
        seenIds.add(m.memberId);
        // Add the primary address and linked addresses to our pool
        if (m.address) userAddresses.add(m.address.toLowerCase());
        m.linkedAddresses?.forEach(linked => linked && userAddresses.add(linked.toLowerCase()));
      }
    }
  }

  // Find by linked address (check if user's address is in some membership's linkedAddresses)
  const lowerAddress = address.toLowerCase();
  for (const m of registry.members) {
    if (m.linkedAddresses?.some(linked => linked && linked.toLowerCase() === lowerAddress) && !seenIds.has(m.memberId)) {
      found.push(m);
      seenIds.add(m.memberId);
      // Add this membership's primary and linked addresses to our pool
      if (m.address) userAddresses.add(m.address.toLowerCase());
      m.linkedAddresses?.forEach(linked => linked && userAddresses.add(linked.toLowerCase()));
    }
  }

  // SECOND PASS: Now check if any of the collected addresses match OTHER memberships
  // This handles the case where member #1 has a linked address that is member #3's primary address
  for (const m of registry.members) {
    if (!seenIds.has(m.memberId)) {
      // Check if this membership's primary address is in our user's address pool
      if (m.address && userAddresses.has(m.address.toLowerCase())) {
        found.push(m);
        seenIds.add(m.memberId);
        continue;
      }
      // Check if any of this membership's linked addresses are in our pool
      if (m.linkedAddresses?.some(linked => linked && userAddresses.has(linked.toLowerCase()))) {
        found.push(m);
        seenIds.add(m.memberId);
      }
    }
  }

  // Sort by memberId (lowest first)
  return found.sort((a, b) => a.memberId - b.memberId);
}

// Check membership by any method: primary address, FID, or linked address
export function findMembership(registry: MemberRegistry, address: string, fid?: number): MemberEntry | undefined {
  console.log("[findMembership] Looking up - address:", address.slice(0, 10) + "...", "fid:", fid);

  // Check primary address first
  const byAddress = isMember(registry, address);
  if (byAddress) {
    console.log("[findMembership] Found by primary address - memberId:", byAddress.memberId);
    return byAddress;
  }

  // Check by FID
  if (fid) {
    const byFid = isMemberByFid(registry, fid);
    if (byFid) {
      console.log("[findMembership] Found by FID - memberId:", byFid.memberId, "memberFid:", byFid.fid);
      return byFid;
    }
  }

  // Check linked addresses
  const byLinked = isMemberByLinkedAddress(registry, address);
  if (byLinked) {
    console.log("[findMembership] Found by linked address - memberId:", byLinked.memberId);
    return byLinked;
  }

  console.log("[findMembership] No membership found");
  return undefined;
}

// Link a new address to an existing membership
export function linkAddressToMember(
  registry: MemberRegistry,
  memberId: number,
  newAddress: string
): { success: boolean; registry: MemberRegistry; error?: string } {
  const lowerAddress = newAddress.toLowerCase();

  // Check if address is already a primary address
  const existingByAddress = registry.members.find(m => m.address && m.address.toLowerCase() === lowerAddress);
  if (existingByAddress) {
    return {
      success: false,
      registry,
      error: `Address already registered as member #${existingByAddress.memberId}`
    };
  }

  // Check if address is already linked to another member
  const existingByLinked = isMemberByLinkedAddress(registry, newAddress);
  if (existingByLinked) {
    return {
      success: false,
      registry,
      error: `Address already linked to member #${existingByLinked.memberId}`
    };
  }

  // Find the member to link to
  const memberIndex = registry.members.findIndex(m => m.memberId === memberId);
  if (memberIndex === -1) {
    return { success: false, registry, error: "Member not found" };
  }

  // Add the linked address
  const updatedMember = {
    ...registry.members[memberIndex],
    linkedAddresses: [
      ...(registry.members[memberIndex].linkedAddresses || []),
      lowerAddress,
    ],
  };

  const updatedMembers = [...registry.members];
  updatedMembers[memberIndex] = updatedMember;

  return {
    success: true,
    registry: {
      ...registry,
      members: updatedMembers,
      lastUpdated: Date.now(),
    },
  };
}

// Store member registry - uses API route which stores in KV
// baseUrl is required for server-side calls
export async function storeMemberRegistry(registry: MemberRegistry, baseUrl?: string): Promise<boolean> {
  try {
    const apiUrl = baseUrl
      ? `${baseUrl}/api/member-registry`
      : '/api/member-registry';

    const response = await fetch(apiUrl, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(registry),
    });
    return response.ok;
  } catch (error) {
    console.error("Failed to store member registry:", error);
    return false;
  }
}

// Generate a 6-character alphanumeric WID for web users
export function generateWID(existingWids: Set<string>): string {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  let wid: string;
  let attempts = 0;
  const maxAttempts = 100;

  do {
    wid = "";
    for (let i = 0; i < 6; i++) {
      wid += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    attempts++;
  } while (existingWids.has(wid) && attempts < maxAttempts);

  if (attempts >= maxAttempts) {
    // Extremely unlikely - fall back to timestamp-based
    wid = Date.now().toString(36).toUpperCase().slice(-6).padStart(6, "0");
  }

  return wid;
}

// Get all existing WIDs from registry
export function getExistingWids(registry: MemberRegistry): Set<string> {
  const wids = new Set<string>();
  for (const member of registry.members) {
    if (member.wid) {
      wids.add(member.wid);
    }
  }
  return wids;
}

export function addMember(
  registry: MemberRegistry,
  address: string,
  fid?: number,
  username?: string,
  txHash?: string,
  signupPlatform?: SignupPlatform,
  isAgent?: boolean,
  agentId?: string
): { registry: MemberRegistry; member: MemberEntry } {
  const memberId = registry.nextMemberId;
  const ensSubname = `${memberId}.netlibrary.eth`;

  // Determine platform - default logic
  const platform = signupPlatform || (fid ? "farcaster" : "base-app");

  // Generate WID for web signups
  let wid: string | undefined;
  if (platform === "web") {
    const existingWids = getExistingWids(registry);
    wid = generateWID(existingWids);
  }

  const newMember: MemberEntry = {
    memberId,
    address,
    ensSubname,
    fid,
    username,
    joinedAt: Date.now(),
    txHash,
    signupPlatform: platform,
    wid,
    // Agent identity
    isAgent,
    agentId,
  };

  const updatedRegistry: MemberRegistry = {
    members: [...registry.members, newMember],
    nextMemberId: memberId + 1,
    lastUpdated: Date.now(),
  };

  return { registry: updatedRegistry, member: newMember };
}

// ============================================================================
// BOOK REVIEWS
// ============================================================================

export const REVIEWS_INDEX_KEY = generateStorageKey("net-library-reviews-v1");

export interface BookReview {
  id: string;
  contentKey: string;
  reviewerAddress: string;
  reviewerFid?: number;
  reviewerUsername?: string;
  rating: number;
  reviewText?: string;
  createdAt: number;
  helpful: number;
}

export interface BookRatingSummary {
  contentKey: string;
  averageRating: number;
  totalReviews: number;
  ratingDistribution: { [key: number]: number };
}

export interface ReviewsIndex {
  reviews: BookReview[];
  summaries: { [contentKey: string]: BookRatingSummary };
  lastUpdated: number;
}

// ============================================================================
// TIPS
// ============================================================================

export const TIPS_INDEX_KEY = generateStorageKey("net-library-tips-v1");

export interface Tip {
  id: string;
  fromAddress: string;
  fromFid?: number;
  fromUsername?: string;
  toAddress: string;
  toFid?: number;
  toUsername?: string;
  amountUsdc: number;
  contentKey?: string;
  message?: string;
  txHash: string;
  createdAt: number;
}

export interface TipsIndex {
  tips: Tip[];
  totalTipsUsdc: number;
  topTippers: { address: string; totalUsdc: number }[];
  topReceivers: { address: string; totalUsdc: number }[];
  lastUpdated: number;
}

// ============================================================================
// READING STREAKS
// ============================================================================

export const STREAKS_INDEX_KEY = generateStorageKey("net-library-streaks-v1");

export interface UserStreak {
  address: string;
  currentStreak: number;
  longestStreak: number;
  lastReadDate: string;
  totalDaysActive: number;
  readingHistory: string[];
}

export interface StreaksIndex {
  users: { [address: string]: UserStreak };
  topStreaks: { address: string; streak: number }[];
  lastUpdated: number;
}

// ============================================================================
// ACHIEVEMENTS
// ============================================================================

export const ACHIEVEMENTS_INDEX_KEY = generateStorageKey("net-library-achievements-v1");

export type AchievementId =
  // Membership achievements
  | "founding-member"
  | "og-member"
  | "early-adopter"
  | "linked"
  // Upload achievements
  | "first-upload"
  | "contributor-5"
  | "contributor-25"
  | "contributor-100"
  // Upvote given achievements
  | "first-upvote"
  | "upvote-supporter"
  | "upvote-champion"
  | "upvote-whale"
  // Upvote received achievements
  | "upvoted-creator"
  | "trending-creator"
  | "viral-creator"
  | "legendary-creator"
  // Data uploaded achievements (MB)
  | "data-1mb"
  | "data-100mb"
  | "data-1000mb"
  | "data-10000mb"
  // Community achievements (comments)
  | "first-comment"
  | "commenter-10"
  | "commenter-100"
  | "commenter-1000";

// Achievement icon IDs - map to SVG icon components
export type AchievementIconId =
  | "shield" | "link" | "star" | "gem"  // Membership
  | "upload" | "sparkle" | "star-shine" | "crown"  // Uploads
  | "arrow-up" | "heart-green" | "circle-green" | "square-green"  // Upvotes Given
  | "heart" | "chart" | "rocket" | "crown-gold"  // Upvotes Received
  | "save" | "disc" | "disc-shine" | "archive"  // Data
  | "message" | "megaphone" | "broadcast" | "crystal";  // Comments

export interface Achievement {
  id: AchievementId;
  name: string;
  description: string;
  iconId: AchievementIconId;
  rarity: "common" | "rare" | "epic" | "legendary";
}

export const ACHIEVEMENTS: Achievement[] = [
  // === MEMBERSHIP (early adoption) - ROW 1: common → rare → epic → legendary ===
  { id: "early-adopter", name: "Member", description: "Join Net Library", iconId: "shield", rarity: "common" },
  { id: "linked", name: "Linked", description: "Add a Net Protocol link to your profile", iconId: "link", rarity: "rare" },
  { id: "og-member", name: "OG Member", description: "Be a top 1000 member", iconId: "star", rarity: "epic" },
  { id: "founding-member", name: "Founding Member", description: "Be a top 100 member", iconId: "gem", rarity: "legendary" },

  // === UPLOADS (what you contribute) - ROW 2: common → rare → epic → legendary ===
  { id: "first-upload", name: "First Upload", description: "Upload your first item", iconId: "upload", rarity: "common" },
  { id: "contributor-5", name: "Contributor", description: "Upload 5 items", iconId: "sparkle", rarity: "rare" },
  { id: "contributor-25", name: "Prolific", description: "Upload 25 items", iconId: "star-shine", rarity: "epic" },
  { id: "contributor-100", name: "Legend", description: "Upload 100 items", iconId: "crown", rarity: "legendary" },

  // === UPVOTES GIVEN (supporting others) - ROW 3: common → rare → epic → legendary ===
  { id: "first-upvote", name: "Supporter", description: "Give your first upvote", iconId: "arrow-up", rarity: "common" },
  { id: "upvote-supporter", name: "Alpha Giver", description: "Give 100+ upvotes", iconId: "heart-green", rarity: "rare" },
  { id: "upvote-champion", name: "Alpha King", description: "Give 1K+ upvotes", iconId: "circle-green", rarity: "epic" },
  { id: "upvote-whale", name: "Alpha Whale", description: "Give 10K+ upvotes", iconId: "square-green", rarity: "legendary" },

  // === UPVOTES RECEIVED (community recognition) - ROW 4: common → rare → epic → legendary ===
  { id: "upvoted-creator", name: "Appreciated", description: "Receive 100+ upvotes", iconId: "heart", rarity: "common" },
  { id: "trending-creator", name: "Trending", description: "Receive 1K+ upvotes", iconId: "chart", rarity: "rare" },
  { id: "viral-creator", name: "Viral", description: "Receive 10K+ upvotes", iconId: "rocket", rarity: "epic" },
  { id: "legendary-creator", name: "Legendary", description: "Receive 100K+ upvotes", iconId: "crown-gold", rarity: "legendary" },

  // === DATA UPLOADED (MB) - ROW 5: common → rare → epic → legendary ===
  { id: "data-1mb", name: "Data Drop", description: "Contribute 1 MB of onchain data", iconId: "save", rarity: "common" },
  { id: "data-100mb", name: "Builder", description: "Contribute 100 MB of onchain data", iconId: "disc", rarity: "rare" },
  { id: "data-1000mb", name: "Architect", description: "Contribute 1 GB of onchain data", iconId: "disc-shine", rarity: "epic" },
  { id: "data-10000mb", name: "Librarian", description: "Contribute 10 GB of onchain data", iconId: "archive", rarity: "legendary" },

  // === COMMUNITY (comments) - ROW 6: common → rare → epic → legendary ===
  { id: "first-comment", name: "1st Timer", description: "Post your first comment", iconId: "message", rarity: "common" },
  { id: "commenter-10", name: "Chatty", description: "Post 10 comments", iconId: "megaphone", rarity: "rare" },
  { id: "commenter-100", name: "Thought Leader", description: "Post 100 comments", iconId: "broadcast", rarity: "epic" },
  { id: "commenter-1000", name: "Oracle", description: "Post 1K+ comments", iconId: "crystal", rarity: "legendary" },
];

export interface UserAchievements {
  address: string;
  earnedAchievements: {
    id: AchievementId;
    earnedAt: number;
  }[];
}

export interface AchievementsIndex {
  users: { [address: string]: UserAchievements };
  recentUnlocks: { address: string; achievementId: AchievementId; earnedAt: number }[];
  lastUpdated: number;
}

// ============================================================================
// UPLOAD LIMITS & WARM-UP PERIOD
// ============================================================================

// App creator/team FIDs - bypass warm-up period entirely
export const APP_CREATOR_FIDS = new Set([
  282520,  // geaux
  248216,  // sartocrates
  6400,    // aspyn
]);

// Warm-up period: First 7 days as a member
export const WARMUP_PERIOD_DAYS = 7;

// Daily upload limits
export const WARMUP_DAILY_LIMIT = 10;      // During warm-up period (first 7 days)
export const REGULAR_DAILY_LIMIT = 100;    // After warm-up period

// Upload Pass: $10 to unlock 100 uploads/day during warm-up
export const UPLOAD_PASS_PRICE = 10;
export const UPLOAD_PASS_DAILY_LIMIT = 100;

// File size limit for all members (same for everyone)
export const MEMBER_MAX_FILE_SIZE_MB = 100;

export interface UserUploadStats {
  totalUploads: number;
  totalMBUploaded: number;
  daysSinceMembership: number; // Days since becoming a member
  uploadsToday: number;
  hasUploadPass: boolean; // User purchased Upload Pass for warm-up period
}

export interface UploadEligibility {
  canUpload: boolean;
  canPurchaseUploadPass: boolean; // true if in warm-up and can buy pass
  reason?: string;
  uploadsRemaining: number;
  maxFileSizeAllowed: number; // in bytes
  // Warm-up period info
  isInWarmupPeriod: boolean;
  daysRemainingInWarmup: number;
  dailyLimitExceeded: boolean;
  hasUploadPass: boolean;
}

export function checkUploadEligibility(
  stats: UserUploadStats,
  fileSizeBytes: number,
  isMember: boolean,
  fid?: number
): UploadEligibility {
  // Team members (app creators) bypass ALL limits — unlimited uploads, no warm-up.
  // Use 99999 instead of Infinity: JSON.stringify(Infinity) === "null", which causes
  // API responses to send null and the client to display "NaN uploads remaining".
  if (fid && APP_CREATOR_FIDS.has(fid)) {
    const maxFileSizeAllowed = MEMBER_MAX_FILE_SIZE_MB * 1024 * 1024;
    return {
      canUpload: true,
      canPurchaseUploadPass: false,
      uploadsRemaining: 99999,
      maxFileSizeAllowed,
      isInWarmupPeriod: false,
      daysRemainingInWarmup: 0,
      dailyLimitExceeded: false,
      hasUploadPass: stats.hasUploadPass,
    };
  }

  // Non-members cannot upload — membership is required.
  // Return canUpload: false and uploadsRemaining: 0 so the UI shows
  // "Join to upload" rather than implying they have uploads remaining.
  if (!isMember) {
    return {
      canUpload: false,
      canPurchaseUploadPass: false,
      reason: "Membership required to upload. Join Net Library to get started.",
      uploadsRemaining: 0,
      maxFileSizeAllowed: 0,
      isInWarmupPeriod: false,
      daysRemainingInWarmup: 0,
      dailyLimitExceeded: false,
      hasUploadPass: false,
    };
  }

  const maxFileSizeAllowed = MEMBER_MAX_FILE_SIZE_MB * 1024 * 1024;
  const isInWarmupPeriod = stats.daysSinceMembership < WARMUP_PERIOD_DAYS;
  const daysRemainingInWarmup = Math.max(0, WARMUP_PERIOD_DAYS - stats.daysSinceMembership);

  // Determine daily limit based on warm-up status and Upload Pass
  let dailyLimit: number;
  if (isInWarmupPeriod) {
    dailyLimit = stats.hasUploadPass ? UPLOAD_PASS_DAILY_LIMIT : WARMUP_DAILY_LIMIT;
  } else {
    dailyLimit = REGULAR_DAILY_LIMIT;
  }

  const uploadsRemaining = Math.max(0, dailyLimit - stats.uploadsToday);

  // Check file size limit (same for all members)
  if (fileSizeBytes > maxFileSizeAllowed) {
    return {
      canUpload: false,
      canPurchaseUploadPass: false,
      reason: `File exceeds the ${MEMBER_MAX_FILE_SIZE_MB}MB limit`,
      uploadsRemaining,
      maxFileSizeAllowed,
      isInWarmupPeriod,
      daysRemainingInWarmup,
      dailyLimitExceeded: false,
      hasUploadPass: stats.hasUploadPass,
    };
  }

  // Check daily limit
  if (stats.uploadsToday >= dailyLimit) {
    // Can only purchase Upload Pass if in warm-up period and don't already have one
    const canPurchasePass = isInWarmupPeriod && !stats.hasUploadPass;

    return {
      canUpload: false,
      canPurchaseUploadPass: canPurchasePass,
      reason: isInWarmupPeriod && !stats.hasUploadPass
        ? `Daily limit of ${dailyLimit} uploads reached (warm-up period: ${daysRemainingInWarmup} days remaining)`
        : `Daily limit of ${dailyLimit} uploads reached`,
      uploadsRemaining: 0,
      maxFileSizeAllowed,
      isInWarmupPeriod,
      daysRemainingInWarmup,
      dailyLimitExceeded: true,
      hasUploadPass: stats.hasUploadPass,
    };
  }

  return {
    canUpload: true,
    canPurchaseUploadPass: false,
    uploadsRemaining,
    maxFileSizeAllowed,
    isInWarmupPeriod,
    daysRemainingInWarmup,
    dailyLimitExceeded: false,
    hasUploadPass: stats.hasUploadPass,
  };
}

// ============================================================================
// COMPREHENSIVE DUPLICATE DETECTION
// ============================================================================

// Match types in order of severity (exact matches block upload, soft matches warn)
export type DuplicateMatchType =
  | "exact-hash"      // Same file content (SHA-256) - BLOCKS upload
  | "exact-isbn"      // Same ISBN/DOI - BLOCKS upload
  | "exact-title-author" // Same title AND author - BLOCKS upload
  | "similar-title"   // Very similar title - WARNS (soft match)
  | "same-author-similar-title"; // Same author with similar title - WARNS (soft match)

export interface DuplicateCheckResult {
  isDuplicate: boolean;
  existingEntry?: DiscoveryEntry;
  matchType?: DuplicateMatchType;
  isHardBlock: boolean; // true = cannot upload, false = warning only
  message?: string;
}

export interface DuplicateCheckInput {
  contentHash?: string;
  title: string;
  author?: string;
  isbn?: string;
}

// Normalize strings for comparison (lowercase, trim, remove common variations)
function normalizeString(str: string): string {
  return str
    .toLowerCase()
    .trim()
    .replace(/\.pdf$/i, "")
    .replace(/[-_]/g, " ")
    .replace(/\s+/g, " ");
}

// Normalize ISBN/DOI (remove dashes, spaces, standardize format)
function normalizeIsbn(isbn: string): string {
  return isbn
    .toLowerCase()
    .trim()
    .replace(/[-\s]/g, "")
    .replace(/^isbn[:\s]*/i, "")
    .replace(/^doi[:\s]*/i, "");
}

// Calculate simple similarity ratio between two strings
function similarityRatio(a: string, b: string): number {
  if (a === b) return 1;
  if (a.length === 0 || b.length === 0) return 0;

  // Check if one contains the other
  if (a.includes(b) || b.includes(a)) {
    const shorter = Math.min(a.length, b.length);
    const longer = Math.max(a.length, b.length);
    return shorter / longer;
  }

  // Simple word overlap check
  const wordsA = new Set(a.split(" ").filter(w => w.length > 2));
  const wordsB = new Set(b.split(" ").filter(w => w.length > 2));

  if (wordsA.size === 0 || wordsB.size === 0) return 0;

  let overlap = 0;
  for (const word of wordsA) {
    if (wordsB.has(word)) overlap++;
  }

  return overlap / Math.max(wordsA.size, wordsB.size);
}

export function checkForDuplicateContent(
  input: DuplicateCheckInput | string, // Support old signature (contentHash) or new (object)
  titleOrEntries?: string | DiscoveryEntry[],
  entriesArg?: DiscoveryEntry[]
): DuplicateCheckResult {
  // Handle both old and new function signatures for backward compatibility
  let contentHash: string | undefined;
  let title: string;
  let author: string | undefined;
  let isbn: string | undefined;
  let entries: DiscoveryEntry[];

  if (typeof input === "string") {
    // Old signature: checkForDuplicateContent(contentHash, title, entries)
    contentHash = input || undefined;
    title = (titleOrEntries as string) || "";
    entries = entriesArg || [];
  } else {
    // New signature: checkForDuplicateContent({ contentHash, title, author, isbn }, entries)
    contentHash = input.contentHash;
    title = input.title;
    author = input.author;
    isbn = input.isbn;
    entries = (titleOrEntries as DiscoveryEntry[]) || [];
  }

  const noMatch: DuplicateCheckResult = { isDuplicate: false, isHardBlock: false };

  if (entries.length === 0) return noMatch;

  // ========================================
  // HARD BLOCKS (cannot upload)
  // ========================================

  // 1. Exact content hash match (same file bytes)
  if (contentHash) {
    const hashMatch = entries.find(e => e.contentHash === contentHash);
    if (hashMatch) {
      return {
        isDuplicate: true,
        existingEntry: hashMatch,
        matchType: "exact-hash",
        isHardBlock: true,
        message: "This exact file has already been uploaded",
      };
    }
  }

  // 2. Exact ISBN/DOI match (same publication identifier)
  if (isbn) {
    const normalizedIsbn = normalizeIsbn(isbn);
    if (normalizedIsbn.length >= 8) { // Valid ISBN/DOI should be at least 8 chars
      const isbnMatch = entries.find(e =>
        e.isbn && normalizeIsbn(e.isbn) === normalizedIsbn
      );
      if (isbnMatch) {
        return {
          isDuplicate: true,
          existingEntry: isbnMatch,
          matchType: "exact-isbn",
          isHardBlock: true,
          message: `A file with this ISBN/DOI already exists: "${isbnMatch.title}"`,
        };
      }
    }
  }

  // 3. Exact title AND author match (same work)
  if (title && author) {
    const normalizedTitle = normalizeString(title);
    const normalizedAuthor = normalizeString(author);

    if (normalizedTitle.length > 3 && normalizedAuthor.length > 2) {
      const exactMatch = entries.find(e => {
        const entryTitle = normalizeString(e.title);
        const entryAuthor = normalizeString(e.author);
        return entryTitle === normalizedTitle && entryAuthor === normalizedAuthor;
      });

      if (exactMatch) {
        return {
          isDuplicate: true,
          existingEntry: exactMatch,
          matchType: "exact-title-author",
          isHardBlock: true,
          message: `"${exactMatch.title}" by ${exactMatch.author} already exists`,
        };
      }
    }
  }

  // ========================================
  // SOFT WARNINGS (can still upload)
  // ========================================

  const normalizedTitle = normalizeString(title);
  if (normalizedTitle.length < 3) return noMatch; // Title too short to check

  // 4. Same author with similar title (likely duplicate edition/version)
  if (author) {
    const normalizedAuthor = normalizeString(author);

    for (const entry of entries) {
      const entryAuthor = normalizeString(entry.author);
      const entryTitle = normalizeString(entry.title);

      // Check if same author
      if (entryAuthor === normalizedAuthor || similarityRatio(entryAuthor, normalizedAuthor) > 0.8) {
        // Check if similar title
        const titleSimilarity = similarityRatio(entryTitle, normalizedTitle);
        if (titleSimilarity > 0.7) {
          return {
            isDuplicate: true,
            existingEntry: entry,
            matchType: "same-author-similar-title",
            isHardBlock: false,
            message: `Similar work by same author exists: "${entry.title}"`,
          };
        }
      }
    }
  }

  // 5. Very similar title (fuzzy match)
  for (const entry of entries) {
    const entryTitle = normalizeString(entry.title);

    // Exact title match (without author check)
    if (entryTitle === normalizedTitle) {
      return {
        isDuplicate: true,
        existingEntry: entry,
        matchType: "similar-title",
        isHardBlock: false,
        message: `A file with a similar title exists: "${entry.title}"`,
      };
    }

    // High similarity check
    const similarity = similarityRatio(entryTitle, normalizedTitle);
    if (similarity > 0.85) {
      return {
        isDuplicate: true,
        existingEntry: entry,
        matchType: "similar-title",
        isHardBlock: false,
        message: `A file with a similar title exists: "${entry.title}"`,
      };
    }

    // One contains the other and similar length
    if (
      (entryTitle.includes(normalizedTitle) || normalizedTitle.includes(entryTitle)) &&
      Math.abs(entryTitle.length - normalizedTitle.length) < 10
    ) {
      return {
        isDuplicate: true,
        existingEntry: entry,
        matchType: "similar-title",
        isHardBlock: false,
        message: `A file with a similar title exists: "${entry.title}"`,
      };
    }
  }

  return noMatch;
}

// Helper to compute SHA-256 hash of file content (client-side)
export async function computeContentHash(file: File): Promise<string> {
  const buffer = await file.arrayBuffer();
  const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, "0")).join("");
  return hashHex;
}

// ============================================================================
// RE-EXPORT SDK FILE UTILITIES (v0.1.7+)
// ============================================================================

// Re-export file detection utilities from SDK for use throughout the app
export { fileToDataUri, detectFileTypeFromBase64, base64ToDataUri };

// ============================================================================
// GRIDS - Visual Curation Boards
// ============================================================================

export type GridVisibility = "public" | "hidden";

/**
 * Grid metadata - stored onchain via Net Protocol
 * The actual cell data is stored in KV for fast, free, mutable operations
 */
export interface Grid {
  id: string;                    // keccak256(encodePacked([creator, name, timestamp]))
  name: string;
  subtitle?: string;             // Optional subtitle/tagline
  description?: string;          // Optional longer description
  size: number;                  // N for N×N grid
  visibility: GridVisibility;
  creator: string;               // Wallet address
  createdAt: number;
  updatedAt: number;
  deleted?: boolean;             // Soft delete flag (KV only)
}

/**
 * Media type categories for grid cells
 */
export type GridMediaType = "image" | "gif" | "video" | "audio" | "text";

/**
 * Individual cell in a grid
 * Cells are stored in KV, not onchain
 */
export interface GridCell {
  row: number;                   // 0-indexed
  col: number;                   // 0-indexed
  cdnUrl: string;                // IPFS, Arweave, or other CDN URL
  contentType: string;           // image/png, video/mp4, etc.
  mediaType?: GridMediaType;     // Categorized media type for UI (image, gif, video, audio)
  addedAt: number;
  title?: string;                // Optional metadata
  coverUrl?: string;             // Cover art URL from discovery index
  contentKey?: string;           // Discovery index key (for linking to item detail page)
  operator?: string;             // Net Protocol operator address (needed for raw media URLs)
  storageType?: "regular" | "chunked" | "xml"; // Storage type from discovery entry (needed for proper content reconstruction)
}

/**
 * Detect media type from URL and content type
 */
export function detectGridMediaType(cdnUrl: string, contentType?: string): GridMediaType {
  const url = cdnUrl.toLowerCase();
  const mime = contentType?.toLowerCase() || "";

  // Check MIME type first (most reliable if provided)
  if (mime && mime !== "image/png") { // Skip default placeholder
    if (mime === "image/gif") return "gif";
    if (mime.startsWith("video/")) return "video";
    if (mime.startsWith("audio/")) return "audio";
    if (mime.startsWith("text/") || mime === "application/json" || mime === "application/xml") return "text";
    if (mime.startsWith("image/")) return "image";
  }

  // Check for GIFs by extension
  if (url.endsWith(".gif") || url.includes(".gif?")) {
    return "gif";
  }

  // Check for video by extension (including with query params)
  if (
    url.endsWith(".mp4") || url.includes(".mp4?") ||
    url.endsWith(".webm") || url.includes(".webm?") ||
    url.endsWith(".mov") || url.includes(".mov?") ||
    url.endsWith(".avi") || url.includes(".avi?") ||
    url.endsWith(".mkv") || url.includes(".mkv?")
  ) {
    return "video";
  }

  // Check for audio by extension (including with query params)
  if (
    url.endsWith(".mp3") || url.includes(".mp3?") ||
    url.endsWith(".wav") || url.includes(".wav?") ||
    url.endsWith(".ogg") || url.includes(".ogg?") ||
    url.endsWith(".flac") || url.includes(".flac?") ||
    url.endsWith(".m4a") || url.includes(".m4a?") ||
    url.endsWith(".aac") || url.includes(".aac?")
  ) {
    return "audio";
  }

  // Check for text files by extension
  if (
    url.endsWith(".txt") || url.includes(".txt?") ||
    url.endsWith(".md") || url.includes(".md?") ||
    url.endsWith(".markdown") ||
    url.endsWith(".html") || url.includes(".html?") ||
    url.endsWith(".htm") || url.includes(".htm?") ||
    url.endsWith(".json") || url.includes(".json?") ||
    url.endsWith(".xml") || url.includes(".xml?") ||
    url.endsWith(".csv") || url.includes(".csv?") ||
    url.endsWith(".log") || url.includes(".log?") ||
    url.endsWith(".rtf") || url.includes(".rtf?")
  ) {
    return "text";
  }

  // Default to image
  return "image";
}

/**
 * Get border color for media type
 */
export function getMediaTypeBorderColor(mediaType?: GridMediaType): string {
  switch (mediaType) {
    case "gif":
      return "#FFD700"; // Yellow for GIFs (animated content)
    case "video":
      return "#FFD700"; // Yellow for videos (animated content)
    case "audio":
      return "#00ff00"; // Green for audio (same as media files in stacks)
    case "text":
      return "#FFFFFF"; // White for text files
    case "image":
    default:
      return "#00ff00"; // Green for images (default)
  }
}

/**
 * Check if a media type is playable (audio, video, gif)
 */
export function isPlayableMedia(mediaType?: GridMediaType): boolean {
  return mediaType === "audio" || mediaType === "video" || mediaType === "gif";
}

/**
 * All cells for a grid - stored in KV
 * KV Key: `grid-cells:${gridId}`
 */
export interface GridCells {
  gridId: string;
  cells: GridCell[];
  updatedAt: number;
}

/**
 * Archived grid - permanent onchain snapshot
 * The image is a PNG with cell metadata embedded in tEXt chunks
 */
export interface ArchivedGrid {
  id: string;                    // keccak256 hash
  gridId: string;                // Reference to original live grid
  gridName: string;              // Grid name at time of archive
  gridSize: number;              // Grid size at time of archive
  cellCount: number;             // Number of cells at time of archive
  archivedAt: number;            // Timestamp when archived
  contentKey?: string;           // Net Protocol content key for PNG (if uploaded onchain)
  cdnUrl?: string;               // Full CDN URL for the archived PNG
  fileName?: string;             // Original filename for correct CDN URL format
  operator?: string;             // Operator address (uploader) for CDN URL construction
  creator: string;               // Address of who created the archive
  creatorFid?: number;           // Farcaster FID of creator
  searchText?: string;           // Concatenated cell titles/URLs for search indexing
}

/**
 * Grid with computed stats for display
 */
export interface GridWithStats extends Grid {
  cellCount: number;             // Number of filled cells
  totalCells: number;            // size * size
  upvoteCount: number;
  previewCells?: GridCell[];     // First few cells for thumbnail preview
  // Creator info (resolved from member registry or Neynar)
  creatorUsername?: string;
  creatorPfpUrl?: string;
  creatorFid?: number;
  // Archive status
  isArchived?: boolean;          // Whether this grid has been archived onchain
  archiveCount?: number;         // Number of archives for this grid
}

// KV storage key patterns for grids
export const GRIDS_KV_KEYS = {
  // Global registry of all grid IDs
  REGISTRY: "grids-registry",
  // Per-user grid list: `user-grids:${address}`
  userGrids: (address: string) => `user-grids:${address.toLowerCase()}`,
  // Grid metadata: `grid:${gridId}`
  grid: (gridId: string) => `grid:${gridId}`,
  // Grid cells: `grid-cells:${gridId}`
  gridCells: (gridId: string) => `grid-cells:${gridId}`,
  // Global archived grids registry
  ARCHIVED_REGISTRY: "archived-grids-registry",
  // Per-user archived grids: `user-archived-grids:${address}`
  userArchivedGrids: (address: string) => `user-archived-grids:${address.toLowerCase()}`,
  // Archived grid metadata: `archive:${archiveId}`
  archive: (archiveId: string) => `archive:${archiveId}`,
} as const;

/**
 * Generate a unique grid ID from creator, name, and timestamp
 * Uses same pattern as Net Protocol content keys for consistency
 */
export function generateGridId(creator: string, name: string, timestamp: number): `0x${string}` {
  return keccak256(
    encodePacked(
      ["address", "string", "uint256"],
      [creator as `0x${string}`, name, BigInt(timestamp)]
    )
  );
}

/**
 * Calculate the minimum grid size needed to fit N items
 * Returns the smallest N where N×N >= itemCount
 */
export function calculateGridSize(itemCount: number): number {
  return Math.ceil(Math.sqrt(itemCount));
}

/**
 * Check if a grid size requires the paid unlock ($2 for 6×6+)
 */
export function requiresGridUnlock(size: number): boolean {
  return size >= 6;
}

// Grid unlock pricing
export const GRID_UNLOCK_PRICE_USD = 2;
export const GRID_FREE_MAX_SIZE = 5; // 5×5 is the largest free grid

/**
 * Generate a score key for grid upvotes
 * Uses the same pattern as content upvotes: keccak256(encodePacked([gridId, creator]))
 */
export function generateGridScoreKey(gridId: string, creator: string): `0x${string}` {
  // Ensure gridId is bytes32 format
  let key = gridId.startsWith("0x") ? gridId : `0x${gridId}`;
  if (key.length < 66) {
    const hexPart = key.slice(2);
    const paddedHex = hexPart.padStart(64, "0");
    key = `0x${paddedHex}`;
  }
  if (key.length > 66) {
    key = key.slice(0, 66);
  }

  return keccak256(
    encodePacked(
      ["bytes32", "address"],
      [key as `0x${string}`, creator.toLowerCase() as `0x${string}`]
    )
  );
}
src/lib/net-relay.ts
/**
 * Net Protocol Relay Service - x402 Gasless Storage
 *
 * This module provides gasless file uploads to Net Protocol storage.
 * Users pay with USDC instead of ETH for gas fees via x402 payment protocol.
 *
 * Flow:
 * 1. Check backend wallet balance (derived from user address)
 * 2. If insufficient, user funds wallet via x402 USDC payment
 * 3. Create relay session (authenticates user)
 * 4. Submit storage transactions via relay (backend wallet pays gas)
 * 5. Wait for on-chain confirmation
 *
 * Benefits:
 * - Single USDC payment instead of 10-15 ETH signatures
 * - Backend wallet handles all storage transactions
 * - Accurate cost estimation upfront
 * - Recovery support for interrupted uploads
 */

import type { Address } from "viem";
import { BASE_CHAIN_ID } from "@/lib/net-protocol";
import { isCoinbaseWalletUA } from "@/lib/ua-utils";

// =============================================================================
// CONFIGURATION
// =============================================================================

export const RELAY_CONFIG = {
  // Net Protocol relay API URL
  apiUrl: "https://www.netprotocol.app",

  // Chain to use for relay transactions
  chainId: BASE_CHAIN_ID,

  // Whether relay is enabled
  enabled: true,

  // Secret key for backend wallet derivation
  secretKey: "[REDACTED]",

  // Session duration in seconds (1 hour)
  sessionDurationSec: 3600,

  // x402 facilitator URL for payment verification
  facilitatorUrl: "https://x402.org/facilitator",

  // USDC contract on Base
  usdcAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" as Address,

  // Minimum funding amount ($0.10)
  minFundingUsdc: 0.1,
} as const;

// =============================================================================
// PRICING - Estimated costs (actual costs come from relay API)
// =============================================================================

export const RELAY_PRICING = {
  // Base cost per transaction submitted via relay
  baseTxCostUsdc: 0.01, // $0.01 per transaction

  // Cost per KB of calldata
  perKbCostUsdc: 0.001, // $0.001 per KB

  // Maximum cost cap per upload
  maxUploadCostUsdc: 5.0, // $5 max per file

  // Low balance threshold - prompt to refill when below this
  lowBalanceThresholdUsdc: 0.5, // $0.50 - suggest refill

  // Recommended refill amount when prompted (default suggestion)
  recommendedFundingUsdc: 1.0, // $1 for multiple uploads
} as const;

// =============================================================================
// TYPES
// =============================================================================

export interface RelaySession {
  sessionToken: string;
  expiresAt: number;
  operatorAddress: Address;
  backendWalletAddress: Address;
  remainingCapacityUsdc: number;
}

export interface RelayTransactionConfig {
  to: Address;
  data: `0x${string}`;
  description?: string;
  chunkIndex?: number;
  idempotencyKey?: string; // For chunk deduplication
}

export interface RelaySubmitResult {
  success: boolean;
  txHashes: `0x${string}`[];
  totalCostUsdc: number;
  error?: string;
  skippedChunks?: number; // Chunks that already existed
}

export interface RelayUploadEstimate {
  totalTransactions: number;
  totalCalldataKb: number;
  estimatedCostUsdc: number;
  breakdown: {
    txCost: number;
    dataCost: number;
  };
}

export interface RelayBalanceInfo {
  backendWalletAddress: Address;
  // Actual ETH balance (relay stores gas in ETH)
  balanceEth: number;
  // Approximate USDC equivalent (ETH * rate, for display only)
  balanceUsdc: number;
  // Raw balance in wei
  balanceWei: string;
  // Can afford an upload (SDK-calculated with actual gas prices)
  sufficient: boolean;
  // Estimated shortfall in USDC equivalent
  shortfallUsdc: number;
  // Balance is below recommended minimum
  lowBalance: boolean;
  // Suggested funding amount when insufficient or low
  recommendedFundingUsdc: number;
}

export interface RelayFundingResult {
  success: boolean;
  txHash?: `0x${string}`;
  newBalanceUsdc?: number;
  error?: string;
  x402Response?: {
    paymentRequired: boolean;
    paymentUrl?: string;
    payTo?: string; // Address to send USDC to
    amount?: number; // Amount in USDC (not wei)
    asset?: string; // USDC contract address
  };
}

export interface RelayTransactionStatus {
  txHash: `0x${string}`;
  status: "pending" | "confirmed" | "failed";
  confirmations: number;
  blockNumber?: number;
  gasUsed?: string;
  error?: string;
}

export type RelayPlatform = "farcaster" | "base-app" | "browser";

// =============================================================================
// API RESPONSE TYPES
// =============================================================================

interface _BalanceApiResponse {
  success?: boolean;
  backendWallet?: string;
  backendWalletAddress?: string; // API returns this field name
  balance?: string; // Wei string (deprecated)
  balanceWei?: string; // Wei string
  balanceEth?: string; // ETH string
  balanceUsdc?: number; // Legacy
  sufficientBalance?: boolean;
  minRequiredWei?: string;
  minRequiredEth?: string;
  error?: string;
}

interface SessionApiResponse {
  sessionToken: string;
  expiresAt: number;
  backendWallet: string;
  remainingCapacity: number;
}

interface SubmitApiResponse {
  success: boolean;
  txHashes: string[];
  totalCost: number;
  skippedChunks?: number;
  error?: string;
}

interface FundApiResponse {
  success: boolean;
  txHash?: string;
  newBalance?: number;
  error?: string;
}

interface StatusApiResponse {
  txHash: string;
  status: "pending" | "confirmed" | "failed";
  confirmations: number;
  blockNumber?: number;
  gasUsed?: string;
  error?: string;
}

// =============================================================================
// RELAY CLIENT - Core Implementation
// =============================================================================

/**
 * Check if relay service is available and enabled
 */
export function isRelayEnabled(): boolean {
  return RELAY_CONFIG.enabled;
}

/**
 * Get the relay API base URL
 */
function getApiUrl(path: string): string {
  const base = RELAY_CONFIG.apiUrl.replace(/\/$/, "");
  // Try /api prefix first, fall back to direct path
  return `${base}/api${path}`;
}

/**
 * Check backend wallet balance for a user
 * Uses local API proxy that calls the @net-protocol/relay SDK server-side
 * (CORS prevents direct browser calls to netprotocol.app)
 *
 * Logic:
 * - `sufficient`: Can they afford THIS specific upload? (balance >= estimated cost)
 * - `lowBalance`: Is balance below $1? (suggest refilling, but don't block)
 */
export async function checkRelayBalance(
  operatorAddress: Address,
  _estimatedCostUsdc?: number
): Promise<RelayBalanceInfo> {
  console.log(`[RELAY] Checking balance for operator ${operatorAddress.slice(0, 10)}...`);

  try {
    // Call our local API proxy (uses SDK server-side to avoid CORS)
    const response = await fetch("/api/relay/balance", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        operatorAddress,
        chainId: RELAY_CONFIG.chainId,
      }),
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({ error: "Unknown error" }));
      throw new Error(errorData.error || `API error: ${response.status}`);
    }

    const result = await response.json();
    console.log(`[RELAY] Balance API result:`, result);

    if (!result.success && result.error) {
      throw new Error(result.error);
    }

    const backendWallet = result.backendWalletAddress as Address;

    // The relay backend wallet stores ETH for paying gas
    // But users fund with USDC (which the relay converts to ETH)
    // We show ETH balance but frame it as "gas credits" equivalent
    const balanceEth = parseFloat(result.balanceEth || "0");

    // IMPORTANT: Trust the SDK's sufficientBalance flag - it's calculated server-side
    // with actual gas price info, not our estimated conversions
    const sufficient = result.sufficientBalance ?? false;

    // Use SDK's minimum required values for accurate thresholds
    const minRequiredEth = parseFloat(result.minRequiredEth || "0.00001");

    // Convert ETH to approximate USDC for display purposes only
    // This is a rough estimate - actual conversion rates vary
    const ETH_TO_USDC_RATE = 3000; // ~$3000/ETH
    const balanceUsdc = balanceEth * ETH_TO_USDC_RATE;
    const minRequiredUsdc = minRequiredEth * ETH_TO_USDC_RATE;

    // Is balance getting low? Use SDK's minimum as the threshold
    const lowBalance = balanceEth < minRequiredEth * 2; // Below 2x minimum = low

    console.log(`[RELAY] Balance: ${balanceEth} ETH (~$${balanceUsdc.toFixed(4)} equiv), Min required: ${minRequiredEth} ETH, Sufficient: ${sufficient}, Low: ${lowBalance}`);

    return {
      backendWalletAddress: backendWallet,
      balanceUsdc,  // Display value (ETH * rate)
      balanceWei: result.balanceWei || "0",
      balanceEth,   // Actual ETH balance
      sufficient,   // Trust SDK's calculation
      shortfallUsdc: sufficient ? 0 : Math.max(0, minRequiredUsdc - balanceUsdc),
      lowBalance,
      // Show recommended funding when insufficient OR low balance
      recommendedFundingUsdc: (sufficient && !lowBalance) ? 0 : RELAY_PRICING.recommendedFundingUsdc,
    };
  } catch (error) {
    const errMsg = error instanceof Error ? error.message : String(error);
    console.error("[RELAY] Balance check error:", errMsg);

    // Re-throw the error - we can't proceed without the backend wallet address from the API
    throw new Error(`Relay service unavailable: ${errMsg}`);
  }
}

/**
 * Fund the backend wallet via x402 USDC payment
 * Returns payment info that triggers the x402 flow
 * Uses local API proxy to avoid CORS issues
 */
export async function fundBackendWallet(
  operatorAddress: Address,
  amountUsdc: number
): Promise<RelayFundingResult> {
  console.log(`[RELAY] Initiating funding: $${amountUsdc.toFixed(2)} USDC for ${operatorAddress.slice(0, 10)}...`);

  try {
    // Call our local API proxy (avoids CORS)
    const response = await fetch("/api/relay/fund", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        operatorAddress,
        chainId: RELAY_CONFIG.chainId,
        amountUsdc, // Pass the user-selected amount
      }),
    });

    // Check for x402 payment required response
    if (response.status === 402) {
      const paymentInfo = await response.json();
      console.log("[RELAY] x402 payment required - FULL response:", JSON.stringify(paymentInfo, null, 2));

      // x402 response has accepts array with payment details
      // The field names may vary - try multiple possible field names
      const accepts = paymentInfo.accepts?.[0];
      console.log("[RELAY] x402 accepts[0]:", JSON.stringify(accepts, null, 2));

      // Try different possible field names for payTo address
      const payTo = accepts?.payTo || accepts?.payToAddress || accepts?.recipient || accepts?.address;

      // Try different possible field names for amount
      const maxAmount = accepts?.maxAmountRequired || accepts?.maxAmount || accepts?.amount;

      // If maxAmount is a string that looks like a big number (wei), convert it
      let amountRequired = amountUsdc;
      if (maxAmount) {
        const maxAmountNum = Number(maxAmount);
        // If the number is > 1000000, it's likely in wei (6 decimals for USDC)
        if (maxAmountNum > 1_000_000) {
          amountRequired = maxAmountNum / 1_000_000;
        } else {
          // It's already in USDC units
          amountRequired = maxAmountNum;
        }
      }

      console.log("[RELAY] x402 parsed - payTo:", payTo, "amount:", amountRequired);

      // Validate payTo address before returning
      if (!payTo) {
        console.error("[RELAY] x402 response missing payTo! Full accepts object:", JSON.stringify(accepts, null, 2));
        console.error("[RELAY] Full paymentInfo object:", JSON.stringify(paymentInfo, null, 2));
      }

      return {
        success: false,
        x402Response: {
          paymentRequired: true,
          paymentUrl: paymentInfo.paymentUrl,
          payTo: payTo,
          amount: amountRequired,
          asset: accepts?.asset,
        },
      };
    }

    if (!response.ok) {
      const errorText = await response.text();
      console.error(`[RELAY] Funding failed: ${response.status} ${errorText}`);
      return {
        success: false,
        error: `Funding failed: ${response.status}`,
      };
    }

    const data: FundApiResponse = await response.json();

    if (data.success) {
      console.log(`[RELAY] Funding successful: tx ${data.txHash}, new balance: $${data.newBalance?.toFixed(4)}`);
      return {
        success: true,
        txHash: data.txHash as `0x${string}`,
        newBalanceUsdc: data.newBalance,
      };
    }

    return {
      success: false,
      error: data.error || "Unknown funding error",
    };
  } catch (error) {
    console.error("[RELAY] Funding error:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Network error during funding",
    };
  }
}

/**
 * Create a relay session for submitting transactions
 */
export async function createRelaySession(
  operatorAddress: Address,
  platform: RelayPlatform
): Promise<{ success: false; error: string } | { success: true; session: RelaySession }> {
  const url = getApiUrl("/relay/session");

  console.log(`[RELAY] Creating session for ${operatorAddress.slice(0, 10)}... (platform: ${platform})`);

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Relay-Secret": RELAY_CONFIG.secretKey,
      },
      body: JSON.stringify({
        operatorAddress,
        chainId: RELAY_CONFIG.chainId,
        platform,
        durationSec: RELAY_CONFIG.sessionDurationSec,
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error(`[RELAY] Session creation failed: ${response.status} ${errorText}`);
      return {
        success: false,
        error: `Session creation failed: ${response.status}`,
      };
    }

    const data: SessionApiResponse = await response.json();

    console.log(`[RELAY] Session created, expires at ${new Date(data.expiresAt * 1000).toISOString()}`);

    return {
      success: true,
      session: {
        sessionToken: data.sessionToken,
        expiresAt: data.expiresAt,
        operatorAddress,
        backendWalletAddress: data.backendWallet as Address,
        remainingCapacityUsdc: data.remainingCapacity,
      },
    };
  } catch (error) {
    console.error("[RELAY] Session creation error:", error);
    return {
      success: false,
      error: error instanceof Error ? error.message : "Network error creating session",
    };
  }
}

/**
 * Submit transactions via relay service
 * Supports chunk idempotency - already-stored chunks are skipped
 */
export async function submitTransactionsViaRelay(
  session: RelaySession,
  transactions: RelayTransactionConfig[],
  platform: RelayPlatform
): Promise<RelaySubmitResult> {
  const url = getApiUrl("/relay/submit");

  console.log(`[RELAY] Submitting ${transactions.length} transactions via relay...`);

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Relay-Secret": RELAY_CONFIG.secretKey,
        "X-Session-Token": session.sessionToken,
      },
      body: JSON.stringify({
        operatorAddress: session.operatorAddress,
        chainId: RELAY_CONFIG.chainId,
        platform,
        transactions: transactions.map(tx => ({
          to: tx.to,
          data: tx.data,
          idempotencyKey: tx.idempotencyKey,
          description: tx.description,
        })),
      }),
    });

    if (!response.ok) {
      const errorText = await response.text();
      console.error(`[RELAY] Submit failed: ${response.status} ${errorText}`);
      return {
        success: false,
        txHashes: [],
        totalCostUsdc: 0,
        error: `Submit failed: ${response.status}`,
      };
    }

    const data: SubmitApiResponse = await response.json();

    if (data.success) {
      console.log(`[RELAY] Submit successful: ${data.txHashes.length} txs, cost: $${data.totalCost.toFixed(4)}, skipped: ${data.skippedChunks || 0}`);
      return {
        success: true,
        txHashes: data.txHashes as `0x${string}`[],
        totalCostUsdc: data.totalCost,
        skippedChunks: data.skippedChunks,
      };
    }

    return {
      success: false,
      txHashes: [],
      totalCostUsdc: 0,
      error: data.error || "Unknown submit error",
    };
  } catch (error) {
    console.error("[RELAY] Submit error:", error);
    return {
      success: false,
      txHashes: [],
      totalCostUsdc: 0,
      error: error instanceof Error ? error.message : "Network error during submit",
    };
  }
}

/**
 * Check transaction status (for confirmation polling)
 */
export async function checkTransactionStatus(
  txHash: `0x${string}`
): Promise<RelayTransactionStatus> {
  const url = getApiUrl(`/relay/status/${txHash}`);

  try {
    const response = await fetch(url, {
      method: "GET",
      headers: {
        "X-Relay-Secret": RELAY_CONFIG.secretKey,
      },
    });

    if (!response.ok) {
      return {
        txHash,
        status: "pending",
        confirmations: 0,
      };
    }

    const data: StatusApiResponse = await response.json();

    return {
      txHash: data.txHash as `0x${string}`,
      status: data.status,
      confirmations: data.confirmations,
      blockNumber: data.blockNumber,
      gasUsed: data.gasUsed,
      error: data.error,
    };
  } catch (error) {
    console.error("[RELAY] Status check error:", error);
    return {
      txHash,
      status: "pending",
      confirmations: 0,
    };
  }
}

/**
 * Wait for all transactions to confirm
 */
export async function waitForRelayConfirmations(
  txHashes: `0x${string}`[],
  options?: {
    timeoutMs?: number;
    pollIntervalMs?: number;
    onProgress?: (confirmed: number, total: number) => void;
  }
): Promise<{ success: boolean; confirmed: number; failed: `0x${string}`[] }> {
  const timeoutMs = options?.timeoutMs || 120000; // 2 minutes default
  const pollIntervalMs = options?.pollIntervalMs || 2000; // 2 seconds
  const startTime = Date.now();

  const confirmedSet = new Set<string>();
  const failedSet = new Set<string>();

  console.log(`[RELAY] Waiting for ${txHashes.length} transactions to confirm...`);

  while (Date.now() - startTime < timeoutMs) {
    for (const txHash of txHashes) {
      if (confirmedSet.has(txHash) || failedSet.has(txHash)) continue;

      const status = await checkTransactionStatus(txHash);

      if (status.status === "confirmed") {
        confirmedSet.add(txHash);
        console.log(`[RELAY] TX ${txHash.slice(0, 10)}... confirmed`);
      } else if (status.status === "failed") {
        failedSet.add(txHash);
        console.log(`[RELAY] TX ${txHash.slice(0, 10)}... FAILED: ${status.error}`);
      }
    }

    options?.onProgress?.(confirmedSet.size, txHashes.length);

    // All done?
    if (confirmedSet.size + failedSet.size === txHashes.length) {
      break;
    }

    await new Promise(resolve => setTimeout(resolve, pollIntervalMs));
  }

  const success = failedSet.size === 0 && confirmedSet.size === txHashes.length;
  console.log(`[RELAY] Confirmation complete: ${confirmedSet.size}/${txHashes.length} confirmed, ${failedSet.size} failed`);

  return {
    success,
    confirmed: confirmedSet.size,
    failed: Array.from(failedSet) as `0x${string}`[],
  };
}

// =============================================================================
// COST ESTIMATION
// =============================================================================

/**
 * Calculate estimated cost for a relay upload (client-side estimate)
 */
export function estimateRelayCost(
  transactions: RelayTransactionConfig[]
): RelayUploadEstimate {
  const txCost = transactions.length * RELAY_PRICING.baseTxCostUsdc;

  // Calculate total calldata size
  const totalCalldataBytes = transactions.reduce((sum, tx) => {
    return sum + (tx.data.length - 2) / 2; // Remove 0x prefix, convert hex to bytes
  }, 0);
  const totalCalldataKb = totalCalldataBytes / 1024;
  const dataCost = totalCalldataKb * RELAY_PRICING.perKbCostUsdc;

  const estimatedCostUsdc = Math.min(
    txCost + dataCost,
    RELAY_PRICING.maxUploadCostUsdc
  );

  return {
    totalTransactions: transactions.length,
    totalCalldataKb,
    estimatedCostUsdc,
    breakdown: { txCost, dataCost },
  };
}

/**
 * Estimate cost for a file upload (before preparing transactions)
 */
export function estimateFileUploadCost(
  fileSize: number,
  storageType: "regular" | "chunked" | "xml"
): RelayUploadEstimate {
  // Estimate transaction count based on storage type
  // Actual transactions created:
  // - XML: 1 tx per 80KB chunk + 1 XML metadata tx + 1 book metadata tx
  // - Chunked: 1 tx for data + 1 book metadata tx
  // - Regular: 1 tx for data + 1 book metadata tx

  let txCount = 2; // Base: data tx + book metadata tx
  let totalCalldataKb = fileSize / 1024;

  if (storageType === "xml") {
    // XML: One transaction per 80KB chunk (sub-chunks are bundled in single tx)
    const XML_CHUNK_SIZE = 80000;
    const base64Size = fileSize * 1.33; // Base64 encoding overhead
    const xmlChunkCount = Math.ceil(base64Size / XML_CHUNK_SIZE);
    // xmlChunkCount data txs + 1 XML metadata tx + 1 book metadata tx
    txCount = xmlChunkCount + 2;
    totalCalldataKb = (base64Size / 1024) * 1.1; // Slight overhead for compression headers
  }
  // Chunked and Regular: txCount stays at 2 (data + book metadata)

  const txCost = txCount * RELAY_PRICING.baseTxCostUsdc;
  const dataCost = totalCalldataKb * RELAY_PRICING.perKbCostUsdc;
  const estimatedCostUsdc = Math.min(
    txCost + dataCost,
    RELAY_PRICING.maxUploadCostUsdc
  );

  return {
    totalTransactions: txCount,
    totalCalldataKb,
    estimatedCostUsdc,
    breakdown: { txCost, dataCost },
  };
}

/**
 * Get required USDC amount for funding (includes buffer)
 */
export function getRequiredFunding(estimatedCostUsdc: number): number {
  // Add 20% buffer and round up to minimum
  const withBuffer = estimatedCostUsdc * 1.2;
  return Math.max(RELAY_CONFIG.minFundingUsdc, withBuffer);
}

/**
 * Convert USDC amount to wei (6 decimals)
 */
export function usdcToWei(amount: number): bigint {
  return BigInt(Math.ceil(amount * 1_000_000));
}

/**
 * Convert wei to USDC amount
 */
export function weiToUsdc(wei: bigint | string): number {
  const weiNum = typeof wei === "string" ? BigInt(wei) : wei;
  return Number(weiNum) / 1_000_000;
}

// =============================================================================
// PLATFORM DETECTION
// =============================================================================

/**
 * Detect current platform
 */
export function detectRelayPlatform(): RelayPlatform {
  if (typeof window === "undefined") return "farcaster";

  // Check for Farcaster frame context
  const isFarcaster = !!(
    window.parent !== window ||
    document.referrer.includes("warpcast") ||
    document.referrer.includes("farcaster")
  );

  if (isFarcaster) return "farcaster";

  // Check for Base App / Coinbase Wallet in-app browser via shared UA utility.
  if (isCoinbaseWalletUA(navigator.userAgent)) {
    return "base-app";
  }

  return "browser";
}

/**
 * Get the appropriate approval strategy for the platform
 */
export function getApprovalStrategy(platform: RelayPlatform): {
  method: "sendCalls" | "writeContract" | "sendTransaction";
  notes: string;
} {
  if (platform === "farcaster") {
    return {
      method: "sendCalls",
      notes: "Farcaster Mini Apps should use EIP-5792 sendCalls for USDC approval",
    };
  }

  if (platform === "base-app") {
    return {
      method: "sendCalls",
      notes: "Base App Smart Wallets support sendCalls natively",
    };
  }

  // Browser with injected wallet
  return {
    method: "writeContract",
    notes: "Standard browser wallets use writeContract for approvals",
  };
}

// =============================================================================
// LOGGING / DIAGNOSTICS
// =============================================================================

export interface RelayDiagnostics {
  sessionId: string;
  platform: RelayPlatform;
  startTime: number;
  phases: {
    name: string;
    startTime: number;
    endTime?: number;
    success?: boolean;
    error?: string;
    details?: Record<string, unknown>;
  }[];
  totalTransactions: number;
  completedTransactions: number;
  skippedTransactions: number;
  totalCostUsdc: number;
  outcome?: "success" | "error" | "cancelled" | "fallback";
}

export function createRelayDiagnostics(platform: RelayPlatform): RelayDiagnostics {
  return {
    sessionId: `relay_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
    platform,
    startTime: Date.now(),
    phases: [],
    totalTransactions: 0,
    completedTransactions: 0,
    skippedTransactions: 0,
    totalCostUsdc: 0,
  };
}

export function logRelayPhase(
  diag: RelayDiagnostics,
  phaseName: string,
  details?: Record<string, unknown>
): void {
  const elapsed = Date.now() - diag.startTime;
  console.log(`[RELAY] [${diag.sessionId}] [+${elapsed}ms] ${phaseName}`, details || "");

  diag.phases.push({
    name: phaseName,
    startTime: Date.now(),
    details,
  });
}

export function endRelayPhase(
  diag: RelayDiagnostics,
  phaseName: string,
  success: boolean,
  error?: string
): void {
  const phase = diag.phases.find(p => p.name === phaseName && !p.endTime);
  if (phase) {
    phase.endTime = Date.now();
    phase.success = success;
    phase.error = error;
  }

  const elapsed = Date.now() - diag.startTime;
  const duration = phase ? phase.endTime! - phase.startTime : 0;
  console.log(`[RELAY] [${diag.sessionId}] [+${elapsed}ms] ${phaseName} END`, {
    success,
    durationMs: duration,
    error,
  });
}

export function finalizeRelayDiagnostics(
  diag: RelayDiagnostics,
  outcome: "success" | "error" | "cancelled" | "fallback",
  errorMessage?: string
): void {
  diag.outcome = outcome;

  const totalDuration = Date.now() - diag.startTime;
  console.log(`[RELAY] [${diag.sessionId}] ========== SESSION SUMMARY ==========`);
  console.log(`[RELAY] Outcome: ${outcome}`);
  console.log(`[RELAY] Duration: ${(totalDuration / 1000).toFixed(1)}s`);
  console.log(`[RELAY] Transactions: ${diag.completedTransactions}/${diag.totalTransactions} (${diag.skippedTransactions} skipped)`);
  console.log(`[RELAY] Cost: $${diag.totalCostUsdc.toFixed(4)} USDC`);
  if (errorMessage) {
    console.log(`[RELAY] Error: ${errorMessage}`);
  }
  console.log(`[RELAY] =====================================`);
}
src/lib/receipt-renderer.ts
/**
 * Shared receipt renderer for social archive images.
 *
 * Extracted from /api/social/receipt so that both:
 *   1. The receipt API route (GET/POST)
 *   2. The archive route (POST /api/v1/archive)
 * can call the rendering function directly without an internal HTTP round-trip.
 *
 * The receipt API route wraps this in an HTTP handler.
 * The archive route calls renderSocialReceipt() directly to avoid the extra
 * network hop (and associated serverless timeout risk).
 *
 * Returns: { dataUrl: string } — "data:image/png;base64,..." ready to upload.
 */

// eslint-disable-next-line @typescript-eslint/no-require-imports
const { ImageResponse } = require("next/og");

import { getEmojiFonts } from "@/lib/emoji-font";

// ---------------------------------------------------------------------------
// Types (re-exported so the receipt API route doesn't have to re-declare them)
// ---------------------------------------------------------------------------

export type SocialPlatform =
  | "farcaster"
  | "twitter"
  | "youtube"
  | "instagram"
  | "tiktok"
  | "reddit"
  | "bluesky"
  | "threads"
  | "linkedin"
  | "paragraph";

export const PLATFORM_INFO: Record<SocialPlatform, { name: string; color: string }> = {
  farcaster: { name: "Farcaster", color: "#8B5CF6" },
  twitter: { name: "Twitter/X", color: "#000000" },
  youtube: { name: "YouTube", color: "#FF0000" },
  instagram: { name: "Instagram", color: "#E1306C" },
  tiktok: { name: "TikTok", color: "#00F2EA" },
  reddit: { name: "Reddit", color: "#FF4500" },
  bluesky: { name: "Bluesky", color: "#0085FF" },
  threads: { name: "Threads", color: "#000000" },
  linkedin: { name: "LinkedIn", color: "#0077B5" },
  paragraph: { name: "Paragraph", color: "#10B981" },
};

export interface SocialAuthor {
  displayName: string;
  username: string;
  avatarUrl?: string;
  fid?: number;
  verified?: boolean;
}

export interface SocialContent {
  platform: SocialPlatform;
  id: string;
  url: string;
  text: string;
  author: SocialAuthor;
  timestamp: string | Date;
  images?: string[];
  thumbnailUrl?: string;
  likes?: number;
  reposts?: number;
  replies?: number;
  views?: number;
  score?: number;
  subreddit?: string;
  duration?: string;
}

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

function formatDate(date: Date | string): string {
  const d = typeof date === "string" ? new Date(date) : date;
  return new Intl.DateTimeFormat("en-US", {
    month: "short",
    day: "numeric",
    year: "numeric",
    hour: "numeric",
    minute: "2-digit",
  }).format(d);
}

function arrayBufferToBase64(buffer: ArrayBuffer): string {
  const bytes = new Uint8Array(buffer);
  let binary = "";
  for (let i = 0; i < bytes.byteLength; i++) {
    binary += String.fromCharCode(bytes[i]);
  }
  return btoa(binary);
}

async function fetchImageAsDataUrl(url: string, timeoutMs = 8000): Promise<string | null> {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
  try {
    const response = await fetch(url, {
      headers: { "User-Agent": "Mozilla/5.0 (compatible; NetLibrary/1.0)" },
      signal: controller.signal,
    });
    clearTimeout(timeoutId);
    if (!response.ok) return null;
    const contentType = response.headers.get("content-type") || "image/jpeg";
    const arrayBuffer = await response.arrayBuffer();
    const base64 = arrayBufferToBase64(arrayBuffer);
    return `data:${contentType};base64,${base64}`;
  } catch {
    clearTimeout(timeoutId);
    return null;
  }
}

interface ArchivedMedia {
  avatarDataUrl: string | null;
  imageDataUrls: string[];
  thumbnailDataUrl: string | null;
}

async function archiveMedia(content: SocialContent): Promise<ArchivedMedia> {
  const results: ArchivedMedia = { avatarDataUrl: null, imageDataUrls: [], thumbnailDataUrl: null };
  const fetchPromises: Promise<void>[] = [];

  if (content.author?.avatarUrl) {
    fetchPromises.push(fetchImageAsDataUrl(content.author.avatarUrl).then((d) => { results.avatarDataUrl = d; }));
  }

  const imagesToFetch = (content.images || []).slice(0, 4);
  for (let i = 0; i < imagesToFetch.length; i++) {
    const imgUrl = imagesToFetch[i];
    fetchPromises.push(fetchImageAsDataUrl(imgUrl).then((d) => { if (d) results.imageDataUrls[i] = d; }));
  }

  if (content.thumbnailUrl) {
    fetchPromises.push(fetchImageAsDataUrl(content.thumbnailUrl).then((d) => { results.thumbnailDataUrl = d; }));
  }

  try {
    await Promise.all(fetchPromises);
  } catch {
    // partial results OK
  }
  results.imageDataUrls = results.imageDataUrls.filter(Boolean);
  return results;
}

// JSX-returning helpers — kept here so they can be used inside ImageResponse()
// which accepts JSX produced by React.createElement. Satori (the Vercel renderer
// used by ImageResponse) processes the element tree at render time.
function getPlatformIcon(platform: SocialPlatform, size = 24) {
  const color = PLATFORM_INFO[platform]?.color ?? "#ffffff";
  // eslint-disable-next-line @typescript-eslint/no-require-imports
  const React = require("react");

  switch (platform) {
    case "farcaster":
      return React.createElement("svg", { width: size, height: size, viewBox: "0 0 24 24", fill: color },
        React.createElement("path", { d: "M18.24 2.4H5.76C3.888 2.4 2.4 3.888 2.4 5.76v12.48c0 1.872 1.488 3.36 3.36 3.36h12.48c1.872 0 3.36-1.488 3.36-3.36V5.76c0-1.872-1.488-3.36-3.36-3.36zm-1.44 15.12h-2.16v-5.04c0-1.392-1.128-2.52-2.52-2.52h-.24c-1.392 0-2.52 1.128-2.52 2.52v5.04H7.2V6.48h2.16v1.68c.648-.96 1.728-1.68 3-1.68h.48c2.424 0 4.44 2.016 4.44 4.44v6.6h-.48z" })
      );
    case "twitter":
      return React.createElement("svg", { width: size, height: size, viewBox: "0 0 24 24", fill: "#ffffff" },
        React.createElement("path", { d: "M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" })
      );
    case "bluesky":
      return React.createElement("svg", { width: size, height: size, viewBox: "0 0 24 24", fill: color },
        React.createElement("path", { d: "M12 10.8c-1.087-2.114-4.046-6.053-6.798-7.995C2.566.944 1.561 1.266.902 1.565.139 1.908 0 3.08 0 3.768c0 .69.378 5.65.624 6.479.815 2.736 3.713 3.66 6.383 3.364.136-.02.275-.039.415-.056-.138.022-.276.04-.415.056-3.912.58-7.387 2.005-2.83 7.078 5.013 5.19 6.87-1.113 7.823-4.308.953 3.195 2.05 9.271 7.733 4.308 4.267-4.308 1.172-6.498-2.74-7.078a8.741 8.741 0 0 1-.415-.056c.14.017.279.036.415.056 2.67.297 5.568-.628 6.383-3.364.246-.828.624-5.79.624-6.478 0-.69-.139-1.861-.902-2.206-.659-.298-1.664-.62-4.3 1.24C16.046 4.748 13.087 8.687 12 10.8z" })
      );
    default:
      return React.createElement("svg", { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "#ffffff", strokeWidth: "2" },
        React.createElement("circle", { cx: "12", cy: "12", r: "10" }),
        React.createElement("line", { x1: "12", y1: "16", x2: "12", y2: "12" }),
        React.createElement("line", { x1: "12", y1: "8", x2: "12.01", y2: "8" })
      );
  }
}

// ---------------------------------------------------------------------------
// renderSocialReceipt — the main shared function
// ---------------------------------------------------------------------------

export interface RenderReceiptOptions {
  /** Base URL of the app, used only to build the app logo URL */
  appBaseUrl: string;
}

export interface RenderReceiptResult {
  /** "data:image/png;base64,..." */
  dataUrl: string;
  /** The cover key used for local cover storage (receipt-{platform}-{id}) */
  coverKey: string;
}

/**
 * Render a social receipt PNG and return it as a base64 data URL.
 * Call directly from server routes — no internal HTTP fetch required.
 */
export async function renderSocialReceipt(
  content: SocialContent,
  options: RenderReceiptOptions
): Promise<RenderReceiptResult> {
  // eslint-disable-next-line @typescript-eslint/no-require-imports
  const React = require("react");

  const { appBaseUrl } = options;
  const appLogoUrl = `${appBaseUrl}/app-logo.png?v=2`;

  const archivedMedia = await archiveMedia(content);

  const platformInfo = PLATFORM_INFO[content.platform] || PLATFORM_INFO.twitter;
  const platformColor = platformInfo.color;
  const platformName = platformInfo.name;
  const platformIcon = getPlatformIcon(content.platform, 24);

  const isVideoContent = content.platform === "youtube" || content.platform === "tiktok";

  const hasImages =
    archivedMedia.imageDataUrls.length > 0 || (content.images && content.images.length > 0);
  const maxTextLength = hasImages ? 200 : 500;

  const cleanedText = content.text
    .replace(/\s*https?:\/\/t\.co\/\S+\s*$/g, "")
    .replace(/\s*https?:\/\/\S+\s*$/g, "")
    .trim();

  const displayText =
    cleanedText.length > maxTextLength ? cleanedText.slice(0, maxTextLength) + "..." : cleanedText;

  const imageUrls =
    archivedMedia.imageDataUrls.length > 0
      ? archivedMedia.imageDataUrls
      : (content.images || []).slice(0, 4);
  const imageCount = imageUrls.length;

  const emojiFonts = await getEmojiFonts();

  const el = React.createElement(
    "div",
    {
      style: {
        height: "100%",
        width: "100%",
        display: "flex",
        flexDirection: "column",
        backgroundColor: "#0a0a0a",
        fontFamily: "system-ui, 'Noto Color Emoji', sans-serif",
      },
    },
    // Header
    React.createElement(
      "div",
      {
        style: {
          display: "flex",
          flexDirection: "row",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "12px 24px",
          backgroundColor: "rgba(0,255,0,0.03)",
          borderBottom: "1px solid rgba(0,255,0,0.2)",
        },
      },
      React.createElement(
        "span",
        { style: { fontSize: 11, color: "#00ff00", letterSpacing: 3, fontWeight: "bold" } },
        "ARCHIVED"
      ),
      React.createElement(
        "span",
        { style: { fontSize: 10, color: "rgba(0,255,0,0.8)" } },
        formatDate(content.timestamp)
      )
    ),
    // Main Content
    React.createElement(
      "div",
      {
        style: {
          display: "flex",
          flex: 1,
          flexDirection: "column",
          padding: "16px 24px",
          gap: 12,
        },
      },
      // Author row
      React.createElement(
        "div",
        { style: { display: "flex", alignItems: "center", gap: 12 } },
        (archivedMedia.avatarDataUrl || content.author?.avatarUrl)
          ? React.createElement("img", {
              src: archivedMedia.avatarDataUrl || content.author?.avatarUrl || "",
              alt: "",
              width: 48,
              height: 48,
              style: {
                width: 48,
                height: 48,
                borderRadius: 24,
                border: "2px solid rgba(255,255,255,0.1)",
              },
            })
          : React.createElement(
              "div",
              {
                style: {
                  width: 48,
                  height: 48,
                  borderRadius: 24,
                  backgroundColor: "#222",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                },
              },
              React.createElement(
                "svg",
                { width: 24, height: 24, viewBox: "0 0 24 24", fill: "none", stroke: "#666", strokeWidth: "2" },
                React.createElement("path", { d: "M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" }),
                React.createElement("circle", { cx: "12", cy: "7", r: "4" })
              )
            ),
        React.createElement(
          "div",
          { style: { display: "flex", flexDirection: "column", gap: 2 } },
          React.createElement(
            "div",
            { style: { display: "flex", alignItems: "center", gap: 6 } },
            React.createElement(
              "span",
              { style: { fontSize: 16, fontWeight: "bold", color: "#ffffff" } },
              (content.author?.displayName || "Unknown").slice(0, 25)
            ),
            content.author?.verified &&
              React.createElement("span", { style: { color: "#1DA1F2", fontSize: 14 } }, "✓")
          ),
          React.createElement(
            "span",
            { style: { fontSize: 13, color: "rgba(255,255,255,0.4)" } },
            `@${content.author?.username || "unknown"}`
          )
        )
      ),
      // Post text
      React.createElement(
        "div",
        {
          style: {
            display: "flex",
            padding: "14px 16px",
            backgroundColor: "rgba(255,255,255,0.03)",
            borderRadius: 8,
            borderLeft: "3px solid rgba(0,255,0,0.4)",
          },
        },
        React.createElement(
          "span",
          {
            style: {
              fontSize: 15,
              color: "#e0e0e0",
              lineHeight: 1.7,
              whiteSpace: "pre-wrap",
              wordBreak: "break-word",
              textAlign: "left",
            },
          },
          displayText
        )
      ),
      // Image grid
      imageCount > 0 &&
        React.createElement(
          "div",
          {
            style: {
              display: "flex",
              gap: 4,
              borderRadius: 12,
              overflow: "hidden",
              height: imageCount === 1 ? 200 : 160,
            },
          },
          imageCount === 1 &&
            React.createElement("img", {
              src: imageUrls[0],
              alt: "",
              width: 752,
              height: 200,
              style: { width: "100%", height: "100%", objectFit: "contain", borderRadius: 12, backgroundColor: "#0a0a0a" },
            }),
          imageCount === 2 &&
            React.createElement(
              React.Fragment,
              null,
              React.createElement("img", { src: imageUrls[0], alt: "", width: 374, height: 160, style: { width: "50%", height: "100%", objectFit: "cover" } }),
              React.createElement("img", { src: imageUrls[1], alt: "", width: 374, height: 160, style: { width: "50%", height: "100%", objectFit: "cover" } })
            ),
          imageCount === 3 &&
            React.createElement(
              React.Fragment,
              null,
              React.createElement("img", { src: imageUrls[0], alt: "", width: 374, height: 160, style: { width: "50%", height: "100%", objectFit: "cover" } }),
              React.createElement(
                "div",
                { style: { display: "flex", flexDirection: "column", width: "50%", gap: 4 } },
                React.createElement("img", { src: imageUrls[1], alt: "", width: 374, height: 78, style: { width: "100%", height: "50%", objectFit: "cover" } }),
                React.createElement("img", { src: imageUrls[2], alt: "", width: 374, height: 78, style: { width: "100%", height: "50%", objectFit: "cover" } })
              )
            ),
          imageCount >= 4 &&
            React.createElement(
              React.Fragment,
              null,
              React.createElement(
                "div",
                { style: { display: "flex", flexDirection: "column", width: "50%", gap: 4 } },
                React.createElement("img", { src: imageUrls[0], alt: "", width: 374, height: 78, style: { width: "100%", height: "50%", objectFit: "cover" } }),
                React.createElement("img", { src: imageUrls[2], alt: "", width: 374, height: 78, style: { width: "100%", height: "50%", objectFit: "cover" } })
              ),
              React.createElement(
                "div",
                { style: { display: "flex", flexDirection: "column", width: "50%", gap: 4 } },
                React.createElement("img", { src: imageUrls[1], alt: "", width: 374, height: 78, style: { width: "100%", height: "50%", objectFit: "cover" } }),
                React.createElement("img", { src: imageUrls[3], alt: "", width: 374, height: 78, style: { width: "100%", height: "50%", objectFit: "cover" } })
              )
            )
        ),
      // Video thumbnail
      isVideoContent &&
        (archivedMedia.thumbnailDataUrl || content.thumbnailUrl) &&
        React.createElement(
          "div",
          { style: { display: "flex", position: "relative", borderRadius: 12, overflow: "hidden", height: 180 } },
          React.createElement("img", {
            src: archivedMedia.thumbnailDataUrl || content.thumbnailUrl || "",
            alt: "",
            width: 752,
            height: 180,
            style: { width: "100%", height: "100%", objectFit: "cover" },
          }),
          React.createElement(
            "div",
            {
              style: {
                position: "absolute",
                top: 0, left: 0, right: 0, bottom: 0,
                display: "flex",
                alignItems: "center",
                justifyContent: "center",
                backgroundColor: "rgba(0,0,0,0.3)",
              },
            },
            React.createElement(
              "div",
              {
                style: {
                  width: 56, height: 56, borderRadius: 28,
                  backgroundColor: "rgba(255,255,255,0.95)",
                  display: "flex",
                  alignItems: "center",
                  justifyContent: "center",
                  fontSize: 22,
                  paddingLeft: 4,
                },
              },
              "▶"
            )
          ),
          content.duration &&
            React.createElement(
              "div",
              {
                style: {
                  position: "absolute", bottom: 8, right: 8,
                  padding: "4px 8px",
                  backgroundColor: "rgba(0,0,0,0.85)",
                  borderRadius: 4,
                  fontSize: 11,
                  color: "#ffffff",
                },
              },
              content.duration
            )
        ),
      // Reddit subreddit badge
      content.subreddit &&
        React.createElement(
          "div",
          {
            style: {
              display: "flex",
              padding: "6px 12px",
              backgroundColor: "rgba(255,69,0,0.1)",
              borderRadius: 6,
              border: "1px solid rgba(255,69,0,0.3)",
              width: "fit-content",
            },
          },
          React.createElement("span", { style: { fontSize: 12, color: "#FF4500" } }, `r/${content.subreddit}`)
        )
    ),
    // Footer
    React.createElement(
      "div",
      {
        style: {
          display: "flex",
          flexDirection: "row",
          alignItems: "center",
          justifyContent: "space-between",
          padding: "12px 24px",
          backgroundColor: "rgba(0,20,0,0.9)",
          borderTop: "1px solid rgba(0,255,0,0.2)",
        },
      },
      React.createElement(
        "div",
        {
          style: {
            display: "flex",
            alignItems: "center",
            gap: 8,
            padding: "6px 12px",
            backgroundColor: `${platformColor}15`,
            borderRadius: 6,
            border: `1px solid ${platformColor}30`,
          },
        },
        platformIcon,
        React.createElement(
          "span",
          {
            style: {
              fontSize: 14,
              color: platformColor === "#000000" ? "#ffffff" : platformColor,
              fontWeight: "600",
            },
          },
          platformName
        )
      ),
      React.createElement(
        "div",
        { style: { display: "flex", alignItems: "center", gap: 10 } },
        React.createElement("img", {
          src: appLogoUrl,
          alt: "",
          width: 32,
          height: 32,
          style: { width: 32, height: 32, objectFit: "contain" },
        }),
        React.createElement(
          "div",
          { style: { display: "flex", flexDirection: "column" } },
          React.createElement(
            "span",
            { style: { fontSize: 13, color: "#00ff00", fontWeight: "bold", letterSpacing: 1 } },
            "NET LIBRARY"
          ),
          React.createElement(
            "span",
            { style: { fontSize: 9, color: "rgba(0,255,0,0.5)", letterSpacing: 1 } },
            "PERMANENT ARCHIVE"
          )
        )
      )
    ),
    // URL footer
    React.createElement(
      "div",
      {
        style: {
          display: "flex",
          justifyContent: "center",
          padding: "6px 24px",
          backgroundColor: "rgba(0,255,0,0.02)",
          borderTop: "1px dashed rgba(0,255,0,0.15)",
        },
      },
      React.createElement(
        "span",
        { style: { fontSize: 9, color: "rgba(0,255,0,0.7)", letterSpacing: 1 } },
        content.url.length > 70 ? content.url.slice(0, 70) + "..." : content.url
      )
    )
  );

  const imageResponse = new ImageResponse(el, {
    width: 800,
    height: 600,
    fonts: emojiFonts,
    headers: { "Cache-Control": "no-cache, no-store, must-revalidate" },
  });

  const arrayBuffer = await imageResponse.arrayBuffer();
  const base64 = Buffer.from(arrayBuffer).toString("base64");
  const dataUrl = `data:image/png;base64,${base64}`;
  const coverKey = `receipt-${content.platform}-${content.id}`;

  return { dataUrl, coverKey };
}
src/lib/redact-secrets.ts
/**
 * Redact sensitive information from source code before exposing it publicly.
 * This prevents accidental exposure of API keys, passwords, and other secrets
 * in the code documentation viewer.
 */

// Patterns to redact with their replacements
const REDACTION_PATTERNS: Array<{ pattern: RegExp; replacement: string }> = [
  // API keys with specific formats (UUIDs, hex strings, etc.)
  {
    pattern: /(['"`])([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\1/gi,
    replacement: '$1[REDACTED-UUID]$1',
  },
  // Namestone API key pattern
  {
    pattern: /NAMESTONE_API_KEY\s*(?:=|:|\|\|)\s*(['"`])[^'"`]+\1/gi,
    replacement: 'NAMESTONE_API_KEY = "[REDACTED]"',
  },
  // Admin key fallbacks
  {
    pattern: /(['"`])netlibrary-admin-\d{4}(-\w+)?\1/gi,
    replacement: '$1[REDACTED]$1',
  },
  // Generic admin key/secret patterns with fallback values
  {
    pattern: /(ADMIN_KEY|ADMIN_SECRET)\s*\|\|\s*(['"`])[^'"`]+\2/gi,
    replacement: '$1 || "[REDACTED]"',
  },
  // API key environment variable fallbacks
  {
    pattern: /(process\.env\.\w*(?:KEY|SECRET|TOKEN|PASSWORD)\w*)\s*\|\|\s*(['"`])[^'"`]+\2/gi,
    replacement: '$1 || "[REDACTED]"',
  },
  // Bearer token examples
  {
    pattern: /Bearer\s+[A-Za-z0-9_-]{20,}/gi,
    replacement: 'Bearer [REDACTED]',
  },
  // Webhook secrets
  {
    pattern: /(WEBHOOK_SECRET|NEYNAR_WEBHOOK_SECRET)\s*(?:=|:|\|\|)\s*(['"`])[^'"`]+\2/gi,
    replacement: '$1 = "[REDACTED]"',
  },
  // Relay secrets
  {
    pattern: /(X-Relay-Secret|X-Secret-Key|secretKey)\s*(?::|=)\s*(['"`])[^'"`]+\2/gi,
    replacement: '$1: "[REDACTED]"',
  },
  // Agent API keys (nl_ prefix pattern)
  {
    pattern: /nl_[A-Za-z0-9]{8}_[A-Za-z0-9]{8}_[A-Za-z0-9]{8}_[A-Za-z0-9]{8}/g,
    replacement: '[REDACTED-API-KEY]',
  },
  // Neynar webhook secret
  {
    pattern: /(NEYNAR_WEBHOOK_SECRET)\s*\|\|\s*(['"`])[^'"`]+\2/gi,
    replacement: '$1 || "[REDACTED]"',
  },
  // Neynar API key in headers
  {
    pattern: /(["']x-api-key["']\s*:\s*)(process\.env\.NEYNAR_API_KEY\s*\|\|\s*["'][^"']+["'])/gi,
    replacement: '$1process.env.NEYNAR_API_KEY || "[REDACTED]"',
  },
  // RPC URL environment fallbacks (may contain API keys in URL)
  {
    pattern: /(BASE_RPC_URL|RPC_URL|ETHEREUM_RPC)\s*\|\|\s*(['"`])https:\/\/[^'"`]+\2/gi,
    replacement: '$1 || "[REDACTED-RPC-URL]"',
  },
];

/**
 * Redact sensitive information from source code content.
 * @param content - The source code content to redact
 * @returns The content with sensitive information replaced with [REDACTED]
 */
export function redactSecrets(content: string): string {
  let redacted = content;

  for (const { pattern, replacement } of REDACTION_PATTERNS) {
    redacted = redacted.replace(pattern, replacement);
  }

  return redacted;
}

/**
 * Check if content contains any sensitive patterns that should be redacted.
 * Useful for validation/testing.
 *
 * NOTE: All patterns carry the `g` flag for `.replace()` usage in `redactSecrets()`.
 * Calling `.test()` on a `g`-flagged RegExp mutates `.lastIndex`, causing
 * alternating true/false results when the same pattern is tested repeatedly
 * against the same string. We reset `.lastIndex` before each call to prevent
 * false negatives silently leaking secrets through the check.
 */
export function containsSensitivePatterns(content: string): boolean {
  return REDACTION_PATTERNS.some(({ pattern }) => {
    pattern.lastIndex = 0; // reset stateful lastIndex before each test (g-flag safety)
    return pattern.test(content);
  });
}
src/lib/relay-feature-flags.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Feature Flags for Net Protocol Relay + x402
 *
 * Central configuration for relay service availability.
 * When Aspyn confirms relay is production-ready, update these values.
 *
 * Environment Variables:
 * - NEXT_PUBLIC_RELAY_ENABLED: "true" to enable relay globally
 * - NEXT_PUBLIC_RELAY_API_URL: Production relay API endpoint
 * - NEXT_PUBLIC_RELAY_TREASURY_ADDRESS: Address to approve USDC spending to
 *
 * Usage:
 * ```ts
 * import { relayFlags, isRelayFeatureEnabled } from '@/lib/relay-feature-flags';
 *
 * if (isRelayFeatureEnabled('gaslessUpload')) {
 *   // Use relay upload
 * }
 * ```
 */

import type { Address } from "viem";

// =============================================================================
// FEATURE FLAGS
// =============================================================================

export interface RelayFeatureFlags {
  // Master switch - enables/disables all relay features
  enabled: boolean;

  // Individual feature flags
  features: {
    // Allow gasless single file uploads via relay
    gaslessUpload: boolean;

    // Allow gasless batch uploads via relay
    gaslessBatchUpload: boolean;

    // Show relay option in upload UI (even if disabled, for preview)
    showRelayOption: boolean;

    // Allow unlimited USDC approval (vs exact amount)
    allowUnlimitedApproval: boolean;

    // Enable detailed diagnostics logging
    diagnosticsLogging: boolean;
  };

  // Environment info
  environment: "development" | "staging" | "production";
}

// =============================================================================
// DEFAULT FLAGS (Relay disabled until live)
// =============================================================================

const _DEFAULT_FLAGS: RelayFeatureFlags = {
  enabled: false,

  features: {
    gaslessUpload: false,
    gaslessBatchUpload: false,
    showRelayOption: true, // Show option even when disabled (grayed out)
    allowUnlimitedApproval: false, // Safer to require exact amounts
    diagnosticsLogging: true,
  },

  environment: "development",
};

// =============================================================================
// CONFIGURATION FROM ENVIRONMENT
// =============================================================================

function getEnvironment(): "development" | "staging" | "production" {
  const env = process.env.NEXT_PUBLIC_ENVIRONMENT || process.env.NODE_ENV;

  if (env === "production") return "production";
  if (env === "staging") return "staging";
  return "development";
}

function getBoolEnv(key: string, defaultValue: boolean): boolean {
  const value = process.env[key];
  if (value === undefined) return defaultValue;
  return value.toLowerCase() === "true" || value === "1";
}

/**
 * Load feature flags from environment variables
 */
function loadRelayFlags(): RelayFeatureFlags {
  const environment = getEnvironment();
  const masterEnabled = getBoolEnv("NEXT_PUBLIC_RELAY_ENABLED", false);

  return {
    enabled: masterEnabled,

    features: {
      // Only enable features if master switch is on
      gaslessUpload: masterEnabled && getBoolEnv("NEXT_PUBLIC_RELAY_GASLESS_UPLOAD", true),
      gaslessBatchUpload: masterEnabled && getBoolEnv("NEXT_PUBLIC_RELAY_BATCH_UPLOAD", true),
      showRelayOption: getBoolEnv("NEXT_PUBLIC_RELAY_SHOW_OPTION", true),
      allowUnlimitedApproval: getBoolEnv("NEXT_PUBLIC_RELAY_UNLIMITED_APPROVAL", false),
      diagnosticsLogging: getBoolEnv("NEXT_PUBLIC_RELAY_DIAGNOSTICS", environment !== "production"),
    },

    environment,
  };
}

// =============================================================================
// RELAY SERVICE CONFIGURATION
// =============================================================================

export interface RelayServiceConfig {
  // API endpoint for relay service
  apiUrl: string;

  // Chain ID (Base mainnet = 8453)
  chainId: number;

  // Address that receives USDC for gas payment
  treasuryAddress: Address;

  // Session duration in seconds
  sessionDurationSec: number;

  // x402 facilitator URL
  facilitatorUrl: string;
}

/**
 * Load relay service configuration from environment
 */
function loadRelayConfig(): RelayServiceConfig {
  return {
    apiUrl: process.env.NEXT_PUBLIC_RELAY_API_URL || "https://relay.netprotocol.app",
    chainId: Number(process.env.NEXT_PUBLIC_RELAY_CHAIN_ID) || 8453,
    treasuryAddress: (process.env.NEXT_PUBLIC_RELAY_TREASURY_ADDRESS ||
      "0x0000000000000000000000000000000000000000") as Address,
    sessionDurationSec: Number(process.env.NEXT_PUBLIC_RELAY_SESSION_DURATION) || 3600,
    facilitatorUrl: process.env.NEXT_PUBLIC_X402_FACILITATOR_URL || "https://x402.org/facilitator",
  };
}

// =============================================================================
// PRICING CONFIGURATION
// =============================================================================

export interface RelayPricingConfig {
  // Base cost per transaction in USDC
  baseTxCostUsdc: number;

  // Cost per KB of calldata in USDC
  perKbCostUsdc: number;

  // Maximum cost cap per single upload in USDC
  maxUploadCostUsdc: number;

  // Minimum USDC balance required to start upload
  minBalanceUsdc: number;
}

function loadRelayPricing(): RelayPricingConfig {
  return {
    baseTxCostUsdc: Number(process.env.NEXT_PUBLIC_RELAY_TX_COST_USDC) || 0.01,
    perKbCostUsdc: Number(process.env.NEXT_PUBLIC_RELAY_KB_COST_USDC) || 0.001,
    maxUploadCostUsdc: Number(process.env.NEXT_PUBLIC_RELAY_MAX_UPLOAD_COST_USDC) || 5.0,
    minBalanceUsdc: Number(process.env.NEXT_PUBLIC_RELAY_MIN_BALANCE_USDC) || 0.1,
  };
}

// =============================================================================
// EXPORTS
// =============================================================================

// Loaded configuration (cached)
export const relayFlags: RelayFeatureFlags = loadRelayFlags();
export const relayConfig: RelayServiceConfig = loadRelayConfig();
export const relayPricing: RelayPricingConfig = loadRelayPricing();

/**
 * Check if a specific relay feature is enabled
 */
export function isRelayFeatureEnabled(
  feature: keyof RelayFeatureFlags["features"]
): boolean {
  return relayFlags.enabled && relayFlags.features[feature];
}

/**
 * Check if relay is available (master switch)
 */
export function isRelayAvailable(): boolean {
  return relayFlags.enabled;
}

/**
 * Get relay configuration for the current environment
 */
export function getRelayConfig(): {
  flags: RelayFeatureFlags;
  service: RelayServiceConfig;
  pricing: RelayPricingConfig;
} {
  return {
    flags: relayFlags,
    service: relayConfig,
    pricing: relayPricing,
  };
}

/**
 * Log relay configuration (for debugging)
 */
export function logRelayConfig(): void {
  if (!relayFlags.features.diagnosticsLogging) return;

  console.log("[RELAY CONFIG]", {
    enabled: relayFlags.enabled,
    environment: relayFlags.environment,
    features: relayFlags.features,
    apiUrl: relayConfig.apiUrl,
    treasuryAddress: relayConfig.treasuryAddress.slice(0, 10) + "...",
    pricing: relayPricing,
  });
}

// =============================================================================
// ACTIVATION CHECKLIST (For when Aspyn says it's ready)
// =============================================================================

/**
 * WHEN RELAY GOES LIVE:
 *
 * 1. Get production values from Aspyn:
 *    - NEXT_PUBLIC_RELAY_API_URL (relay API endpoint)
 *    - NEXT_PUBLIC_RELAY_TREASURY_ADDRESS (where USDC goes)
 *
 * 2. Add to .env:
 *    NEXT_PUBLIC_RELAY_ENABLED=true
 *    NEXT_PUBLIC_RELAY_API_URL=https://relay.netprotocol.app
 *    NEXT_PUBLIC_RELAY_TREASURY_ADDRESS=0x...
 *
 * 3. Test on staging first:
 *    NEXT_PUBLIC_ENVIRONMENT=staging
 *
 * 4. Verify:
 *    - USDC approval flow works
 *    - Session creation succeeds
 *    - Transaction submission works
 *    - Files appear on CDN
 *
 * 5. Ship to production!
 */
src/lib/relay-upload-utils.ts
"use client";

/**
 * Shared Relay Upload Utilities
 *
 * Critical logic shared between single-file and batch upload hooks.
 * Single source of truth for:
 * - Smart Wallet detection
 * - Simulation failure detection
 * - Session management
 * - Upload guards
 */

import { createPublicClient, http, type Address } from "viem";
import { base } from "viem/chains";

// =============================================================================
// BASE PUBLIC CLIENT (shared for all relay operations)
// =============================================================================

/**
 * Dedicated Base public client for relay operations
 * Used for Smart Wallet detection and other chain checks
 */
export const basePublicClient = createPublicClient({
  chain: base,
  transport: http("https://mainnet.base.org"),
});

// =============================================================================
// SMART WALLET DETECTION
// =============================================================================

/**
 * Check if a Smart Wallet contract is deployed at the given address.
 *
 * Coinbase Smart Wallets (ERC-4337 Account Abstraction) may not be deployed
 * until their first transaction. This affects gas estimation because:
 * 1. First tx includes deployment cost (CREATE2 + initialization)
 * 2. Bundler simulation may fail with misleading "insufficient funds" error
 *
 * @returns true if contract code exists, false if EOA or undeployed Smart Wallet
 */
export async function isSmartWalletDeployed(address: Address): Promise<boolean> {
  try {
    const code = await basePublicClient.getCode({ address });
    // If code exists and is more than "0x", the contract is deployed
    return code !== undefined && code !== "0x" && code.length > 2;
  } catch (error) {
    console.warn("[relay-utils] Failed to check Smart Wallet deployment:", error);
    return true; // Assume deployed on error to avoid false negatives
  }
}

// =============================================================================
// SIMULATION FAILURE DETECTION
// =============================================================================

/**
 * Detect if an error is a Smart Wallet simulation failure (not actual insufficient funds)
 *
 * These errors look like "insufficient funds" but are actually simulation failures:
 * - "Error generating transaction" - Coinbase Wallet popup message
 * - "simulation failed" - Bundler response
 * - "AA21" or "AA25" - Account Abstraction error codes
 * - "execution reverted" - Generic simulation failure
 */
export function isSimulationFailure(errorMsg: string): boolean {
  const lowerMsg = errorMsg.toLowerCase();
  return (
    lowerMsg.includes("error generating transaction") ||
    lowerMsg.includes("simulation failed") ||
    lowerMsg.includes("execution reverted") ||
    lowerMsg.includes("aa21") || // First tx with undeployed account
    lowerMsg.includes("aa25") || // Invalid account signature
    lowerMsg.includes("useroperation") ||
    // The false positive - this often masks simulation failures
    (lowerMsg.includes("make sure you have enough funds") && lowerMsg.includes("error"))
  );
}

// =============================================================================
// USER REJECTION DETECTION
// =============================================================================

/**
 * Detect if an error is a user rejection (user cancelled the wallet prompt)
 */
export function isUserRejection(errorMsg: string): boolean {
  const lowerMsg = errorMsg.toLowerCase();
  return (
    lowerMsg.includes("user rejected") ||
    lowerMsg.includes("user denied") ||
    lowerMsg.includes("user refused") ||
    lowerMsg.includes("user dismissed") ||
    lowerMsg.includes("rejected by user") ||
    lowerMsg.includes("cancelled by user") ||
    lowerMsg.includes("user cancelled") ||
    lowerMsg.includes("user canceled")
  );
}

// =============================================================================
// ERC20 UTILS
// =============================================================================

/**
 * Minimal ERC20 ABI for USDC operations
 */
export const ERC20_ABI = [
  {
    name: "transfer",
    type: "function",
    inputs: [
      { name: "to", type: "address" },
      { name: "value", type: "uint256" },
    ],
    outputs: [{ name: "", type: "bool" }],
  },
  {
    name: "balanceOf",
    type: "function",
    inputs: [{ name: "account", type: "address" }],
    outputs: [{ name: "", type: "uint256" }],
  },
] as const;

export const USDC_DECIMALS = 6;
export const USDC_ADDRESS = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" as Address;

/**
 * Check user's USDC balance on Base chain
 */
export async function checkUserUsdcBalance(address: Address): Promise<number> {
  try {
    const balance = await basePublicClient.readContract({
      address: USDC_ADDRESS,
      abi: ERC20_ABI,
      functionName: "balanceOf",
      args: [address],
    });
    return Number(balance) / 10 ** USDC_DECIMALS;
  } catch (error) {
    console.error("[relay-utils] Failed to check USDC balance:", error);
    return 0;
  }
}

// =============================================================================
// RELAY CONFIG (shared constants)
// =============================================================================

export const RELAY_CONFIG = {
  apiUrl: "https://www.netprotocol.app",
  chainId: 8453 as const, // Base mainnet
  secretKey: "[REDACTED]",
  usdcAddress: USDC_ADDRESS,
  // x402 facilitator address (receives USDC payments, converts to ETH for relay wallet)
  x402FacilitatorAddress: "0x6462F8f301Bd08c206ee611aA00015bA41acc1D0" as Address,
  // Verify retry settings
  verifyMaxRetries: 5,
  verifyRetryDelayMs: 2000,
} as const;

// =============================================================================
// UPLOAD ERROR ANALYSIS
// =============================================================================

/**
 * Analyze an upload error and categorize it
 */
export function analyzeUploadError(error: unknown): {
  message: string;
  isUserRejection: boolean;
  isSimulationFailure: boolean;
  isInsufficientFunds: boolean;
  isRecoverable: boolean;
} {
  const message = error instanceof Error ? error.message : String(error);
  const lowerMsg = message.toLowerCase();

  const userRejection = isUserRejection(message);
  const simulationFail = isSimulationFailure(message);

  // True insufficient funds (not simulation failure)
  const insufficientFunds =
    (lowerMsg.includes("insufficient") || lowerMsg.includes("not enough")) &&
    !simulationFail;

  // Recoverable = can retry (not user rejection, not permanent failure)
  const recoverable = !userRejection && (simulationFail || insufficientFunds);

  return {
    message,
    isUserRejection: userRejection,
    isSimulationFailure: simulationFail,
    isInsufficientFunds: insufficientFunds,
    isRecoverable: recoverable,
  };
}
src/lib/relay-upload.ts
/* eslint-disable @neynar/no-process-env */
/**
 * Shared relay upload helper for server-side file uploads to Net Protocol.
 *
 * Used by both /api/v1/library/upload (agent file uploads) and
 * /api/v1/archive (social receipt archiving) to avoid duplicating the
 * two-step relay flow (balance → submit).
 *
 * Flow:
 *   1. Balance call  → resolve backendWalletAddress for CDN URL generation
 *   2. Submit call   → relay encodes + broadcasts the Storage.put() transaction(s)
 *   3. Return        → { cdnUrl, operatorAddress, txHashes, storageKey, storageType }
 */

import { stringToHex } from "viem";
import {
  STORAGE_CONTRACT_ADDRESS,
  CHUNKED_STORAGE_ADDRESS,
  STORAGE_ABI,
  CHUNKED_STORAGE_ABI,
  BASE_CHAIN_ID,
  getCdnUrl,
  generateStorageKey,
} from "@/lib/net-protocol";
import { chunkDataForStorage } from "@net-protocol/storage";

// ---------------------------------------------------------------------------
// Relay constants (server-to-server, same values as upload route)
// ---------------------------------------------------------------------------

export const RELAY_API_URL = "https://www.netprotocol.app";
export const RELAY_SECRET_KEY = "net-relay-public-access-key-v1";
const RELAY_BACKEND_WALLET_FALLBACK = process.env.RELAY_BACKEND_WALLET || "";

// ---------------------------------------------------------------------------
// Size thresholds (must match upload route)
// ---------------------------------------------------------------------------

export const CHUNK_THRESHOLD = 20_000;   // <20KB  → regular Storage.put()
export const CHUNKED_THRESHOLD = 80_000; // <80KB  → ChunkedStorage.put()
                                          // ≥80KB  → xml (multi-chunk)

export type StorageType = "regular" | "chunked" | "xml";

function getStorageType(fileSize: number): StorageType {
  if (fileSize < CHUNK_THRESHOLD) return "regular";
  if (fileSize < CHUNKED_THRESHOLD) return "chunked";
  return "xml";
}

// ---------------------------------------------------------------------------
// RelayTransaction shape the relay API expects
// ---------------------------------------------------------------------------

interface RelayTransaction {
  to: string;
  abi: readonly unknown[];
  functionName: string;
  args: unknown[];
}

// ---------------------------------------------------------------------------
// uploadBufferToRelay
//
// Uploads a Buffer (any binary content) to Net Protocol via the relay.
// operatorAddress is the wallet identity for this upload (agent address or
// member wallet address).
//
// Returns null on relay failure — callers should decide whether to abort or
// fall through to a degraded response.
// ---------------------------------------------------------------------------

export interface RelayUploadResult {
  cdnUrl: string;
  operatorAddress: string; // backendWalletAddress resolved from relay
  storageKey: `0x${string}`;
  storageType: StorageType;
  fileName: string;
  txHashes: string[];
}

export async function uploadBufferToRelay(
  buffer: Buffer,
  fileName: string,
  operatorAddress: string, // caller's wallet — used as submit operatorAddress + CDN fallback
  storageKeyOverride?: `0x${string}` // optional: pre-generated key for dedup
): Promise<RelayUploadResult | null> {
  const fileSize = buffer.length;
  const storageType = getStorageType(fileSize);
  const timestamp = Date.now();

  const storageKey: `0x${string}` =
    storageKeyOverride ?? generateStorageKey(`netlib-${fileName}-${timestamp}`);

  const dataAsBase64 = buffer.toString("base64");
  const dataHex = stringToHex(dataAsBase64);

  // Build transaction(s)
  const transactions: RelayTransaction[] = [];

  if (storageType === "regular") {
    transactions.push({
      to: STORAGE_CONTRACT_ADDRESS,
      abi: STORAGE_ABI,
      functionName: "put",
      args: [storageKey, fileName, dataHex],
    });
  } else if (storageType === "chunked") {
    const chunks = chunkDataForStorage(dataAsBase64);
    transactions.push({
      to: CHUNKED_STORAGE_ADDRESS,
      abi: CHUNKED_STORAGE_ABI,
      functionName: "put",
      args: [storageKey, fileName, chunks],
    });
  } else {
    // xml: split into 80KB chunks
    const XML_CHUNK_SIZE = 80_000;
    const xmlChunks: Array<{ key: `0x${string}`; compressedChunks: string[] }> = [];

    for (let i = 0; i < dataAsBase64.length; i += XML_CHUNK_SIZE) {
      const chunkString = dataAsBase64.slice(i, i + XML_CHUNK_SIZE);
      const compressedChunks = chunkDataForStorage(chunkString);
      const chunkKey = generateStorageKey(`netlib-chunk-${fileName}-${timestamp}-${i}`);
      xmlChunks.push({ key: chunkKey, compressedChunks });
      transactions.push({
        to: CHUNKED_STORAGE_ADDRESS,
        abi: CHUNKED_STORAGE_ABI,
        functionName: "put",
        args: [chunkKey, "", compressedChunks],
      });
    }

    const xmlMetadata = JSON.stringify({
      type: "xml",
      chunks: xmlChunks.map((c) => c.key),
      fileName,
      fileSize,
    });

    transactions.push({
      to: STORAGE_CONTRACT_ADDRESS,
      abi: STORAGE_ABI,
      functionName: "put",
      args: [storageKey, fileName, stringToHex(xmlMetadata)],
    });
  }

  // Step 1: Balance call → resolve backendWalletAddress
  let backendWalletAddress: string | null = null;
  try {
    const balanceResp = await fetch(`${RELAY_API_URL}/api/relay/balance`, {
      method: "POST",
      headers: { "Content-Type": "application/json", "X-Relay-Secret": RELAY_SECRET_KEY },
      body: JSON.stringify({
        operatorAddress,
        chainId: BASE_CHAIN_ID,
        secretKey: RELAY_SECRET_KEY,
      }),
    });
    if (balanceResp.ok) {
      const balanceJson = await balanceResp.json() as { backendWalletAddress?: string };
      backendWalletAddress = balanceJson.backendWalletAddress ?? null;
    } else {
      console.error(`[relay-upload] Balance call failed (${balanceResp.status})`);
    }
  } catch (err) {
    console.error("[relay-upload] Balance call network error:", err);
  }

  // Step 2: Submit transactions
  let submitResult: Record<string, unknown>;
  try {
    const submitResp = await fetch(`${RELAY_API_URL}/api/relay/submit`, {
      method: "POST",
      headers: { "Content-Type": "application/json", "X-Relay-Secret": RELAY_SECRET_KEY },
      body: JSON.stringify({
        transactions,
        operatorAddress,
        sessionToken: RELAY_SECRET_KEY,
        secretKey: RELAY_SECRET_KEY,
        chainId: BASE_CHAIN_ID,
      }),
    });

    const rawBody = await submitResp.text();
    if (!submitResp.ok) {
      console.error(`[relay-upload] Submit failed (${submitResp.status}): ${rawBody.slice(0, 300)}`);
      return null;
    }

    submitResult = JSON.parse(rawBody) as Record<string, unknown>;
  } catch (err) {
    console.error("[relay-upload] Submit network error:", err);
    return null;
  }

  // Collect tx hashes
  const txHashes: string[] = [];
  if (Array.isArray(submitResult.transactionHashes)) {
    txHashes.push(...(submitResult.transactionHashes as string[]));
  } else if (typeof submitResult.transactionHash === "string") {
    txHashes.push(submitResult.transactionHash);
  }

  // Resolve final operator address for CDN URL
  // Priority: submit response → balance call → env var → caller's address (fallback)
  const resolvedOperator =
    (submitResult.backendWalletAddress as string | undefined) ||
    backendWalletAddress ||
    RELAY_BACKEND_WALLET_FALLBACK ||
    operatorAddress;

  const cdnUrl = getCdnUrl(BASE_CHAIN_ID, resolvedOperator, storageKey, storageType, fileName);

  return { cdnUrl, operatorAddress: resolvedOperator, storageKey, storageType, fileName, txHashes };
}
src/lib/siwe.ts
/**
 * Sign In With Ethereum (SIWE) utilities
 *
 * Creates and parses SIWE messages for cryptographic wallet verification.
 * Based on EIP-4361: https://eips.ethereum.org/EIPS/eip-4361
 */

export interface SiweMessageParams {
  domain: string;
  address: string;
  statement: string;
  uri: string;
  version: string;
  chainId: number;
  nonce: string;
  issuedAt: string;
  expirationTime?: string;
}

/**
 * Creates a SIWE message string following EIP-4361 format
 */
export function createSiweMessage(params: SiweMessageParams): string {
  const {
    domain,
    address,
    statement,
    uri,
    version,
    chainId,
    nonce,
    issuedAt,
    expirationTime,
  } = params;

  let message = `${domain} wants you to sign in with your Ethereum account:\n`;
  message += `${address}\n\n`;
  message += `${statement}\n\n`;
  message += `URI: ${uri}\n`;
  message += `Version: ${version}\n`;
  message += `Chain ID: ${chainId}\n`;
  message += `Nonce: ${nonce}\n`;
  message += `Issued At: ${issuedAt}`;

  if (expirationTime) {
    message += `\nExpiration Time: ${expirationTime}`;
  }

  return message;
}

/**
 * Parses a SIWE message string back into its components
 */
export function parseSiweMessage(message: string): Partial<SiweMessageParams> {
  const lines = message.split('\n');
  const result: Partial<SiweMessageParams> = {};

  // First line: "{domain} wants you to sign in with your Ethereum account:"
  const domainMatch = lines[0]?.match(/^(.+) wants you to sign in with your Ethereum account:$/);
  if (domainMatch) {
    result.domain = domainMatch[1];
  }

  // Second line: address
  if (lines[1]) {
    result.address = lines[1].trim();
  }

  // Parse the rest of the fields
  for (const line of lines) {
    if (line.startsWith('URI: ')) {
      result.uri = line.substring(5);
    } else if (line.startsWith('Version: ')) {
      result.version = line.substring(9);
    } else if (line.startsWith('Chain ID: ')) {
      result.chainId = parseInt(line.substring(10), 10);
    } else if (line.startsWith('Nonce: ')) {
      result.nonce = line.substring(7);
    } else if (line.startsWith('Issued At: ')) {
      result.issuedAt = line.substring(11);
    } else if (line.startsWith('Expiration Time: ')) {
      result.expirationTime = line.substring(17);
    }
  }

  // Extract statement (between address and URI)
  const uriIndex = lines.findIndex(l => l.startsWith('URI: '));
  if (uriIndex > 3) {
    // Statement is between line 3 (after blank line) and uriIndex - 1 (before blank line)
    const statementLines = lines.slice(3, uriIndex - 1).filter(l => l.trim());
    result.statement = statementLines.join('\n');
  }

  return result;
}

/**
 * Generates a random nonce for SIWE messages
 */
export function generateNonce(): string {
  const array = new Uint8Array(16);
  crypto.getRandomValues(array);
  return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
}

/**
 * Creates a SIWE message for Net Library wallet linking
 */
export function createLinkWalletMessage(
  address: string,
  fid: number,
  nonce: string
): string {
  const now = new Date();
  const expiration = new Date(now.getTime() + 10 * 60 * 1000); // 10 minutes

  return createSiweMessage({
    domain: typeof window !== 'undefined' ? window.location.host : 'net-library.app',
    address,
    statement: `Link this wallet to Farcaster account (FID: ${fid}) on Net Library. This signature proves you own this wallet.`,
    uri: typeof window !== 'undefined' ? window.location.origin : 'https://net-library.app',
    version: '1',
    chainId: 8453, // Base mainnet
    nonce,
    issuedAt: now.toISOString(),
    expirationTime: expiration.toISOString(),
  });
}
src/lib/ua-utils.ts
/**
 * User-Agent detection utilities.
 *
 * Single source of truth for Coinbase Wallet UA detection — previously
 * duplicated across app-mode.ts, net-relay.ts, and diagnostics.ts.
 * Centralising here ensures all files stay in sync.
 */

/**
 * Returns true if the current user-agent belongs to the Coinbase Wallet
 * in-app browser.
 *
 * Uses specific identifiers to avoid false positives on strings like
 * "database", "Firebase", or "Chromium-based" that incidentally contain
 * "base" or "coinbase".
 */
export function isCoinbaseWalletUA(ua: string): boolean {
  const lower = ua.toLowerCase();
  return (
    lower.includes("coinbasewallet") ||
    lower.includes("coinbase/") ||
    lower.includes("coinbase wallet")
  );
}
src/lib/upload-queue.ts
/**
 * Upload Queue System
 * Manages multiple files for sequential upload
 */

export interface QueuedUpload {
  id: string;
  file: File;
  title: string;
  author: string;
  categories: string[];
  coverUrl?: string;
  publicationYear?: string;
  publisher?: string;
  isbn?: string;
  description?: string;
  stackIds?: string[]; // Stacks to add this file to after upload
  status: "pending" | "uploading" | "complete" | "error";
  progress: number; // 0-100
  error?: string;
  cdnUrl?: string;
  addedAt: number;
  originalEpubName?: string; // Track if converted from EPUB
  fromDraft?: boolean; // Track if metadata was restored from a previous failed upload
}

export interface UploadQueueState {
  items: QueuedUpload[];
  currentIndex: number;
  isProcessing: boolean;
}

const UPLOAD_QUEUE_KEY = "net-library-upload-queue";
const FAILED_DRAFTS_KEY = "net-library-failed-drafts";

/**
 * Saved draft metadata for failed uploads (keyed by filename)
 */
export interface UploadDraft {
  fileName: string;
  fileSize: number;
  title: string;
  author: string;
  categories: string[];
  coverUrl?: string;
  publicationYear?: string;
  publisher?: string;
  isbn?: string;
  description?: string;
  stackIds?: string[];
  savedAt: number;
}

/**
 * Save failed uploads as drafts for later recovery
 */
export function saveFailedDrafts(queue: QueuedUpload[]): void {
  try {
    // Only save items that failed or are pending (not complete)
    const failedItems = queue.filter(item =>
      item.status === "error" || item.status === "pending"
    );

    if (failedItems.length === 0) {
      // Clear drafts if no failures
      localStorage.removeItem(FAILED_DRAFTS_KEY);
      return;
    }

    // Get existing drafts and merge with new ones
    const existingDrafts = getFailedDrafts();
    const newDrafts: Record<string, UploadDraft> = { ...existingDrafts };

    for (const item of failedItems) {
      if (!item.file?.name) continue;

      const key = `${item.file.name}-${item.file.size}`;
      newDrafts[key] = {
        fileName: item.file.name,
        fileSize: item.file.size,
        title: item.title,
        author: item.author,
        categories: item.categories,
        coverUrl: item.coverUrl,
        publicationYear: item.publicationYear,
        publisher: item.publisher,
        isbn: item.isbn,
        description: item.description,
        stackIds: item.stackIds,
        savedAt: Date.now(),
      };
    }

    localStorage.setItem(FAILED_DRAFTS_KEY, JSON.stringify(newDrafts));
    console.log(`[upload-queue] Saved ${failedItems.length} draft(s) for recovery`);
  } catch (e) {
    console.error("[upload-queue] Failed to save drafts:", e);
  }
}

/**
 * Get saved draft metadata for failed uploads
 */
export function getFailedDrafts(): Record<string, UploadDraft> {
  try {
    const saved = localStorage.getItem(FAILED_DRAFTS_KEY);
    if (!saved) return {};

    const drafts = JSON.parse(saved) as Record<string, UploadDraft>;

    // Clean up drafts older than 7 days
    const oneWeekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000;
    const cleaned: Record<string, UploadDraft> = {};

    for (const [key, draft] of Object.entries(drafts)) {
      if (draft.savedAt > oneWeekAgo) {
        cleaned[key] = draft;
      }
    }

    // Save cleaned version if different
    if (Object.keys(cleaned).length !== Object.keys(drafts).length) {
      localStorage.setItem(FAILED_DRAFTS_KEY, JSON.stringify(cleaned));
    }

    return cleaned;
  } catch (e) {
    console.error("[upload-queue] Failed to get drafts:", e);
    return {};
  }
}

/**
 * Find a saved draft for a file (by name and size)
 */
export function findDraftForFile(file: File): UploadDraft | null {
  const drafts = getFailedDrafts();
  const key = `${file.name}-${file.size}`;
  return drafts[key] || null;
}

/**
 * Clear a specific draft after successful upload
 */
export function clearDraftForFile(file: File): void {
  try {
    const drafts = getFailedDrafts();
    const key = `${file.name}-${file.size}`;
    if (drafts[key]) {
      delete drafts[key];
      localStorage.setItem(FAILED_DRAFTS_KEY, JSON.stringify(drafts));
    }
  } catch (e) {
    console.error("[upload-queue] Failed to clear draft:", e);
  }
}

/**
 * Clear all saved drafts
 */
export function clearAllDrafts(): void {
  try {
    localStorage.removeItem(FAILED_DRAFTS_KEY);
  } catch (e) {
    console.error("[upload-queue] Failed to clear drafts:", e);
  }
}

/**
 * Create a new queued upload item
 */
export function createQueuedUpload(
  file: File,
  metadata?: { title?: string; author?: string; categories?: string[] }
): QueuedUpload {
  // Auto-fill title from filename
  const nameWithoutExt = file.name.replace(/\.[^/.]+$/, "").replace(/[-_]/g, " ");

  return {
    id: `upload-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
    file,
    title: metadata?.title || nameWithoutExt,
    author: metadata?.author || "",
    categories: metadata?.categories || [],
    status: "pending",
    progress: 0,
    addedAt: Date.now(),
  };
}

/**
 * Save queue state to localStorage (without file data)
 * Note: Files cannot be serialized, so we only save metadata
 */
export function saveQueueState(queue: QueuedUpload[]): void {
  try {
    // Save only metadata (not File objects)
    const serializable = queue.map(item => ({
      id: item.id,
      title: item.title,
      author: item.author,
      categories: item.categories,
      coverUrl: item.coverUrl,
      publicationYear: item.publicationYear,
      publisher: item.publisher,
      isbn: item.isbn,
      description: item.description,
      stackIds: item.stackIds,
      status: item.status,
      progress: item.progress,
      error: item.error,
      cdnUrl: item.cdnUrl,
      addedAt: item.addedAt,
      fileName: item.file?.name,
      fileSize: item.file?.size,
    }));
    localStorage.setItem(UPLOAD_QUEUE_KEY, JSON.stringify(serializable));
  } catch (e) {
    console.error("[upload-queue] Failed to save state:", e);
  }
}

/**
 * Get saved queue metadata (files must be re-added)
 */
export function getSavedQueueMetadata(): Partial<QueuedUpload>[] {
  try {
    const saved = localStorage.getItem(UPLOAD_QUEUE_KEY);
    if (!saved) return [];
    return JSON.parse(saved);
  } catch (e) {
    console.error("[upload-queue] Failed to get state:", e);
    return [];
  }
}

/**
 * Clear queue state
 */
export function clearQueueState(): void {
  try {
    localStorage.removeItem(UPLOAD_QUEUE_KEY);
  } catch (e) {
    console.error("[upload-queue] Failed to clear state:", e);
  }
}

/**
 * Format queue summary for display
 */
export function getQueueSummary(queue: QueuedUpload[]): {
  total: number;
  pending: number;
  uploading: number;
  complete: number;
  failed: number;
  totalSize: number;
  formattedSize: string;
} {
  const total = queue.length;
  const pending = queue.filter(q => q.status === "pending").length;
  const uploading = queue.filter(q => q.status === "uploading").length;
  const complete = queue.filter(q => q.status === "complete").length;
  const failed = queue.filter(q => q.status === "error").length;
  const totalSize = queue.reduce((sum, q) => sum + (q.file?.size || 0), 0);

  const formattedSize = totalSize < 1024 * 1024
    ? `${(totalSize / 1024).toFixed(1)} KB`
    : `${(totalSize / (1024 * 1024)).toFixed(1)} MB`;

  return { total, pending, uploading, complete, failed, totalSize, formattedSize };
}

/**
 * Estimate total transactions needed for all files in queue
 * Flow: File → Base64 (×1.33) → 80KB XML chunks → compressed → 20KB sub-chunks
 */
export function estimateTotalTransactions(queue: QueuedUpload[]): number {
  return queue.reduce((sum, item) => {
    if (!item.file) return sum;
    const fileSize = item.file.size;

    if (fileSize < 20000) {
      return sum + 1; // Regular storage
    } else if (fileSize < 80000) {
      return sum + 1; // Chunked storage
    } else {
      // XML storage: base64 → 80KB chunks → compressed → ~4 sub-chunks each
      const base64Size = fileSize * 1.33;
      const xmlChunkCount = Math.ceil(base64Size / 80000);
      const subChunksPerXmlChunk = 4; // Conservative estimate for PDFs
      return sum + (xmlChunkCount * subChunksPerXmlChunk) + 1; // +1 for metadata
    }
  }, 0);
}
src/lib/upload-rate-limit.ts
/**
 * Server-Side Upload Rate Limiting
 *
 * Enforces daily upload limits at the API level for all upload routes
 * (/api/v1/library/upload, /api/register-cdn-link, /api/v1/library/write).
 *
 * This prevents CLI/API users from bypassing client-side warm-up enforcement.
 * Uses the same KV store and limit constants as /api/upload-check.
 */

import { getKV, setKV } from "@/lib/agent-auth";
import {
  APP_CREATOR_FIDS,
  WARMUP_PERIOD_DAYS,
  WARMUP_DAILY_LIMIT,
  REGULAR_DAILY_LIMIT,
  UPLOAD_PASS_DAILY_LIMIT,
} from "@/lib/net-protocol";

// KV keys (must match /api/upload-check/route.ts)
const UPLOAD_STATS_KEY = "upload-stats-index";
const UPLOAD_PASSES_KEY = "upload-passes-index";
const MEMBERS_KEY = "member-registry";

interface DailyStats {
  totalUploads: number;
  totalBytesUploaded: number;
  firstUploadAt: number;
  lastUploadAt: number;
  dailyUploads: { [date: string]: number };
}

interface UploadStatsIndex {
  users: { [address: string]: DailyStats };
  lastUpdated: number;
}

interface UploadPassesIndex {
  passes: { [address: string]: { purchasedAt: number; txHash?: string } };
  lastUpdated: number;
}

interface MemberEntry {
  memberId: number;
  address: string;
  joinedAt: number;
  fid?: number;
  linkedAddresses?: string[];
  hasStackPass?: boolean;
}

interface MemberRegistry {
  members: MemberEntry[];
  nextMemberId: number;
  lastUpdated: number;
}

/**
 * Get today's UTC date string (YYYY-MM-DD).
 * Always uses UTC to ensure consistent day boundaries across timezones.
 */
function getTodayUtc(): string {
  return new Date().toISOString().slice(0, 10);
}

/**
 * Check and enforce the daily upload rate limit for an authenticated API caller.
 *
 * @param address - The uploader's wallet address (required)
 * @param fid     - The uploader's Farcaster ID (optional, used for team bypass)
 * @returns `{ allowed: true }` if the upload is permitted,
 *          `{ allowed: false, error: string, status: number }` if it should be rejected.
 *
 * Call this BEFORE executing the upload. Call `recordServerUpload` AFTER success.
 *
 * KNOWN LIMITATION — TOCTOU (time-of-check / time-of-use) race:
 * `checkServerUploadLimit` reads the current counter and `recordServerUpload`
 * increments it in a separate KV write. Parallel requests from the same address
 * can all pass the check before any of them has written its increment, allowing a
 * small burst above the declared daily limit. The practical consequence is a few
 * extra uploads per day — acceptable given the low-sensitivity limit values.
 * A true fix would require an atomic check-and-increment KV operation or a
 * distributed lock, neither of which is available on all KV backends used here.
 */
export async function checkServerUploadLimit(
  address: string,
  fid?: number
): Promise<{ allowed: true } | { allowed: false; error: string; status: 429 }> {
  // Team members bypass all limits
  if (fid && APP_CREATOR_FIDS.has(fid)) {
    return { allowed: true };
  }

  const normalizedAddress = address.toLowerCase();
  const today = getTodayUtc();

  // Load required data in parallel
  const [uploadStats, uploadPasses, rawRegistry] = await Promise.all([
    getKV<UploadStatsIndex>(UPLOAD_STATS_KEY),
    getKV<UploadPassesIndex>(UPLOAD_PASSES_KEY),
    getKV<MemberRegistry | MemberEntry[]>(MEMBERS_KEY),
  ]);

  const stats = uploadStats ?? { users: {}, lastUpdated: 0 };
  const passes = uploadPasses ?? { passes: {}, lastUpdated: 0 };

  // Normalise registry format (old = array, new = registry object)
  const members: MemberEntry[] = Array.isArray(rawRegistry)
    ? (rawRegistry as MemberEntry[])
    : ((rawRegistry as MemberRegistry | null)?.members ?? []);

  // Collect all addresses that belong to this user (cross-platform identity)
  const allAddresses = new Set<string>([normalizedAddress]);
  for (const m of members) {
    if (!m.address) continue;
    const mAddr = m.address.toLowerCase();
    const isMatch =
      mAddr === normalizedAddress ||
      m.linkedAddresses?.some((l) => l && l.toLowerCase() === normalizedAddress) ||
      (fid && m.fid === fid);

    if (isMatch) {
      allAddresses.add(mAddr);
      m.linkedAddresses?.forEach((l) => l && allAddresses.add(l.toLowerCase()));
    }
  }

  // Aggregate today's upload count across all user addresses
  let uploadsToday = 0;
  for (const addr of allAddresses) {
    uploadsToday += stats.users[addr]?.dailyUploads?.[today] ?? 0;
  }

  // Determine if this user has an Upload Pass or Stack Pass
  let hasUploadPass = false;
  for (const addr of allAddresses) {
    if (passes.passes[addr]) {
      hasUploadPass = true;
      break;
    }
  }
  if (!hasUploadPass) {
    for (const m of members) {
      const isMatch =
        allAddresses.has(m.address?.toLowerCase()) ||
        (fid && m.fid === fid);
      if (isMatch && m.hasStackPass) {
        hasUploadPass = true;
        break;
      }
    }
  }

  // Determine member join date (earliest across all linked accounts)
  let earliestJoin: number | null = null;
  for (const m of members) {
    const isMatch =
      allAddresses.has(m.address?.toLowerCase()) ||
      (fid && m.fid === fid);
    if (isMatch && m.joinedAt && m.joinedAt > 0) {
      if (earliestJoin === null || m.joinedAt < earliestJoin) {
        earliestJoin = m.joinedAt;
      }
    }
  }

  // Use fid-based team bypass at the stats level as well
  const memberJoinedAt = earliestJoin ?? Date.now();
  let daysSinceMembership = Math.floor((Date.now() - memberJoinedAt) / 86_400_000);
  if (fid && APP_CREATOR_FIDS.has(fid)) {
    daysSinceMembership = WARMUP_PERIOD_DAYS + 1; // force out of warm-up
  }

  const isInWarmup = daysSinceMembership < WARMUP_PERIOD_DAYS;

  // Daily limit: warm-up period respects Upload Pass; after warm-up always 100/day
  const dailyLimit = isInWarmup
    ? (hasUploadPass ? UPLOAD_PASS_DAILY_LIMIT : WARMUP_DAILY_LIMIT)
    : REGULAR_DAILY_LIMIT;

  if (uploadsToday >= dailyLimit) {
    const warmupMsg = isInWarmup && !hasUploadPass
      ? " New members have a 7-day warm-up period (10/day). Purchase an Upload Pass to bypass."
      : "";
    return {
      allowed: false,
      error: `Daily upload limit reached (${dailyLimit}/day). Try again tomorrow.${warmupMsg}`,
      status: 429,
    };
  }

  return { allowed: true };
}

/**
 * Increment the server-side upload counter for `address` after a successful upload.
 * Fire-and-forget safe — errors are logged but not thrown.
 */
export async function recordServerUpload(
  address: string,
  fileSizeBytes: number
): Promise<void> {
  try {
    const normalizedAddress = address.toLowerCase();
    const today = getTodayUtc();

    const existing = await getKV<UploadStatsIndex>(UPLOAD_STATS_KEY);
    const stats: UploadStatsIndex = existing ?? { users: {}, lastUpdated: 0 };

    if (!stats.users[normalizedAddress]) {
      stats.users[normalizedAddress] = {
        totalUploads: 0,
        totalBytesUploaded: 0,
        firstUploadAt: Date.now(),
        lastUploadAt: Date.now(),
        dailyUploads: {},
      };
    }

    const u = stats.users[normalizedAddress];
    u.totalUploads += 1;
    u.totalBytesUploaded += fileSizeBytes;
    u.lastUploadAt = Date.now();
    u.dailyUploads[today] = (u.dailyUploads[today] ?? 0) + 1;

    // Clean up daily counts older than 7 days to keep the record lean
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setUTCDate(sevenDaysAgo.getUTCDate() - 7);
    const cutoff = sevenDaysAgo.toISOString().slice(0, 10);
    for (const date of Object.keys(u.dailyUploads)) {
      if (date < cutoff) delete u.dailyUploads[date];
    }

    stats.lastUpdated = Date.now();
    await setKV(UPLOAD_STATS_KEY, stats);
  } catch (err) {
    console.error("[upload-rate-limit] Error recording upload:", err);
  }
}
src/lib/upload-recovery.ts
/**
 * Upload Recovery System
 * Saves upload progress to localStorage so interrupted uploads can be resumed
 */

export interface UploadRecoveryState {
  // File info
  fileName: string;
  fileSize: number;
  fileType: string;
  fileHash?: string; // SHA-256 hash to verify it's the same file

  // Metadata
  title: string;
  author: string;
  categories: string[];
  coverUrl?: string;

  // Upload progress
  storageKey: string;
  storageType: "regular" | "chunked" | "xml";
  totalChunks: number;
  completedChunkKeys: string[]; // For XML uploads, track which chunk keys were stored
  allChunkKeys?: string[]; // ALL chunk keys in order (for resume to reuse same keys)

  // Wallet info
  walletAddress: string;

  // Timestamps
  startedAt: number;
  lastUpdatedAt: number;
}

const RECOVERY_KEY = "net-library-upload-recovery";

/**
 * Save upload state for potential recovery
 */
export function saveUploadState(state: UploadRecoveryState): void {
  try {
    localStorage.setItem(RECOVERY_KEY, JSON.stringify(state));
  } catch (e) {
    console.error("[upload-recovery] Failed to save state:", e);
  }
}

/**
 * Update just the completed chunks (called after each successful chunk)
 */
export function updateCompletedChunks(chunkKey: string): void {
  try {
    const saved = localStorage.getItem(RECOVERY_KEY);
    if (!saved) return;

    const state: UploadRecoveryState = JSON.parse(saved);
    if (!state.completedChunkKeys.includes(chunkKey)) {
      state.completedChunkKeys.push(chunkKey);
      state.lastUpdatedAt = Date.now();
      localStorage.setItem(RECOVERY_KEY, JSON.stringify(state));
    }
  } catch (e) {
    console.error("[upload-recovery] Failed to update chunks:", e);
  }
}

/**
 * Get any saved upload state for recovery
 */
export function getRecoveryState(): UploadRecoveryState | null {
  try {
    const saved = localStorage.getItem(RECOVERY_KEY);
    if (!saved) return null;

    const state: UploadRecoveryState = JSON.parse(saved);

    // Check if state is stale (older than 24 hours)
    const maxAge = 24 * 60 * 60 * 1000; // 24 hours
    if (Date.now() - state.lastUpdatedAt > maxAge) {
      clearRecoveryState();
      return null;
    }

    return state;
  } catch (e) {
    console.error("[upload-recovery] Failed to get state:", e);
    return null;
  }
}

/**
 * Check if there's a recoverable upload for a specific wallet
 */
export function hasRecoverableUpload(walletAddress: string): boolean {
  const state = getRecoveryState();
  if (!state) return false;

  return (
    state.walletAddress.toLowerCase() === walletAddress.toLowerCase() &&
    state.completedChunkKeys.length > 0 &&
    state.completedChunkKeys.length < state.totalChunks
  );
}

/**
 * Clear recovery state (called on successful upload completion)
 */
export function clearRecoveryState(): void {
  try {
    localStorage.removeItem(RECOVERY_KEY);
  } catch (e) {
    console.error("[upload-recovery] Failed to clear state:", e);
  }
}

/**
 * Get human-readable recovery info
 */
export function getRecoveryInfo(state: UploadRecoveryState): {
  progress: string;
  timeAgo: string;
  chunksRemaining: number;
} {
  const completedCount = state.completedChunkKeys.length;
  const progress = `${completedCount} of ${state.totalChunks} chunks uploaded`;

  const minutesAgo = Math.floor((Date.now() - state.lastUpdatedAt) / (60 * 1000));
  const hoursAgo = Math.floor(minutesAgo / 60);
  const timeAgo = hoursAgo > 0
    ? `${hoursAgo} hour${hoursAgo !== 1 ? "s" : ""} ago`
    : minutesAgo > 0
    ? `${minutesAgo} minute${minutesAgo !== 1 ? "s" : ""} ago`
    : "just now";

  return {
    progress,
    timeAgo,
    chunksRemaining: state.totalChunks - completedCount,
  };
}
src/lib/wagmi-x402-adapter.ts
/**
 * Wagmi x402 Adapter
 *
 * Creates a LocalAccount-compatible object from wagmi's WalletClient.
 * This allows the @net-protocol/relay SDK to work with Farcaster Mini Apps
 * and other wagmi-based wallet connections.
 *
 * The key insight: LocalAccount only needs:
 * - address: The wallet address
 * - signTypedData: A function to sign EIP-712 typed data
 *
 * Wagmi's WalletClient provides both, so we just wrap it.
 *
 * NOTE: The SDK passes BigInt values (e.g., expiresAt) which fail JSON serialization
 * on Coinbase Smart Wallets (Base App). We convert BigInt to string before signing.
 */

import type { Address, WalletClient } from "viem";
import type { LocalAccount } from "viem/accounts";

/**
 * Recursively converts BigInt values to strings for JSON serialization.
 * Required for Coinbase Smart Wallets (Base App) which fail on BigInt in RPC calls.
 */
function sanitizeBigInts(obj: unknown): unknown {
  if (typeof obj === "bigint") {
    return obj.toString();
  }
  if (Array.isArray(obj)) {
    return obj.map(sanitizeBigInts);
  }
  if (obj !== null && typeof obj === "object") {
    const result: Record<string, unknown> = {};
    for (const [key, value] of Object.entries(obj)) {
      result[key] = sanitizeBigInts(value);
    }
    return result;
  }
  return obj;
}

/**
 * Creates a LocalAccount-compatible signer from a wagmi WalletClient.
 *
 * This adapter enables the @net-protocol/relay SDK to work with:
 * - Farcaster Mini App wallets (Smart Wallets via EIP-5792)
 * - WalletConnect wallets
 * - Browser extension wallets
 * - Any wagmi-connected wallet
 *
 * @param walletClient - The wagmi WalletClient instance
 * @returns A LocalAccount-compatible object that can be used with the relay SDK
 *
 * @example
 * ```typescript
 * const { data: walletClient } = useWalletClient();
 * const account = createWagmiLocalAccount(walletClient);
 *
 * // Now use with @net-protocol/relay SDK
 * const relayClient = new RelayClient({ apiUrl, chainId });
 * const { sessionToken } = await relayClient.createSession({
 *   operatorAddress: account.address,
 *   secretKey: "[REDACTED]",
 *   account,
 * });
 * ```
 */
export function createWagmiLocalAccount(walletClient: WalletClient): LocalAccount {
  if (!walletClient.account) {
    throw new Error("WalletClient has no account. Ensure wallet is connected.");
  }

  const address = walletClient.account.address;

  // Create a LocalAccount-compatible object
  // The SDK only uses address and signTypedData
  const account = {
    address,
    publicKey: "0x" as `0x${string}`, // Not used by relay SDK
    source: "wagmi" as const,
    type: "local" as const,

    // The key method - signs EIP-712 typed data
    signTypedData: async (params: {
      domain: Record<string, unknown>;
      types: Record<string, unknown>;
      primaryType: string;
      message: Record<string, unknown>;
    }): Promise<`0x${string}`> => {
      // Sanitize BigInt values for Base App (Coinbase Smart Wallet) compatibility
      // The SDK passes BigInt(expiresAt) which fails JSON serialization in RPC calls
      const sanitizedMessage = sanitizeBigInts(params.message) as Record<string, unknown>;
      const sanitizedDomain = sanitizeBigInts(params.domain) as Record<string, unknown>;

      console.log(`[WAGMI-ADAPTER] Signing typed data...`);
      console.log(`[WAGMI-ADAPTER] Domain:`, JSON.stringify(sanitizedDomain));
      console.log(`[WAGMI-ADAPTER] Message:`, JSON.stringify(sanitizedMessage));

      const signature = await walletClient.signTypedData({
        account: walletClient.account!,
        domain: sanitizedDomain as Parameters<typeof walletClient.signTypedData>[0]["domain"],
        types: params.types as Parameters<typeof walletClient.signTypedData>[0]["types"],
        primaryType: params.primaryType,
        message: sanitizedMessage,
      });

      console.log(`[WAGMI-ADAPTER] Signature received: ${signature?.slice(0, 20)}... (${signature?.length} chars)`);

      // Validate signature format - Net Protocol requires 132 char hex string (0x + 130 hex = 65 bytes)
      if (!signature || typeof signature !== "string") {
        console.error(`[WAGMI-ADAPTER] Invalid signature type:`, typeof signature);
        throw new Error(`Invalid signature: expected string, got ${typeof signature}`);
      }

      if (!signature.startsWith("0x")) {
        console.error(`[WAGMI-ADAPTER] Signature missing 0x prefix:`, signature.slice(0, 20));
        throw new Error(`Invalid signature: missing 0x prefix`);
      }

      // Standard ECDSA = 132 chars, but Smart Wallets return longer ERC-1271 signatures
      // Net Protocol backend now supports ERC-1271 verification (June 2025)
      if (signature.length !== 132) {
        console.log(`[WAGMI-ADAPTER] ERC-1271 smart wallet signature: ${signature.length} chars`);
        console.log(`[WAGMI-ADAPTER] Passing through to Net Protocol for on-chain verification`);
      }

      return signature;
    },

    // These methods are required by LocalAccount but not used by relay SDK
    sign: async () => {
      throw new Error("sign() not implemented - use signTypedData instead");
    },
    signMessage: async () => {
      throw new Error("signMessage() not implemented - use signTypedData instead");
    },
    signTransaction: async () => {
      throw new Error("signTransaction() not implemented - use signTypedData instead");
    },

    // Additional required properties
    experimental_signAuthorization: undefined,
    nonceManager: undefined,
  } as unknown as LocalAccount;

  return account;
}

/**
 * Alternative: Create LocalAccount from address + signTypedData function
 *
 * Use this when you have direct access to signTypedDataAsync from wagmi hooks
 * (e.g., useSignTypedData) instead of a full WalletClient.
 *
 * @param address - The wallet address
 * @param signTypedDataFn - The signTypedData function (from useSignTypedData hook)
 */
export function createLocalAccountFromSignTypedData(
  address: Address,
  signTypedDataFn: (params: {
    domain: Record<string, unknown>;
    types: Record<string, unknown>;
    primaryType: string;
    message: Record<string, unknown>;
  }) => Promise<`0x${string}`>
): LocalAccount {
  const account = {
    address,
    publicKey: "0x" as `0x${string}`,
    source: "wagmi" as const,
    type: "local" as const,
    signTypedData: signTypedDataFn,
    sign: async () => {
      throw new Error("sign() not implemented");
    },
    signMessage: async () => {
      throw new Error("signMessage() not implemented");
    },
    signTransaction: async () => {
      throw new Error("signTransaction() not implemented");
    },
    experimental_signAuthorization: undefined,
    nonceManager: undefined,
  } as unknown as LocalAccount;

  return account;
}
src/lib/x402-config.ts
/**
 * x402 Payment Configuration for Net Library
 *
 * This file contains the configuration for x402 payments.
 * Use withX402 wrapper for individual API routes (recommended)
 * or paymentMiddleware for global protection.
 *
 * Documentation: https://x402.org
 * GitHub: https://github.com/coinbase/x402
 */

// Treasury address for receiving payments
export const TREASURY_ADDRESS = "0x18A432D008a0e5E1D611eae194EE3bdc7FD3f3FA" as const;

// Network configuration
// "base" for mainnet, "base-sepolia" for testnet
export const PAYMENT_NETWORK = "base" as const;

// Default facilitator (handles payment verification and settlement)
export const FACILITATOR_CONFIG = {
  url: "https://x402.org/facilitator",
};

/**
 * Pre-configured route configs for common use cases
 * Import these when wrapping routes with withX402
 */
export const PRICE_CONFIGS = {
  // Micropayment for content access
  microPayment: {
    price: "$0.01",
    network: PAYMENT_NETWORK,
    config: {
      description: "Access content on Net Library",
    },
  },

  // Standard content fee
  standardContent: {
    price: "$0.10",
    network: PAYMENT_NETWORK,
    config: {
      description: "Download from Net Library",
    },
  },

  // Premium feature access
  premiumAccess: {
    price: "$1.00",
    network: PAYMENT_NETWORK,
    config: {
      description: "Premium Net Library access",
    },
  },

  // Membership fee
  membership: {
    price: "$5.00",
    network: PAYMENT_NETWORK,
    config: {
      description: "Net Library Membership",
    },
  },
} as const;

/**
 * Example: How to protect an API route with x402
 *
 * ```typescript
 * // In your API route file (e.g., /api/premium/route.ts)
 * import { NextRequest, NextResponse } from "next/server";
 * import { withX402 } from "x402-next";
 * import { TREASURY_ADDRESS, PRICE_CONFIGS, FACILITATOR_CONFIG } from "@/lib/x402-config";
 *
 * const handler = async (request: NextRequest) => {
 *   // Your API logic here
 *   return NextResponse.json({ data: "premium content" });
 * };
 *
 * export const GET = withX402(
 *   handler,
 *   TREASURY_ADDRESS,
 *   PRICE_CONFIGS.premiumAccess,
 *   FACILITATOR_CONFIG
 * );
 * ```
 */
src/settings/app-images.json
{
  "iconUrl": "/app-logo.png",
  "splashImageUrl": "/app-splash.png",
  "heroImageUrl": "/app-hero.png",
  "imageUrl": "/app-hero.png"
}
src/settings/app-settings.json
{
  "name": "Net Library",
  "shortName": "NetLib",
  "subtitle": "Decentralized Onchain Files",
  "description": "Upload, view, read, and share files stored onchain - all powered by Net Protocol.",
  "shortDescription": "Decentralized onchain file storage powered by Net Protocol.",
  "primaryCategory": "social",
  "tags": ["pdf", "storage", "reading"],
  "splashBackgroundColor": "#0a0f0a",
  "tagline": "Decentralized Onchain Files",
  "requiredChains": ["eip155:8453", "eip155:1"],
  "useDynamicShareImage": false,
  "shareButtonTitle": "View Files"
}
public/netlibrary-eth-landing.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Net Library - Decentralized Onchain Media Library</title>
  <meta name="description" content="The world's first fully onchain decentralized media library. Upload, read, upvote, and share media permanently on the blockchain.">

  <!-- Open Graph -->
  <meta property="og:title" content="Net Library - Decentralized Onchain Media Library">
  <meta property="og:description" content="Upload, read, upvote, and share media permanently on the blockchain.">
  <meta property="og:type" content="website">
  <meta property="og:url" content="https://netlibrary.eth.limo">

  <!-- Twitter Card -->
  <meta name="twitter:card" content="summary_large_image">
  <meta name="twitter:title" content="Net Library - Decentralized Onchain Media Library">
  <meta name="twitter:description" content="Upload, read, upvote, and share media permanently on the blockchain.">

  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    :root {
      --green: #00ff00;
      --green-dim: rgba(0, 255, 0, 0.7);
      --green-faint: rgba(0, 255, 0, 0.1);
      --green-glow: rgba(0, 255, 0, 0.3);
      --yellow: #facc15;
      --yellow-dim: rgba(250, 204, 21, 0.7);
      --yellow-faint: rgba(250, 204, 21, 0.1);
      --yellow-glow: rgba(250, 204, 21, 0.3);
      --black: #000000;
      --dark: #0a0a0a;
      --gray: #1a1a1a;
      --text-gray: #888888;
      --farcaster: #8A63D2;
      --base: #0052FF;
    }

    @font-face {
      font-family: 'Terminal';
      src: local('Courier New'), local('monospace');
    }

    body {
      font-family: 'Courier New', Courier, monospace;
      background-color: var(--black);
      color: var(--green);
      min-height: 100vh;
      line-height: 1.6;
      overflow-x: hidden;
    }

    /* Scanline effect */
    body::before {
      content: '';
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: repeating-linear-gradient(
        0deg,
        transparent 0px,
        transparent 2px,
        rgba(0, 0, 0, 0.1) 2px,
        rgba(0, 0, 0, 0.1) 4px
      );
      pointer-events: none;
      z-index: 1000;
      opacity: 0.3;
    }

    /* Container */
    .container {
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
    }

    /* Header */
    header {
      text-align: center;
      padding: 40px 20px;
      border-bottom: 1px solid var(--green-faint);
      background: linear-gradient(180deg, var(--green-faint) 0%, transparent 100%);
    }

    .logo-container {
      margin-bottom: 24px;
    }

    .logo {
      width: 120px;
      height: 150px;
    }

    h1 {
      font-size: 2.5rem;
      letter-spacing: 4px;
      text-shadow: 0 0 20px var(--green-glow);
      margin-bottom: 8px;
    }

    .tagline {
      color: var(--green-dim);
      font-size: 0.9rem;
      letter-spacing: 2px;
    }

    /* Launch Buttons */
    .launch-section {
      padding: 40px 20px;
      border-bottom: 1px solid var(--green-faint);
    }

    .launch-section h2 {
      text-align: center;
      font-size: 1rem;
      color: var(--green-dim);
      margin-bottom: 24px;
      letter-spacing: 3px;
    }

    .launch-buttons {
      display: flex;
      flex-direction: column;
      gap: 16px;
      max-width: 400px;
      margin: 0 auto;
    }

    .launch-btn {
      display: flex;
      align-items: center;
      gap: 16px;
      padding: 16px 24px;
      border-radius: 12px;
      text-decoration: none;
      font-family: inherit;
      font-size: 1rem;
      font-weight: bold;
      transition: all 0.2s ease;
      cursor: pointer;
      border: 2px solid;
    }

    .launch-btn .icon {
      width: 40px;
      height: 40px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
    }

    .launch-btn .text {
      flex: 1;
      text-align: left;
    }

    .launch-btn .text .title {
      display: block;
      font-weight: bold;
    }

    .launch-btn .text .subtitle {
      display: block;
      font-size: 0.7rem;
      opacity: 0.7;
      margin-top: 2px;
    }

    .launch-btn .arrow {
      font-size: 1.2rem;
      opacity: 0.5;
    }

    /* Farcaster Button */
    .launch-btn.farcaster {
      background: rgba(138, 99, 210, 0.1);
      border-color: rgba(138, 99, 210, 0.3);
      color: var(--farcaster);
    }

    .launch-btn.farcaster:hover {
      background: rgba(138, 99, 210, 0.2);
      border-color: var(--farcaster);
      box-shadow: 0 0 20px rgba(138, 99, 210, 0.3);
    }

    .launch-btn.farcaster .icon {
      background: rgba(138, 99, 210, 0.2);
    }

    /* Base Button */
    .launch-btn.base {
      background: rgba(0, 82, 255, 0.1);
      border-color: rgba(0, 82, 255, 0.3);
      color: var(--base);
    }

    .launch-btn.base:hover {
      background: rgba(0, 82, 255, 0.2);
      border-color: var(--base);
      box-shadow: 0 0 20px rgba(0, 82, 255, 0.3);
    }

    .launch-btn.base .icon {
      background: rgba(0, 82, 255, 0.2);
    }

    /* Browser Button */
    .launch-btn.browser {
      background: var(--yellow-faint);
      border-color: rgba(250, 204, 21, 0.3);
      color: var(--yellow);
    }

    .launch-btn.browser:hover {
      background: rgba(250, 204, 21, 0.15);
      border-color: var(--yellow);
      box-shadow: 0 0 20px var(--yellow-glow);
    }

    .launch-btn.browser .icon {
      background: rgba(250, 204, 21, 0.2);
    }

    /* Tabs Section */
    .tabs-section {
      padding: 40px 20px;
    }

    .tabs-nav {
      display: flex;
      gap: 8px;
      margin-bottom: 24px;
      overflow-x: auto;
      padding-bottom: 8px;
    }

    .tab-btn {
      padding: 12px 20px;
      background: var(--dark);
      border: 1px solid var(--gray);
      border-radius: 8px;
      color: var(--text-gray);
      font-family: inherit;
      font-size: 0.85rem;
      cursor: pointer;
      transition: all 0.2s ease;
      white-space: nowrap;
    }

    .tab-btn:hover {
      border-color: var(--green-glow);
      color: var(--green-dim);
    }

    .tab-btn.active {
      background: var(--green-faint);
      border-color: rgba(0, 255, 0, 0.3);
      color: var(--green);
    }

    .tab-content {
      display: none;
    }

    .tab-content.active {
      display: block;
    }

    /* Features Grid */
    .features-grid {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 16px;
    }

    @media (max-width: 600px) {
      .features-grid {
        grid-template-columns: 1fr;
      }
    }

    .feature-card {
      background: var(--dark);
      border: 1px solid var(--gray);
      border-radius: 12px;
      padding: 20px;
      transition: all 0.2s ease;
    }

    .feature-card:hover {
      border-color: var(--green-glow);
      box-shadow: 0 0 15px rgba(0, 255, 0, 0.1);
    }

    .feature-card .emoji {
      font-size: 2rem;
      margin-bottom: 12px;
    }

    .feature-card h3 {
      font-size: 1rem;
      margin-bottom: 8px;
      color: var(--green);
    }

    .feature-card p {
      font-size: 0.8rem;
      color: var(--text-gray);
      line-height: 1.5;
    }

    /* Accordion/Dropdown */
    .accordion {
      margin-top: 24px;
    }

    .accordion-item {
      border: 1px solid var(--gray);
      border-radius: 8px;
      margin-bottom: 8px;
      overflow: hidden;
    }

    .accordion-header {
      width: 100%;
      padding: 16px 20px;
      background: var(--dark);
      border: none;
      color: var(--green);
      font-family: inherit;
      font-size: 0.9rem;
      text-align: left;
      cursor: pointer;
      display: flex;
      justify-content: space-between;
      align-items: center;
      transition: all 0.2s ease;
    }

    .accordion-header:hover {
      background: var(--gray);
    }

    .accordion-header .arrow {
      transition: transform 0.2s ease;
    }

    .accordion-item.open .accordion-header .arrow {
      transform: rotate(180deg);
    }

    .accordion-content {
      max-height: 0;
      overflow: hidden;
      transition: max-height 0.3s ease;
      background: var(--black);
    }

    .accordion-item.open .accordion-content {
      max-height: 500px;
    }

    .accordion-content-inner {
      padding: 20px;
      font-size: 0.85rem;
      color: var(--text-gray);
      line-height: 1.7;
    }

    .accordion-content-inner ul {
      margin-left: 20px;
      margin-top: 8px;
    }

    .accordion-content-inner li {
      margin-bottom: 4px;
    }

    /* Stats Banner */
    .stats-banner {
      background: linear-gradient(135deg, var(--green-faint) 0%, transparent 100%);
      border: 2px solid rgba(0, 255, 0, 0.3);
      border-radius: 16px;
      padding: 24px;
      margin: 24px 0;
    }

    .stats-banner h3 {
      text-align: center;
      font-size: 0.9rem;
      color: var(--green-dim);
      margin-bottom: 16px;
      letter-spacing: 2px;
    }

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 16px;
      text-align: center;
    }

    .stat-item .value {
      font-size: 1.5rem;
      font-weight: bold;
      color: var(--green);
    }

    .stat-item .label {
      font-size: 0.7rem;
      color: var(--text-gray);
      margin-top: 4px;
    }

    /* Resources Links */
    .resources-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 12px;
      margin-top: 16px;
    }

    .resource-link {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 16px;
      background: var(--dark);
      border: 1px solid var(--gray);
      border-radius: 8px;
      text-decoration: none;
      color: var(--green);
      transition: all 0.2s ease;
    }

    .resource-link:hover {
      border-color: var(--green-glow);
      background: var(--green-faint);
    }

    .resource-link .emoji {
      font-size: 1.5rem;
      margin-bottom: 8px;
    }

    .resource-link .text {
      font-size: 0.75rem;
      text-align: center;
    }

    /* Footer */
    footer {
      text-align: center;
      padding: 40px 20px;
      border-top: 1px solid var(--green-faint);
      margin-top: 40px;
    }

    footer p {
      font-size: 0.8rem;
      color: var(--text-gray);
      margin-bottom: 8px;
    }

    footer .powered-by {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      color: var(--green-dim);
      font-size: 0.75rem;
    }

    footer .links {
      margin-top: 16px;
      display: flex;
      justify-content: center;
      gap: 24px;
    }

    footer .links a {
      color: var(--text-gray);
      text-decoration: none;
      font-size: 0.75rem;
      transition: color 0.2s ease;
    }

    footer .links a:hover {
      color: var(--green);
    }

    /* Scrollbar */
    ::-webkit-scrollbar {
      width: 8px;
      height: 8px;
    }

    ::-webkit-scrollbar-track {
      background: var(--dark);
    }

    ::-webkit-scrollbar-thumb {
      background: var(--gray);
      border-radius: 4px;
    }

    ::-webkit-scrollbar-thumb:hover {
      background: var(--green-glow);
    }

    /* Glow animation */
    @keyframes glow {
      0%, 100% { text-shadow: 0 0 20px var(--green-glow); }
      50% { text-shadow: 0 0 30px var(--green), 0 0 40px var(--green-glow); }
    }

    h1 {
      animation: glow 3s ease-in-out infinite;
    }
  </style>
</head>
<body>
  <div class="container">
    <!-- Header -->
    <header>
      <div class="logo-container">
        <!-- Net Library App Logo -->
        <img src="/app-logo.png" alt="Net Library" class="logo" style="width: 120px; height: auto; filter: drop-shadow(0 0 10px rgba(0, 255, 0, 0.5));" />
      </div>

      <h1>NET LIBRARY</h1>
      <p class="tagline">THE WORLD'S FIRST FULLY ONCHAIN DECENTRALIZED MEDIA LIBRARY</p>
    </header>

    <!-- Launch Buttons -->
    <section class="launch-section">
      <h2>// LAUNCH NET LIBRARY</h2>

      <div class="launch-buttons">
        <!-- Farcaster -->
        <a href="https://warpcast.com/~/frames/launch?domain=miniapp-generator-fid-282520-251210015136529.neynar.app" class="launch-btn farcaster">
          <div class="icon">
            <svg width="24" height="24" viewBox="0 0 1000 1000" fill="none">
              <path d="M257.778 155.556H742.222V844.444H671.111V528.889H670.414C662.554 441.677 589.258 373.333 500 373.333C410.742 373.333 337.446 441.677 329.586 528.889H328.889V844.444H257.778V155.556Z" fill="#8A63D2"/>
              <path d="M128.889 253.333L157.778 351.111H182.222V746.667C169.949 746.667 160 756.616 160 768.889V795.556H155.556C143.283 795.556 133.333 805.505 133.333 817.778V844.444H382.222V817.778C382.222 805.505 372.273 795.556 360 795.556H355.556V768.889C355.556 756.616 345.606 746.667 333.333 746.667H306.667V253.333H128.889Z" fill="#8A63D2"/>
              <path d="M675.556 746.667C663.283 746.667 653.333 756.616 653.333 768.889V795.556H648.889C636.616 795.556 626.667 805.505 626.667 817.778V844.444H875.556V817.778C875.556 805.505 865.606 795.556 853.333 795.556H848.889V768.889C848.889 756.616 838.94 746.667 826.667 746.667V351.111H851.111L880 253.333H702.222V746.667H675.556Z" fill="#8A63D2"/>
            </svg>
          </div>
          <div class="text">
            <span class="title">Open in Warpcast</span>
            <span class="subtitle">Farcaster Mini App</span>
          </div>
          <span class="arrow">→</span>
        </a>

        <!-- Base -->
        <a href="https://go.base.org/mini-apps?app=net-library" class="launch-btn base">
          <div class="icon">
            <svg width="24" height="24" viewBox="0 0 111 111" fill="none">
              <path d="M54.921 110.034C85.359 110.034 110.034 85.402 110.034 55.017C110.034 24.6319 85.359 0 54.921 0C26.0432 0 2.35281 22.1714 0 50.3923H72.8467V59.6416H0C2.35281 87.8625 26.0432 110.034 54.921 110.034Z" fill="#0052FF"/>
            </svg>
          </div>
          <div class="text">
            <span class="title">Open in Coinbase Wallet</span>
            <span class="subtitle">Base App</span>
          </div>
          <span class="arrow">→</span>
        </a>

        <!-- Browser -->
        <a href="https://miniapp-generator-fid-282520-251210015136529.neynar.app/" class="launch-btn browser">
          <div class="icon">
            <span style="font-size: 24px;">🌐</span>
          </div>
          <div class="text">
            <span class="title">Open in Browser</span>
            <span class="subtitle">Web Version</span>
          </div>
          <span class="arrow">→</span>
        </a>
      </div>
    </section>

    <!-- Tabs Section -->
    <section class="tabs-section">
      <div class="tabs-nav">
        <button class="tab-btn active" data-tab="features">Features</button>
        <button class="tab-btn" data-tab="how-it-works">How It Works</button>
        <button class="tab-btn" data-tab="membership">Membership</button>
        <button class="tab-btn" data-tab="resources">Resources</button>
      </div>

      <!-- Features Tab -->
      <div class="tab-content active" id="features">
        <div class="features-grid">
          <div class="feature-card">
            <div class="emoji">📤</div>
            <h3>Upload Media</h3>
            <p>Upload PDFs, images, audio, video, and text files permanently to the blockchain.</p>
          </div>

          <div class="feature-card">
            <div class="emoji">📚</div>
            <h3>Curate Stacks</h3>
            <p>Create and share themed collections. Organize content into browsable stacks.</p>
          </div>

          <div class="feature-card">
            <div class="emoji">▲</div>
            <h3>Upvote Content</h3>
            <p>Support creators with onchain upvotes powered by Score Protocol.</p>
          </div>

          <div class="feature-card">
            <div class="emoji">🎴</div>
            <h3>Library Card NFT</h3>
            <p>Mint your membership card with ENS subname (yourname.netlibrary.eth).</p>
          </div>

          <div class="feature-card">
            <div class="emoji">📖</div>
            <h3>Built-in Reader</h3>
            <p>Read documents with zoom, bookmarks, and progress tracking.</p>
          </div>

          <div class="feature-card">
            <div class="emoji">🎬</div>
            <h3>Media Player</h3>
            <p>View images, play audio and video with fullscreen mode.</p>
          </div>
        </div>
      </div>

      <!-- How It Works Tab -->
      <div class="tab-content" id="how-it-works">
        <div class="accordion">
          <div class="accordion-item">
            <button class="accordion-header">
              <span>What is Net Library?</span>
              <span class="arrow">▼</span>
            </button>
            <div class="accordion-content">
              <div class="accordion-content-inner">
                Net Library is the world's first fully onchain decentralized media library. All content is stored permanently on the blockchain using Net Protocol, making it uncensorable and always accessible.
              </div>
            </div>
          </div>

          <div class="accordion-item">
            <button class="accordion-header">
              <span>How is content stored?</span>
              <span class="arrow">▼</span>
            </button>
            <div class="accordion-content">
              <div class="accordion-content-inner">
                Content is stored directly onchain using Net Protocol's storage architecture on Base. Files are chunked, compressed, and stored in smart contract storage - no IPFS, no centralized servers.
              </div>
            </div>
          </div>

          <div class="accordion-item">
            <button class="accordion-header">
              <span>What can I upload?</span>
              <span class="arrow">▼</span>
            </button>
            <div class="accordion-content">
              <div class="accordion-content-inner">
                Net Library supports multiple media types:
                <ul>
                  <li>PDFs and documents</li>
                  <li>Images (PNG, JPG, GIF, WebP)</li>
                  <li>Audio files (MP3, WAV)</li>
                  <li>Video files (MP4, WebM)</li>
                  <li>Text files (TXT, Markdown)</li>
                </ul>
              </div>
            </div>
          </div>

          <div class="accordion-item">
            <button class="accordion-header">
              <span>What are Stacks?</span>
              <span class="arrow">▼</span>
            </button>
            <div class="accordion-content">
              <div class="accordion-content-inner">
                Stacks are curated collections of content. Anyone can create a Stack around a theme (e.g., "Crypto Research", "Art Books", "Podcasts") and add items to it. Stacks can be upvoted and shared.
              </div>
            </div>
          </div>

          <div class="accordion-item">
            <button class="accordion-header">
              <span>How do upvotes work?</span>
              <span class="arrow">▼</span>
            </button>
            <div class="accordion-content">
              <div class="accordion-content-inner">
                Upvotes are powered by Score Protocol - fully onchain and verifiable. When you upvote content, it's recorded permanently on Base. Upvotes help surface quality content and support creators.
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Membership Tab -->
      <div class="tab-content" id="membership">
        <div class="stats-banner">
          <h3>// MEMBERSHIP BENEFITS</h3>
          <div class="stats-grid">
            <div class="stat-item">
              <div class="value">$2</div>
              <div class="label">USDC One-Time</div>
            </div>
            <div class="stat-item">
              <div class="value">∞</div>
              <div class="label">Lifetime Access</div>
            </div>
            <div class="stat-item">
              <div class="value">NFT</div>
              <div class="label">Library Card</div>
            </div>
          </div>
        </div>

        <div class="accordion">
          <div class="accordion-item">
            <button class="accordion-header">
              <span>What do members get?</span>
              <span class="arrow">▼</span>
            </button>
            <div class="accordion-content">
              <div class="accordion-content-inner">
                <ul>
                  <li><strong>Library Card NFT</strong> - Your unique membership token</li>
                  <li><strong>ENS Subname</strong> - yourname.netlibrary.eth</li>
                  <li><strong>Upload Access</strong> - Upload content to the library</li>
                  <li><strong>Create Stacks</strong> - Curate your own collections</li>
                  <li><strong>Achievement System</strong> - Earn badges for contributions</li>
                  <li><strong>Leaderboard</strong> - Track your standing</li>
                </ul>
              </div>
            </div>
          </div>

          <div class="accordion-item">
            <button class="accordion-header">
              <span>How do I become a member?</span>
              <span class="arrow">▼</span>
            </button>
            <div class="accordion-content">
              <div class="accordion-content-inner">
                1. Open Net Library in your preferred app<br>
                2. Go to the Profile tab<br>
                3. Click "Become a Member"<br>
                4. Choose your ENS subname<br>
                5. Pay $2 USDC (one-time)<br>
                6. Receive your Library Card NFT!
              </div>
            </div>
          </div>

          <div class="accordion-item">
            <button class="accordion-header">
              <span>Can I browse without membership?</span>
              <span class="arrow">▼</span>
            </button>
            <div class="accordion-content">
              <div class="accordion-content-inner">
                Yes! Anyone can browse and read content in Net Library for free. Membership is only required to upload content, create stacks, and participate in the upvote system.
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Resources Tab -->
      <div class="tab-content" id="resources">
        <div class="resources-grid">
          <a href="https://miniapp-generator-fid-282520-251210015136529.neynar.app/net-library-overview.html" class="resource-link" target="_blank">
            <span class="emoji">📖</span>
            <span class="text">Overview</span>
          </a>
          <a href="https://miniapp-generator-fid-282520-251210015136529.neynar.app/net-library-specs.html" class="resource-link" target="_blank">
            <span class="emoji">⚙️</span>
            <span class="text">Technical</span>
          </a>
          <a href="https://miniapp-generator-fid-282520-251210015136529.neynar.app/net-library-docs.html" class="resource-link" target="_blank">
            <span class="emoji">💻</span>
            <span class="text">Code Docs</span>
          </a>
        </div>

        <div class="accordion" style="margin-top: 24px;">
          <div class="accordion-item">
            <button class="accordion-header">
              <span>Built With</span>
              <span class="arrow">▼</span>
            </button>
            <div class="accordion-content">
              <div class="accordion-content-inner">
                <ul>
                  <li><strong>Net Protocol</strong> - Onchain storage infrastructure</li>
                  <li><strong>Score Protocol</strong> - Onchain upvote system</li>
                  <li><strong>Base</strong> - L2 blockchain</li>
                  <li><strong>ENS</strong> - Decentralized naming</li>
                  <li><strong>Farcaster</strong> - Social protocol</li>
                  <li><strong>Neynar</strong> - Farcaster infrastructure</li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- Footer -->
    <footer>
      <p>Media should be permanent, uncensorable, and accessible to all.</p>
      <div class="powered-by">
        <span>Powered by</span>
        <strong>Net Protocol</strong>
        <span>on</span>
        <strong>Base</strong>
      </div>
      <div class="links">
        <a href="https://netprotocol.app" target="_blank">Net Protocol</a>
        <a href="https://base.org" target="_blank">Base</a>
        <a href="https://ens.domains" target="_blank">ENS</a>
      </div>
    </footer>
  </div>

  <script>
    // Tab functionality
    document.querySelectorAll('.tab-btn').forEach(btn => {
      btn.addEventListener('click', () => {
        // Remove active from all tabs
        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));

        // Add active to clicked tab
        btn.classList.add('active');
        document.getElementById(btn.dataset.tab).classList.add('active');
      });
    });

    // Accordion functionality
    document.querySelectorAll('.accordion-header').forEach(header => {
      header.addEventListener('click', () => {
        const item = header.parentElement;
        item.classList.toggle('open');
      });
    });
  </script>
</body>
</html>
public/net-library-docs.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <title>Net Library - Code Documentation</title>
  <script>
    // Scroll to top on page load (fixes modal iframe scroll position issue)
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => window.scrollTo(0, 0));
    } else {
      window.scrollTo(0, 0);
    }
    window.addEventListener('load', () => window.scrollTo(0, 0));
  </script>
  <style>
    @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;600;700&display=swap');

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    html, body {
      font-family: 'JetBrains Mono', monospace;
      background: #000;
      color: #fff;
      line-height: 1.5;
      font-size: 13px;
      overflow-x: hidden;
      width: 100%;
      max-width: 100vw;
    }

    .header {
      position: sticky;
      top: 0;
      background: rgba(0, 0, 0, 0.95);
      border-bottom: 1px solid rgba(0, 255, 0, 0.3);
      padding: 12px 16px;
      padding-right: 60px; /* Make room for modal close button (X) when opened in iframe */
      z-index: 100;
      backdrop-filter: blur(10px);
    }

    .header-content {
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 12px;
    }

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .logo {
      width: 32px;
      height: 32px;
    }

    .header h1 {
      font-size: 16px;
      color: #00ff00;
      letter-spacing: 2px;
    }

    .header .subtitle {
      font-size: 10px;
      color: #666;
    }

    /* Quick actions dropdown in header */
    .quick-actions {
      position: relative;
    }

    /* Hide quick actions by default - shown only for members */
    .quick-actions.hidden {
      display: none;
    }

    .quick-actions-btn {
      display: flex;
      align-items: center;
      gap: 6px;
      padding: 8px 12px;
      background: rgba(0, 255, 0, 0.1);
      border: 1px solid rgba(0, 255, 0, 0.3);
      border-radius: 8px;
      color: #00ff00;
      font-size: 11px;
      font-family: inherit;
      cursor: pointer;
      transition: all 0.2s;
    }

    .quick-actions-btn:hover {
      background: rgba(0, 255, 0, 0.2);
    }

    .quick-actions-menu {
      display: none;
      position: absolute;
      top: 100%;
      right: 0;
      margin-top: 4px;
      background: #0a0a0a;
      border: 1px solid rgba(0, 255, 0, 0.3);
      border-radius: 8px;
      padding: 8px;
      min-width: 200px;
      z-index: 200;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
    }

    .quick-actions-menu.open {
      display: block;
    }

    .quick-action-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 10px 12px;
      color: #ccc;
      font-size: 11px;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.2s;
      text-decoration: none;
      border: none;
      background: none;
      width: 100%;
      text-align: left;
      font-family: inherit;
    }

    .quick-action-item:hover {
      background: rgba(0, 255, 0, 0.1);
      color: #00ff00;
    }

    .quick-action-item .icon {
      font-size: 14px;
    }

    .download-btn {
      display: flex;
      align-items: center;
      gap: 6px;
      padding: 8px 16px;
      background: linear-gradient(135deg, rgba(0,255,0,0.2), rgba(0,255,0,0.1));
      border: 1px solid #00ff00;
      border-radius: 8px;
      color: #00ff00;
      font-size: 11px;
      font-family: inherit;
      cursor: pointer;
      transition: all 0.2s;
      text-decoration: none;
    }

    .download-btn:hover {
      background: rgba(0,255,0,0.3);
      box-shadow: 0 0 20px rgba(0,255,0,0.3);
    }

    .page {
      padding: 16px;
      border-bottom: 1px solid rgba(0, 255, 0, 0.1);
    }

    h2 {
      font-size: 16px;
      color: #00ff00;
      margin-bottom: 12px;
      padding-bottom: 8px;
      border-bottom: 1px solid rgba(0, 255, 0, 0.3);
      display: flex;
      align-items: center;
      gap: 8px;
    }

    h3 {
      font-size: 14px;
      color: #00ff00;
      margin: 16px 0 10px 0;
    }

    p {
      font-size: 12px;
      color: #ccc;
      margin-bottom: 10px;
    }

    .card {
      background: #0a0a0a;
      border: 1px solid rgba(0, 255, 0, 0.2);
      border-radius: 8px;
      padding: 12px;
      margin-bottom: 12px;
    }

    .file-list {
      display: grid;
      gap: 6px;
    }

    .file-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 8px 10px;
      background: #0a0a0a;
      border: 1px solid rgba(0, 255, 0, 0.15);
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.2s;
    }

    .file-item:hover {
      border-color: #00ff00;
      background: rgba(0, 255, 0, 0.05);
    }

    .file-item.active {
      border-color: #00ff00;
      background: rgba(0, 255, 0, 0.1);
    }

    .file-name {
      color: #00ff00;
      font-size: 11px;
    }

    .file-path {
      color: #666;
      font-size: 9px;
    }

    .badge {
      font-size: 9px;
      padding: 2px 6px;
      border-radius: 4px;
      background: rgba(0, 255, 0, 0.1);
      color: #00ff00;
    }

    .badge.hook { background: rgba(0, 150, 255, 0.2); color: #0096ff; }
    .badge.component { background: rgba(0, 255, 0, 0.2); color: #00ff00; }
    .badge.api { background: rgba(255, 150, 0, 0.2); color: #ff9600; }
    .badge.share { background: rgba(255, 0, 150, 0.2); color: #ff0096; }

    .code-viewer {
      background: #0a0a0a;
      border: 1px solid rgba(0, 255, 0, 0.2);
      border-radius: 8px;
      overflow: hidden;
    }

    .code-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 8px 12px;
      background: rgba(0, 255, 0, 0.05);
      border-bottom: 1px solid rgba(0, 255, 0, 0.2);
    }

    .code-title {
      color: #00ff00;
      font-size: 11px;
      font-weight: 600;
    }

    .code-actions {
      display: flex;
      gap: 8px;
    }

    .code-btn {
      padding: 4px 10px;
      background: rgba(0, 255, 0, 0.1);
      border: 1px solid rgba(0, 255, 0, 0.3);
      border-radius: 4px;
      color: #00ff00;
      font-size: 10px;
      cursor: pointer;
      transition: all 0.2s;
    }

    .code-btn:hover {
      background: rgba(0, 255, 0, 0.2);
    }

    .code-content {
      max-height: 400px;
      overflow: auto;
      padding: 12px;
    }

    pre {
      margin: 0;
      font-family: 'JetBrains Mono', monospace;
      font-size: 10px;
      line-height: 1.5;
      color: #ccc;
      white-space: pre;
      tab-size: 2;
    }

    .line-numbers {
      display: inline-block;
      width: 36px;
      text-align: right;
      padding-right: 10px;
      margin-right: 10px;
      border-right: 1px solid rgba(0, 255, 0, 0.1);
      color: #444;
      user-select: none;
    }

    .loading {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 30px;
      color: #00ff00;
      font-size: 12px;
    }

    .loading::after {
      content: '';
      width: 16px;
      height: 16px;
      border: 2px solid #00ff00;
      border-top-color: transparent;
      border-radius: 50%;
      animation: spin 1s linear infinite;
      margin-left: 10px;
    }

    @keyframes spin {
      to { transform: rotate(360deg); }
    }

    /* Accordion/Dropdown styles */
    .accordion {
      border: 1px solid rgba(0, 255, 0, 0.2);
      border-radius: 8px;
      overflow: hidden;
      margin-bottom: 8px;
    }

    .accordion-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 12px 14px;
      background: #0a0a0a;
      cursor: pointer;
      transition: all 0.2s;
      border: none;
      width: 100%;
      text-align: left;
      font-family: inherit;
      color: #fff;
    }

    .accordion-header:hover {
      background: rgba(0, 255, 0, 0.05);
    }

    .accordion-header.open {
      background: rgba(0, 255, 0, 0.1);
      border-bottom: 1px solid rgba(0, 255, 0, 0.2);
    }

    .accordion-title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 12px;
      color: #00ff00;
      font-weight: 600;
    }

    .accordion-count {
      font-size: 10px;
      color: #666;
      background: rgba(0, 255, 0, 0.1);
      padding: 2px 8px;
      border-radius: 10px;
    }

    .accordion-arrow {
      font-size: 10px;
      color: #00ff00;
      transition: transform 0.2s;
    }

    .accordion-header.open .accordion-arrow {
      transform: rotate(180deg);
    }

    .accordion-content {
      display: none;
      padding: 10px;
      background: #050505;
      max-height: 250px;
      overflow-y: auto;
    }

    .accordion-content.open {
      display: block;
    }

    .search-box {
      width: 100%;
      padding: 8px 10px;
      background: #0a0a0a;
      border: 1px solid rgba(0, 255, 0, 0.3);
      border-radius: 6px;
      color: #fff;
      font-family: inherit;
      font-size: 11px;
      margin-bottom: 10px;
    }

    .search-box:focus {
      outline: none;
      border-color: #00ff00;
    }

    .footer {
      padding: 16px;
      text-align: center;
      color: #444;
      font-size: 9px;
      border-top: 1px solid rgba(0, 255, 0, 0.1);
    }

    .empty-state {
      text-align: center;
      padding: 30px;
      color: #666;
      font-size: 11px;
    }

    .copy-toast {
      position: fixed;
      bottom: 20px;
      left: 50%;
      transform: translateX(-50%);
      background: #00ff00;
      color: #000;
      padding: 10px 20px;
      border-radius: 8px;
      font-size: 12px;
      font-weight: 600;
      opacity: 0;
      transition: opacity 0.3s;
      z-index: 1000;
    }

    .copy-toast.show {
      opacity: 1;
    }

    /* Compact split view for mobile */
    .browser-section {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }
  </style>
</head>
<body>

<div class="header">
  <div class="header-content">
    <div class="header-left">
      <img src="/app-logo.png" alt="Net Library" class="logo">
      <div>
        <h1>CODE DOCS</h1>
        <div class="subtitle">Net Library Source</div>
      </div>
    </div>
    <div class="quick-actions hidden" id="quick-actions-container">
      <button class="quick-actions-btn" id="quick-actions-toggle">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
        <span>Actions</span>
        <span style="font-size: 8px;">▼</span>
      </button>
      <div class="quick-actions-menu" id="quick-actions-menu">
        <button class="quick-action-item" id="download-zip-btn">
          <span class="icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></svg></span>
          <span>Download ZIP</span>
        </button>
        <button class="quick-action-item" id="download-json-btn">
          <span class="icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg></span>
          <span>Download JSON</span>
        </button>
        <button class="quick-action-item" id="download-logo-btn">
          <span class="icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg></span>
          <span>Download Logo PNG</span>
        </button>
        <a href="/api/source-files" target="_blank" class="quick-action-item">
          <span class="icon"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg></span>
          <span>View Files API</span>
        </a>
      </div>
    </div>
  </div>
</div>

<!-- COMPACT OVERVIEW + CODE BROWSER -->
<section class="page">
  <!-- Code Viewer (now at top!) -->
  <div class="code-viewer" id="code-viewer" style="margin-bottom: 12px;">
    <div class="code-header">
      <span class="code-title" id="code-title">Code Viewer</span>
      <div class="code-actions">
        <button class="code-btn" id="clear-btn" style="display: none;">✕ Clear</button>
        <button class="code-btn" id="copy-btn" style="display: none;"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:-2px;margin-right:4px"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>Copy</button>
      </div>
    </div>
    <div class="code-content">
      <pre id="code-content"><div class="empty-state"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:-2px;margin-right:4px"><polyline points="6 9 12 15 18 9"/></svg> Tap a file below</div></pre>
    </div>
  </div>

  <!-- Search -->
  <input type="text" class="search-box" id="file-search" placeholder="Search files...">

  <!-- File Categories as Accordions -->
  <div class="browser-section">
    <!-- Hooks Accordion -->
    <div class="accordion">
      <button class="accordion-header" data-category="hooks">
        <span class="accordion-title">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
          <span>Hooks</span>
        </span>
        <div style="display: flex; align-items: center; gap: 8px;">
          <span class="accordion-count" id="hooks-count">0</span>
          <span class="accordion-arrow">▼</span>
        </div>
      </button>
      <div class="accordion-content">
        <div class="file-list" id="hooks-list"></div>
      </div>
    </div>

    <!-- Components Accordion -->
    <div class="accordion">
      <button class="accordion-header" data-category="components">
        <span class="accordion-title">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><rect x="7" y="7" width="3" height="9"/><rect x="14" y="7" width="3" height="5"/></svg>
          <span>Components</span>
        </span>
        <div style="display: flex; align-items: center; gap: 8px;">
          <span class="accordion-count" id="components-count">0</span>
          <span class="accordion-arrow">▼</span>
        </div>
      </button>
      <div class="accordion-content">
        <div class="file-list" id="components-list"></div>
      </div>
    </div>

    <!-- APIs Accordion -->
    <div class="accordion">
      <button class="accordion-header" data-category="api">
        <span class="accordion-title">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18.36 6.64a9 9 0 1 1-12.73 0"/><line x1="12" y1="2" x2="12" y2="12"/></svg>
          <span>API Routes</span>
        </span>
        <div style="display: flex; align-items: center; gap: 8px;">
          <span class="accordion-count" id="apis-count">0</span>
          <span class="accordion-arrow">▼</span>
        </div>
      </button>
      <div class="accordion-content">
        <div class="file-list" id="apis-list"></div>
      </div>
    </div>

    <!-- Share Routes Accordion -->
    <div class="accordion">
      <button class="accordion-header" data-category="share">
        <span class="accordion-title">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/></svg>
          <span>Share Routes</span>
        </span>
        <div style="display: flex; align-items: center; gap: 8px;">
          <span class="accordion-count" id="share-count">0</span>
          <span class="accordion-arrow">▼</span>
        </div>
      </button>
      <div class="accordion-content">
        <div class="file-list" id="share-list"></div>
      </div>
    </div>

    <!-- Embed Widgets Accordion -->
    <div class="accordion">
      <button class="accordion-header" data-category="embed">
        <span class="accordion-title">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
          <span>Embed Widgets</span>
        </span>
        <div style="display: flex; align-items: center; gap: 8px;">
          <span class="accordion-count" id="embed-count">0</span>
          <span class="accordion-arrow">▼</span>
        </div>
      </button>
      <div class="accordion-content">
        <div class="file-list" id="embed-list"></div>
      </div>
    </div>

    <!-- Resources Accordion -->
    <div class="accordion">
      <button class="accordion-header" data-category="resources">
        <span class="accordion-title">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/></svg>
          <span>Resources</span>
        </span>
        <div style="display: flex; align-items: center; gap: 8px;">
          <span class="accordion-count" id="resources-count">0</span>
          <span class="accordion-arrow">▼</span>
        </div>
      </button>
      <div class="accordion-content">
        <div class="file-list" id="resources-list"></div>
      </div>
    </div>

    <!-- Markdown Docs Accordion -->
    <div class="accordion">
      <button class="accordion-header" data-category="markdown">
        <span class="accordion-title">
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><polyline points="10 9 9 9 8 9"/></svg>
          <span>Documentation (MD)</span>
        </span>
        <div style="display: flex; align-items: center; gap: 8px;">
          <span class="accordion-count" id="markdown-count">0</span>
          <span class="accordion-arrow">▼</span>
        </div>
      </button>
      <div class="accordion-content">
        <div class="file-list" id="markdown-list"></div>
      </div>
    </div>
  </div>
</section>

<!-- Info Section -->
<section class="page" style="padding: 12px 16px;">
  <div class="card" style="margin-bottom: 8px;">
    <p style="margin: 0; font-size: 10px; color: #888;">
      <strong style="color: #00ff00;">Tech:</strong> Next.js 15 • React 19 • TypeScript • Wagmi v2 • Drizzle ORM
    </p>
  </div>

  <!-- Recent Updates -->
  <div class="accordion" style="margin-top: 8px;">
    <button class="accordion-header" data-category="recent-updates">
      <span class="accordion-title">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/></svg>
        <span>Recent Code Updates (latest)</span>
      </span>
      <div style="display: flex; align-items: center; gap: 8px;">
        <span class="accordion-arrow">▼</span>
      </div>
    </button>
    <div class="accordion-content">
      <div style="padding: 8px 0;">
        <p style="font-size: 11px; color: #00ff00; margin-bottom: 8px;"><strong>🔒 Server-Side Rate Limiting + Security Hardening (latest)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          All three upload routes now enforce limits server-side:<br>
          • <code>src/lib/upload-rate-limit.ts</code> — shared <code>checkServerUploadLimit()</code> / <code>recordServerUpload()</code><br>
          • Respects warm-up period, Upload Pass, Stack Pass, and team FID bypass<br>
          • <code>/api/upload-check</code> GET + POST both derive <code>isMember</code> from the registry (prevents spoofing)<br>
          • <code>/api/register-cdn-link</code> rate-limit key uses authenticated FID for Bearer requests<br>
          • <code>getUserUploadStats</code> accepts optional <code>prefetchedMembers</code> to eliminate redundant KV reads<br>
          • Client-side <code>recordUpload()</code> calls removed — server is sole write path; client calls <code>refresh()</code>
        </p>

        <p style="font-size: 11px; color: #00ff00; margin-bottom: 8px;"><strong>📱 Social Post Archiving — 10 Platforms (latest)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          Archive posts from Farcaster, X/Twitter, Instagram, Bluesky, YouTube, TikTok, Reddit, Threads, LinkedIn, Mastodon:<br>
          • Paste post URL → fetch metadata → generate styled receipt via Satori → upload to Net Protocol<br>
          • <code>hasAutoPopulatedRef</code> prevents Farcaster cast data re-fetches from overwriting user edits<br>
          • Receipt title uses <code>PLATFORM_INFO[platform]?.name</code> (was hardcoded)<br>
          • <code>fetchThreads</code> / <code>fetchLinkedIn</code> now throw descriptive errors; params renamed <code>_url</code>
        </p>

        <p style="font-size: 11px; color: #00ff00; margin-bottom: 8px;"><strong>🖼 Image Editor — Full-Resolution Export (latest)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          • Export scale multiplier: <code>targetWidth / canvasSize.width</code> with div-by-zero guard<br>
          • Eraser uses canvas background color (transparent for PNG, white for JPEG)<br>
          • Blob URLs tracked in ref and revoked on unmount (memory leak fix)<br>
          • All 4 export paths (download, save, share, receipt) use consistent resolution
        </p>

        <p style="font-size: 11px; color: #00ff00; margin-bottom: 8px;"><strong>🦊 Smart Wallet Capability Detection (latest)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          • <code>useWalletCapabilities</code> — queries EIP-5792 <code>wallet_getCapabilities</code><br>
          • Handles hex <code>"0x2105"</code>, decimal-string <code>"8453"</code>, and numeric <code>8453</code> chain ID key formats<br>
          • <code>skipSendCalls = capabilitiesLoading || !hasAtomicBatch</code> — defaults to skip until confirmed<br>
          • <code>NET_LIBRARY_DATA_SUFFIX</code> attached as <code>dataSuffix</code> on <code>sendCallsAsync</code> for ERC-8021 attribution<br>
          • <code>isCoinbaseWalletUA()</code> in <code>src/lib/ua-utils.ts</code> — centralises UA detection (was in 3 files)<br>
          • <code>Cross-Origin-Opener-Policy: same-origin-allow-popups</code> header added for popup wallet auth
        </p>

        <p style="font-size: 11px; color: #00ff00; margin-bottom: 8px;"><strong>🧑‍💻 UX Fixes (latest)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          • Membership popup guarded by <code>!isMembershipLoading</code> — no flicker for existing members<br>
          • Server dismiss state re-fetched when wallet/FID identity changes (<code>lastFetchedIdentity</code> ref)<br>
          • API key CLI card in Achievements shows copy buttons for install + <code>config set apiKey</code><br>
          • <code>uploadsRemaining: 99999</code> for team members (was <code>Infinity</code> → serialised as <code>null</code>)<br>
          • Text editor uploads preserve HTML formatting when styled content detected (<code>.html</code> instead of <code>.txt</code>)<br>
          • Server-side preference persistence via <code>/api/prefs</code> (KV fallback for webviews)
        </p>

        <p style="font-size: 11px; color: #22c55e; margin-bottom: 8px;"><strong>🗂 Filesystem Stack Support — v1 API (v2.6.0)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          <code>PUT /api/v1/stacks/write</code> now supports <code>action: "add-fs-item"</code> for filesystem stacks:<br>
          • Fields: <code>contentKey</code>, <code>path</code> (required, must start with /), <code>fileName</code>, <code>fileSize</code>, <code>mimeType</code><br>
          • Stack must have <code>isFileSystem: true</code> — returns 400 otherwise<br>
          • Automatically updates <code>fileCount</code> and <code>totalSize</code> on the stack record<br>
          • <code>GET /api/v1/stacks/{stackId}</code> now returns filesystem metadata on both stack object and each item<br>
          • Filesystem stacks bypass discovery-index visibility filter (files don't have discovery entries)
        </p>

        <p style="font-size: 11px; color: #22c55e; margin-bottom: 8px;"><strong>🔑 PUT /api/v1/agents/me — Self-Service Profile Updates (v2.6.0)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          Agents can now update their own profile without admin access:<br>
          • Fields: <code>name</code>, <code>description</code>, <code>pfpUrl</code>, <code>webhookUrl</code>, <code>erc8004TokenId</code><br>
          • Setting <code>erc8004TokenId</code> triggers on-chain ERC-8004 re-verification and updates both agent record and member registry
        </p>

        <p style="font-size: 11px; color: #22c55e; margin-bottom: 8px;"><strong>🔶 ERC-8004 Token ID Fix — Embed Card (v2.6.0)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          <code>GET /api/v1/embeds/card/[address]</code> now correctly returns <code>erc8004TokenId</code>:<br>
          • Token ID sourced from agent record (primary) with member registry as fallback<br>
          • Both <code>erc8004Verified</code> and <code>erc8004TokenId</code> always present for agent members<br>
          • <code>RegisteredAgent</code> type updated with <code>erc8004TokenId</code>, <code>erc8004Verified</code>, <code>erc8004CheckedAt</code> fields
        </p>

        <p style="font-size: 11px; color: #F97316; margin-bottom: 8px;"><strong>🔶 ERC-8004 Verified Agent Integration (v2.5.0)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          Agents on the ERC-8004 Base Identity Registry get verified badge:<br>
          • <code>POST /api/v1/agents/verify-8004</code> - Re-verify ERC-8004 status<br>
          • <code>PUT /api/v1/agents</code> or <code>PUT /api/v1/agents/me</code> - Set <code>erc8004TokenId</code> to trigger verification<br>
          • <strong>Visual:</strong> Orange (#F97316) ring around PFP, BadgeCheck icon next to AGENT badge<br>
          • <strong>Verification:</strong> Calls <code>ownerOf(tokenId)</code> or <code>balanceOf(address)</code> on registry<br>
          • <strong>Caching:</strong> 1-hour cache, auto re-verify on embed widget load<br>
          • Registry: <code>0x8004A169FB4a3325136EB29fA0ceB6D2e539a432</code> on Base
        </p>

        <p style="font-size: 11px; color: #a855f7; margin-bottom: 8px;"><strong>🤖 Agent API v2.0 Embed Data Routes (v1.43.0)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          New public JSON endpoints for embed widget data:<br>
          • <code>/api/v1/embeds/card/[address]</code> - Library card data (member info, stats, rank, PFP)<br>
          • <code>/api/v1/embeds/grid/[gridId]</code> - Grid metadata and cells with cover URLs<br>
          • <code>/api/v1/embeds/user/[address]</code> - User profile with paginated uploads<br>
          • CORS-enabled for cross-origin requests, no authentication required<br>
          • Agent detection: <code>isAgent</code>, <code>agentId</code> fields included when applicable
        </p>

        <p style="font-size: 11px; color: #a855f7; margin-bottom: 8px;"><strong>🔐 Agent API Enhancements (v1.43.0)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          • <code>/api/v1/agents/me</code> - Full agent profile with widget embed URLs<br>
          • <code>/api/v1/agents/membership</code> - Library Card purchase (paid + admin grant)<br>
          • <code>/api/v1/agents/tasks</code> - Task queue for @mention workflows<br>
          • <code>/api/v1/webhooks/farcaster</code> - Neynar webhook receiver<br>
          • P1-P5 fixes: Race conditions, 20-item limits, bootstrap security, rate limiting
        </p>

        <p style="font-size: 11px; color: #00ff00; margin-bottom: 8px;"><strong>🎨 Emoji Font Support (v1.42.6)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          Proper emoji rendering in Satori/ImageResponse:<br>
          • New shared utility: <code>src/lib/emoji-font.ts</code><br>
          • On-demand fetch of Noto Color Emoji from CDN (~1.5MB)<br>
          • First request ~100-200ms, subsequent requests use cached font<br>
          • Fallback to Twemoji if primary fails<br>
          • Applied to social receipt rendering - emojis in usernames now display correctly
        </p>

        <p style="font-size: 11px; color: #00ff00; margin-bottom: 8px;"><strong>📜 Receipt Layout Improvements (v1.42.6)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          Better social receipt readability:<br>
          • Trailing t.co URLs automatically stripped from tweet text<br>
          • Timestamp opacity increased (0.5 → 0.8)<br>
          • Footer URL opacity increased (0.35 → 0.7)
        </p>

        <p style="font-size: 11px; color: #ff6b6b; margin-bottom: 8px;"><strong>⚠️ XML Chunk Retrieval Fix (v1.42.5)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          Fixed social receipt archives not displaying. For relay uploads:<br>
          • XML metadata embeds user's wallet in <code>o</code> attribute<br>
          • But relay's backend wallet actually writes the chunks<br>
          • <code>/api/book-file</code> now uses passed <code>operatorAddress</code> parameter<br>
          • Root cause: SDK generates XML before knowing backend wallet
        </p>

        <p style="font-size: 11px; color: #ff6b6b; margin-bottom: 8px;"><strong>⚠️ Satori Image Fix (v1.42.4)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          Satori silently drops images without explicit dimensions. Fixed in receipt route:<br>
          • Container: <code>height: 150, width: "100%"</code> (not maxHeight)<br>
          • Image element: <code>width={736} height={150}</code> attributes required<br>
          • Result: Receipt size increased from ~27KB to ~196KB with embedded images
        </p>

        <p style="font-size: 11px; color: #00ff00; margin-bottom: 8px;"><strong>Media Archiving System</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          <code>src/app/api/social/receipt/route.tsx</code><br><br>
          • <strong>fetchImageAsDataUrl(url)</strong>: Downloads an image and converts to base64 data URL for embedding<br>
          • <strong>archiveMedia(content)</strong>: Fetches avatar, images (up to 4), and video thumbnail in parallel with 8s timeout per fetch<br>
          • <strong>ArchivedMedia interface</strong>: { avatarDataUrl, imageDataUrls[], thumbnailDataUrl }<br>
          • <strong>arrayBufferToBase64()</strong>: Edge-compatible base64 encoding using btoa instead of Buffer
        </p>

        <p style="font-size: 11px; color: #00ff00; margin-bottom: 8px;"><strong>Twitter Image Extraction</strong></p>
        <p style="font-size: 10px; color: #aaa;">
          <code>src/app/api/social/fetch/route.ts</code><br><br>
          • <strong>extractTwitterImages(data)</strong>: Comprehensive helper that checks all 5 possible image locations in Twitter syndication API responses (data.photos, mediaDetails, entities.media, extended_entities.media, card.binding_values)
        </p>
      </div>
    </div>
  </div>

  <!-- Architecture Notes (v1.42.0) -->
  <div class="accordion" style="margin-top: 8px;">
    <button class="accordion-header" data-category="arch-notes">
      <span class="accordion-title">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>
        <span>Architecture Notes (v1.42.0)</span>
      </span>
      <div style="display: flex; align-items: center; gap: 8px;">
        <span class="accordion-arrow">▼</span>
      </div>
    </button>
    <div class="accordion-content">
      <div style="padding: 8px 0;">
        <p style="font-size: 11px; color: #00ff00; margin-bottom: 8px;"><strong>Storage Architecture</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          Net Protocol storage types:<br>
          • <strong>regular</strong>: Files &lt;20KB, single transaction<br>
          • <strong>chunked</strong>: Files 20-80KB, multi-chunk storage<br>
          • <strong>xml</strong>: Files &gt;80KB, XML manifest + chunks
        </p>

        <p style="font-size: 11px; color: #a855f7; margin-bottom: 8px;"><strong>CDN URL Fix (v1.42.0)</strong></p>
        <p style="font-size: 10px; color: #aaa; margin-bottom: 10px;">
          Net Protocol's <code>/chunked-storage/file/</code> endpoint returns 404.<br>
          Solution: Route through <code>/api/book-file</code> which uses <code>/storage/raw/</code> endpoint.<br>
          Applied in: <code>mini-app.tsx</code>, <code>book-card.tsx</code>, <code>book-detail.tsx</code>
        </p>

        <p style="font-size: 11px; color: #a855f7; margin-bottom: 8px;"><strong>Dual Storage for Archives</strong></p>
        <p style="font-size: 10px; color: #aaa;">
          Social receipts & grid archives use dual storage:<br>
          • <strong>KV (coverUrl)</strong>: Fast thumbnail/card display via <code>/api/upload-cover</code><br>
          • <strong>Onchain (contentKey)</strong>: Permanent storage via Net Protocol<br>
          Flow: Generate → Upload to KV → Upload onchain → Register both URLs
        </p>
      </div>
    </div>
  </div>
</section>

<footer class="footer">
  <p>Net Library Code Docs • Built on Net Protocol</p>
</footer>

<div class="copy-toast" id="copy-toast">Copied to clipboard!</div>

<script>
// State
let allFiles = [];
let currentFile = null;
let isMember = false;

// Listen for membership status from parent frame
window.addEventListener('message', (event) => {
  if (event.data && event.data.type === 'membershipStatus') {
    isMember = event.data.isMember;
    // Show quick actions only for admins (APP_CREATOR_FIDS, computed in parent)
    const quickActionsContainer = document.getElementById('quick-actions-container');
    if (quickActionsContainer) {
      if (event.data.isAdmin) {
        quickActionsContainer.classList.remove('hidden');
      } else {
        quickActionsContainer.classList.add('hidden');
      }
    }
  }
});

// Initialize
document.addEventListener('DOMContentLoaded', async () => {
  await loadFiles();
  setupEventListeners();
});

// Load files from API
async function loadFiles() {
  try {
    const response = await fetch('/api/source-files');
    const data = await response.json();

    if (data.success) {
      allFiles = data.files;
      updateStats(data);
      populateAccordions(data.byCategory);
    }
  } catch (err) {
    console.error('Failed to load files:', err);
  }
}

// Update accordion counts
function updateStats(data) {
  document.getElementById('hooks-count').textContent = data.byCategory?.hooks?.length || 0;
  document.getElementById('components-count').textContent = data.byCategory?.components?.length || 0;
  document.getElementById('apis-count').textContent = data.byCategory?.api?.length || 0;
  document.getElementById('share-count').textContent = data.byCategory?.share?.length || 0;
  document.getElementById('embed-count').textContent = data.byCategory?.embed?.length || 0;
  document.getElementById('resources-count').textContent = data.byCategory?.resources?.length || 0;
  document.getElementById('markdown-count').textContent = data.byCategory?.markdown?.length || 0;
}

// Populate accordions with files
function populateAccordions(byCategory) {
  const sections = {
    'hooks-list': byCategory?.hooks || [],
    'components-list': byCategory?.components || [],
    'apis-list': byCategory?.api || [],
    'share-list': byCategory?.share || [],
    'embed-list': byCategory?.embed || [],
    'resources-list': byCategory?.resources || [],
    'markdown-list': byCategory?.markdown || [],
  };

  for (const [containerId, files] of Object.entries(sections)) {
    const container = document.getElementById(containerId);
    if (!container) continue;

    if (files.length === 0) {
      container.innerHTML = '<div class="empty-state">No files</div>';
      continue;
    }

    container.innerHTML = files.map(f => `
      <div class="file-item" data-path="${f.path}">
        <div>
          <div class="file-name">${f.name}</div>
          <div class="file-path">${f.path}</div>
        </div>
      </div>
    `).join('');

    container.querySelectorAll('.file-item').forEach(item => {
      item.addEventListener('click', () => {
        loadFileContent(item.dataset.path);
        // Scroll to code viewer
        document.getElementById('code-viewer').scrollIntoView({ behavior: 'smooth', block: 'start' });
      });
    });
  }
}

// Filter files based on search
function filterFiles(searchTerm) {
  const term = searchTerm.toLowerCase();

  document.querySelectorAll('.accordion').forEach(accordion => {
    const fileList = accordion.querySelector('.file-list');
    const fileItems = fileList.querySelectorAll('.file-item');
    let visibleCount = 0;

    fileItems.forEach(item => {
      const name = item.querySelector('.file-name').textContent.toLowerCase();
      const path = item.querySelector('.file-path').textContent.toLowerCase();
      const matches = !term || name.includes(term) || path.includes(term);

      item.style.display = matches ? 'flex' : 'none';
      if (matches) visibleCount++;
    });

    // Open accordions with matches when searching
    if (term && visibleCount > 0) {
      accordion.querySelector('.accordion-header').classList.add('open');
      accordion.querySelector('.accordion-content').classList.add('open');
    }
  });
}

// Load file content
async function loadFileContent(filePath) {
  currentFile = filePath;

  // Highlight active file
  document.querySelectorAll('.file-item').forEach(item => {
    item.classList.toggle('active', item.dataset.path === filePath);
  });

  document.getElementById('code-title').textContent = filePath.split('/').pop();
  document.getElementById('code-content').innerHTML = '<div class="loading">Loading...</div>';
  document.getElementById('copy-btn').style.display = 'none';

  try {
    const response = await fetch(`/api/source-files?file=${encodeURIComponent(filePath)}`);
    const data = await response.json();

    if (data.success) {
      const lines = data.file.content.split('\n');
      const numbered = lines.map((line, i) => {
        const lineNum = `<span class="line-numbers">${i + 1}</span>`;
        const escapedLine = escapeHtml(line);
        return lineNum + escapedLine;
      }).join('\n');

      document.getElementById('code-content').innerHTML = `<pre>${numbered}</pre>`;
      document.getElementById('copy-btn').style.display = 'block';
      document.getElementById('clear-btn').style.display = 'block';
    } else {
      document.getElementById('code-content').innerHTML = '<div class="empty-state">Failed to load file</div>';
    }
  } catch (err) {
    console.error('Failed to load file:', err);
    document.getElementById('code-content').innerHTML = '<div class="empty-state">Error loading file</div>';
  }
}

// Escape HTML
function escapeHtml(text) {
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

// Download file helper
// Always opens in external browser - downloads are meant to be used outside the mini-app
// Mobile users can long-press to save to photos or use share sheet
async function downloadFile(url, _filename) {
  const fullUrl = window.location.origin + url;

  showToast('Opening in browser...');

  // We're in an iframe within the React app (same origin)
  // Call the global function that the parent app exposes
  try {
    if (window.parent && window.parent.__netLibraryOpenExternal) {
      await window.parent.__netLibraryOpenExternal(fullUrl);
      return;
    }
  } catch (err) {
    console.log('Parent function not available:', err);
  }

  // Fallback: open directly
  openInBrowser(fullUrl);
}

// Fallback function to open URL in browser
function openInBrowser(url) {
  // On iOS, create a link element for better handling
  if (/iPhone|iPad|iPod/.test(navigator.userAgent)) {
    const link = document.createElement('a');
    link.href = url;
    link.target = '_blank';
    link.rel = 'noopener noreferrer';
    document.body.appendChild(link);
    link.click();
    setTimeout(() => document.body.removeChild(link), 100);
  } else {
    window.open(url, '_blank', 'noopener,noreferrer');
  }
}

// Setup event listeners
function setupEventListeners() {
  // Quick actions dropdown toggle
  const quickActionsToggle = document.getElementById('quick-actions-toggle');
  const quickActionsMenu = document.getElementById('quick-actions-menu');

  quickActionsToggle.addEventListener('click', (e) => {
    e.stopPropagation();
    quickActionsMenu.classList.toggle('open');
  });

  // Close menu when clicking outside
  document.addEventListener('click', () => {
    quickActionsMenu.classList.remove('open');
  });

  // Download ZIP button
  document.getElementById('download-zip-btn').addEventListener('click', () => {
    downloadFile('/api/source-files/download', `net-library-source-${Date.now()}.zip`);
    quickActionsMenu.classList.remove('open');
  });

  // Download JSON button
  document.getElementById('download-json-btn').addEventListener('click', () => {
    downloadFile('/api/source-files/download-json', `net-library-files-${Date.now()}.json`);
    quickActionsMenu.classList.remove('open');
  });

  // Download Logo PNG button
  document.getElementById('download-logo-btn').addEventListener('click', () => {
    downloadFile('/app-logo.png', 'net-library-logo.png');
    quickActionsMenu.classList.remove('open');
  });

  // Accordion toggles
  document.querySelectorAll('.accordion-header').forEach(header => {
    header.addEventListener('click', () => {
      header.classList.toggle('open');
      header.nextElementSibling.classList.toggle('open');
    });
  });

  // Search
  document.getElementById('file-search').addEventListener('input', (e) => {
    filterFiles(e.target.value);
  });

  // Copy button
  document.getElementById('copy-btn').addEventListener('click', async () => {
    if (!currentFile) return;

    try {
      const response = await fetch(`/api/source-files?file=${encodeURIComponent(currentFile)}`);
      const data = await response.json();
      if (data.success) {
        await navigator.clipboard.writeText(data.file.content);
        showToast('Copied!');
      }
    } catch (err) {
      console.error('Failed to copy:', err);
    }
  });

  // Clear button
  document.getElementById('clear-btn').addEventListener('click', () => {
    clearCodeViewer();
  });
}

// Clear the code viewer
function clearCodeViewer() {
  currentFile = null;
  document.getElementById('code-title').textContent = 'Code Viewer';
  document.getElementById('code-content').innerHTML = '<div class="empty-state"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline;vertical-align:-2px;margin-right:4px"><polyline points="6 9 12 15 18 9"/></svg> Tap a file below</div>';
  document.getElementById('copy-btn').style.display = 'none';
  document.getElementById('clear-btn').style.display = 'none';

  // Remove active state from all file items
  document.querySelectorAll('.file-item').forEach(item => {
    item.classList.remove('active');
  });
}

// Show toast
function showToast(message = 'Copied to clipboard!') {
  const toast = document.getElementById('copy-toast');
  toast.textContent = message;
  toast.classList.add('show');
  setTimeout(() => toast.classList.remove('show'), 2000);
}
</script>

</body>
</html>