text: import "./App.css";
  import { useEffect, useState } from "react";
  import idl from "./idl.json";
  import { Connection, PublicKey, clusterApiUrl } from "@solana/web3.js";
  import { Program, Provider, web3 } from "@project-serum/anchor";
  import kp from "./keypair.json";
  
  // SystemProgram is a reference to the Solana runtime!
  const { SystemProgram, Keypair } = web3;
  
  // Create a keypair for the account that will hold the GIF data.
  const arr = Object.values(kp._keypair.secretKey);
  const secret = new Uint8Array(arr);
  const baseAccount = web3.Keypair.fromSecretKey(secret);
  
  // Get our program's id form the IDL file.
  const programID = new PublicKey(idl.metadata.address);
  
  // Set our network to devent.
  const network = clusterApiUrl("devnet");
  
  // Control's how we want to acknowledge when a trasnaction is "done".
  const opts = {
    preflightCommitment: "processed",
  };
  
  const TEST_GIFS = [
    "https://media1.giphy.com/media/12X0cBwYo7JW8w/giphy.gif?cid=ecf05e4735egmo5rd73hj85drrfc9t6oke4ubmsw8dw5h7zm&rid=giphy.gif&ct=g",
    "https://media0.giphy.com/media/26uf1EUQzKKGcIhJS/giphy.gif?cid=ecf05e47y7vw8k1nzf4bjoseohpxl0fuqrc0s1qdwdin7348&rid=giphy.gif&ct=g",
    "https://media3.giphy.com/media/uqSU9IEYEKAbS/giphy.gif?cid=ecf05e47tqlq5uxhgzg08lqlrc8ht8rw153jj619csol64ob&rid=giphy.gif&ct=g",
    "https://media1.giphy.com/media/10lvYncs50d3B6/giphy.gif?cid=ecf05e47l9p9lj1lpnh7mdgsmydzz0sjal87lrexu09voago&rid=giphy.gif&ct=g",
  ];
  
  const App = () => {
    const [walletAddress, setWalletAddress] = useState(null);
    const [gifList, setGifList] = useState([]);
    const [inputValue, setInputValue] = useState("");
  
    const checkIfWalletIsConnected = async () => {
      try {
        const { solana } = window;
  
        if (solana) {
          if (solana.isPhantom) {
            console.log("Phantom wallet found!");
  
            const response = await solana.connect({ onlyIfTrusted: true });
            console.log(
              "Connected with Public Key:",
              response.publicKey.toString()
            );
  
            setWalletAddress(response.publicKey.toString());
          }
        } else {
          alert("Solana object not found! Get a Phantom Wallet 👻");
        }
      } catch (error) {
        console.error(error);
      }
    };
  
    const connectWallet = async () => {
      const { solana } = window;
  
      if (solana) {
        const response = await solana.connect();
        console.log("Connected with Public Key:", response.publicKey.toString());
        setWalletAddress(response.publicKey.toString());
      }
    };
  
    const sendGif = async () => {
      if (inputValue.length === 0) {
        console.log("No gif link given!");
        return;
      }
      console.log("Gif link:", inputValue);
      try {
        const provider = getProvider();
        const program = new Program(idl, programID, provider);
  
        await program.rpc.addGif(inputValue, {
          accounts: {
            baseAccount: baseAccount.publicKey,
            user: provider.wallet.publicKey,
          },
        });
        console.log("GIF sucesfully sent to program", inputValue);
  
        await getGifList();
      } catch (error) {
        console.log("Error sending GIF:", error);
      }
    };
  
    const onInputChange = (event) => {
      const { value } = event.target;
      setInputValue(value);
    };
  
    const getProvider = () => {
      const connection = new Connection(network, opts.preflightCommitment);
      const provider = new Provider(
        connection,
        window.solana,
        opts.preflightCommitment
      );
      return provider;
    };
  
    const createGifAccount = async () => {
      try {
        const provider = getProvider();
        const program = new Program(idl, programID, provider);
        console.log("ping");
        await program.rpc.startStuffOff({
          accounts: {
            baseAccount: baseAccount.publicKey,
            user: provider.wallet.publicKey,
            systemProgram: SystemProgram.programId,
          },
          signers: [baseAccount],
        });
        console.log(
          "Created a new BaseAccount w/ address:",
          baseAccount.publicKey.toString()
        );
        await getGifList();
      } catch (error) {
        console.log("Error creating BaseAccount account:", error);
      }
    };
    /*
     * We want to render this UI when the user hasn't connected
     * their wallet to our app yet.
     */
    const renderNotConnectedContainer = () => (
      <button
        className="cta-button connect-wallet-button"
        onClick={connectWallet}
      >
        Connect to Wallet
      </button>
    );
  
    const renderConnectedContainer = () => {
      // If we hit this, it means the program account hasn't be initialized.
      if (gifList === null) {
        return (
          <div className="connected-container">
            <button
              className="cta-button submit-gif-button"
              onClick={createGifAccount}
            >
              Do One-Time Initialization For GIF Program Account
            </button>
          </div>
        );
      }
      // Otherwise, we're good! Account exists. User can submit GIFs.
      else {
        return (
          <div className="connected-container">
            <form
              onSubmit={(event) => {
                event.preventDefault();
                sendGif();
              }}
            >
              <input
                type="text"
                placeholder="Enter gif link!"
                value={inputValue}
                onChange={onInputChange}
              />
              <button type="submit" className="cta-button submit-gif-button">
                Submit
              </button>
            </form>
            <div className="gif-grid">
              {/* We use index as the key instead, also, the src is now item.gifLink */}
              {gifList.map((item, index) => (
                <div className="gif-item" key={index}>
                  <img src={item.gifLink} />
                </div>
              ))}
            </div>
          </div>
        );
      }
    };
    /*
     * When our component first mounts, let's check to see if we have a connected
     * Phantom Wallet
     */
    useEffect(() => {
      const onLoad = async () => {
        await checkIfWalletIsConnected();
      };
      window.addEventListener("load", onLoad);
      return () => window.removeEventListener("load", onLoad);
    }, []);
  
    useEffect(() => {
      const onLoad = async () => {
        await checkIfWalletIsConnected();
      };
      window.addEventListener("load", onLoad);
      return () => window.removeEventListener("load", onLoad);
    }, []);
  
    const getGifList = async () => {
      try {
        const provider = getProvider();
        const program = new Program(idl, programID, provider);
        const account = await program.account.baseAccount.fetch(
          baseAccount.publicKey
        );
  
        console.log("Got the account", account);
        setGifList(account.gifList);
      } catch (error) {
        console.log("Error in getGifs: ", error);
        setGifList(null);
      }
    };
  
    useEffect(() => {
      if (walletAddress) {
        console.log("Fetching GIF list...");
        getGifList();
      }
    }, [walletAddress]);
  
    return (
      <div className="App">
        <div className={walletAddress ? "authed-container" : "container"}>
          <div className="header-container">
            <p className="header">🖼️ GIF Share</p>
            <p className="sub-text">
              View your Stewie GIF collection in the metaverse ✨
            </p>
  
            {!walletAddress && renderNotConnectedContainer()}
            {walletAddress && renderConnectedContainer()}
          </div>
        </div>
      </div>
    );
  };
  
  export default App;
  