const { useState, useEffect, useMemo } = React;

// Simple Router Hook
function useRouter() {
  const [path, setPath] = useState(window.location.pathname);
  
  useEffect(() => {
    const onPopState = () => setPath(window.location.pathname);
    window.addEventListener('popstate', onPopState);
    return () => window.removeEventListener('popstate', onPopState);
  }, []);

  const navigate = (to) => {
    window.history.pushState({}, '', to);
    setPath(to);
    window.scrollTo(0, 0);
  };

  return { path, navigate };
}

// Custom Link Component
function NavLink({ to, children, className, style, ...props }) {
  const { path, navigate } = useRouter();
  
  const scrollToId = (id) => {
    const el = document.getElementById(id);
    if (el) {
      const headerOffset = 72;
      const elementPosition = el.getBoundingClientRect().top;
      const offsetPosition = elementPosition + window.pageYOffset - headerOffset;

      window.scrollTo({
        top: offsetPosition,
        behavior: "smooth"
      });
    }
  };

  const handleClick = (e) => {
    if (to.startsWith('/#')) {
      const id = to.substring(2);
      if (path !== '/') {
        e.preventDefault();
        navigate('/');
        // Wait for landing page to render before scrolling
        setTimeout(() => scrollToId(id), 150);
        return;
      }
      // Same page anchor
      e.preventDefault();
      scrollToId(id);
      return;
    }
    e.preventDefault();
    navigate(to);
  };
  return <a href={to} onClick={handleClick} className={className} style={style} {...props}>{children}</a>;
}

const PRICE = 0.00019;
const SUPPLY = 4250;
const MAX_PER = 10;
const START_MINTED = 3600;

function getPfpUrl(id) {
  // Use a high-performance IPFS gateway for the 4,250 gems
  const IPFS_GATEWAY = "https://ipfs.io/ipfs/Qmf8RGk84HwnxwAvQtcqPChp5GTA5Sk33mx5wohYsVDJjz";
  // The IPFS folder is 0-indexed, so we subtract 1 from the ID
  return `${IPFS_GATEWAY}/${id - 1}.png`;
}

function SectionHead({ eyebrow, title, note }) {
  return (
    <div style={{ marginBottom: 40 }}>
      <div className="eyebrow" style={{ marginBottom: 12 }}>{eyebrow}</div>
      <h2 className="head" style={{ fontSize: "clamp(32px, 4vw, 48px)", fontWeight: 900, margin: 0 }}>{title}</h2>
      {note && <p className="mono" style={{ color: "var(--ink-soft)", fontSize: 13, marginTop: 10 }}>{note}</p>}
    </div>
  );
}

function Header({ account, connectWallet, isOwner, withdraw }) {
  const { path } = useRouter();
  const links = [
    ["HOW", "/#how", false], 
    ["MINT", "/mint", false], 
    ["GALLERY", "/#gallery", false], 
    ["WHITELIST", "/whitelist", true],
    ["FAQ", "/#faq", false]
  ];
  const shortAddr = (a) => a.slice(0, 6) + "..." + a.slice(-4);

  return (
    <header style={{ 
      position: "sticky", top: 0, zIndex: 100, 
      background: "rgba(10,10,11,0.75)", 
      backdropFilter: "blur(16px)", WebkitBackdropFilter: "blur(16px)", 
      color: "var(--ink)", borderBottom: "1px solid var(--line)" 
    }}>
      <div style={{ maxWidth: 1400, margin: "0 auto", padding: "0 40px", display: "flex", alignItems: "center", justifyContent: "space-between", height: 72 }}>
        <NavLink to="/" style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <div style={{ width: 40, height: 40, overflow: "hidden", borderRadius: "8px", border: "1px solid var(--line-2)", background: "var(--paper-3)" }}>
            <img src={getPfpUrl(10)} alt="GEMSO Logo" style={{ width: "100%", height: "100%", objectFit: "cover", imageRendering: "pixelated" }} />
          </div>
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            <span className="mono" style={{ fontWeight: 900, fontSize: 18, letterSpacing: "-0.02em", color: "var(--ink)", lineHeight: 1 }}>GEMSO</span>
            <span className="mono" style={{ fontSize: 9, fontWeight: 700, letterSpacing: "0.1em", color: "var(--emerald)", textTransform: "uppercase" }}>Pixel_Atelier</span>
          </div>
        </NavLink>
        <nav style={{ display: "flex", gap: 36, alignItems: "center" }} className="nav-desktop">
          {links.map(([l, h, soon]) => {
            if (soon) {
              return (
                <div key={l} className="mono" style={{ 
                  fontSize: 10, fontWeight: 700, letterSpacing: ".08em", 
                  color: "var(--ink-faint)", 
                  cursor: "not-allowed",
                  display: "flex",
                  flexDirection: "column",
                  alignItems: "center",
                  gap: 2
                }}>
                  <span>{l}</span>
                  <span style={{ fontSize: 7, color: "var(--ink-faint)", opacity: 0.6 }}>SOON</span>
                </div>
              );
            }

            const isAnchor = h.startsWith("/#");
            
            if (isAnchor) {
              return (
                <NavLink key={l} to={h} className="mono" style={{ 
                  fontSize: 12, fontWeight: 700, letterSpacing: ".08em", 
                  color: "var(--ink-soft)", 
                  transition: "all .2s ease" 
                }}
                onMouseEnter={e => { e.currentTarget.style.color = "var(--emerald)"; e.currentTarget.style.transform = "translateY(-1px)"; }}
                onMouseLeave={e => { e.currentTarget.style.color = "var(--ink-soft)"; e.currentTarget.style.transform = "translateY(0)"; }}>{l}</NavLink>
              );
            }

            return (
              <NavLink key={l} to={h} className="mono" style={{ 
                fontSize: 12, fontWeight: 700, letterSpacing: ".08em", 
                color: path === h ? "var(--emerald)" : "var(--ink-soft)", 
                transition: "all .2s ease" 
              }}
              onMouseEnter={e => { e.currentTarget.style.color = "var(--emerald)"; e.currentTarget.style.transform = "translateY(-1px)"; }}
              onMouseLeave={e => { e.currentTarget.style.color = path === h ? "var(--emerald)" : "var(--ink-soft)"; e.currentTarget.style.transform = "translateY(0)"; }}>{l}</NavLink>
            );
          })}
          <div style={{ width: 1, height: 16, background: "var(--line)" }}></div>
          <div style={{ display: "flex", gap: 12 }}>
            {isOwner && (
              <button className="btn btn-sm" style={{ borderColor: "var(--emerald)", color: "var(--emerald)" }} onClick={withdraw}>
                Withdraw
              </button>
            )}
            <button className="btn btn-sm btn-primary" style={{ borderRadius: "4px" }} onClick={connectWallet}>
              {account ? shortAddr(account) : "Connect"}
            </button>
          </div>
        </nav>
      </div>
      <style>{`@media (max-width: 820px){ .nav-desktop{ display:none !important; } }`}</style>
    </header>
  );
}

function Hero({ minted, onMinted, account, connectWallet }) {
  return (
    <section id="top" style={{ paddingTop: 40, paddingBottom: 28 }}>
      <div className="wrap" style={{ display: "grid", gridTemplateColumns: "0.92fr 1.08fr", gap: 40, alignItems: "stretch" }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", minHeight: 540, overflow: "hidden" }}>
          <img src={getPfpUrl(950)} alt="GEMSO #950" style={{ width: "100%", height: "100%", objectFit: "contain", imageRendering: "pixelated" }} />
        </div>

        <div style={{ display: "flex", flexDirection: "column", justifyContent: "center" }}>
          <div className="eyebrow" style={{ marginBottom: 16 }}>PIXEL GEM-PEOPLE / GENESIS DROP</div>
          <h1 className="head" style={{ fontWeight: 900, lineHeight: 0.92, letterSpacing: "-0.02em", margin: 0 }}>
            <span style={{ display: "block", fontSize: "clamp(54px, 7vw, 104px)", color: "var(--ink)" }}>GEMSO</span>
            <span style={{ display: "block", fontSize: "clamp(48px, 6vw, 92px)", color: "var(--emerald)" }}>($GEMSO)</span>
          </h1>
          <p className="mono" style={{ color: "var(--ink-soft)", fontSize: 15, lineHeight: 1.7, maxWidth: 540, marginTop: 22 }}>
            A collection of 4,250 pixel gem-people on Ethereum. Connect any EVM wallet, pick your slots, and{" "}
            <span style={{ background: "var(--emerald-soft)", color: "var(--emerald)", padding: "1px 6px", fontWeight: 600 }}>mint up to 10 gems</span>{" "}
            in a single transaction. Every specimen is sealed at mint.
          </p>

          <div style={{ marginTop: 28 }}>
            <MintModule minted={minted} onMinted={onMinted} account={account} connectWallet={connectWallet} />
          </div>

          <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginTop: 26 }}>
            {["ERC-721", "PIXEL ART", "4,250 SUPPLY", "FAIR MINT"].map(t => (
              <span key={t} className="tag">{t}</span>
            ))}
          </div>
        </div>
      </div>
      <style>{`@media (max-width: 900px){ #top .wrap{ grid-template-columns: 1fr !important; } #top .card{ min-height: 380px !important; } }`}</style>
    </section>
  );
}

const CONTRACT_ADDRESS = "0x6e6A074C66BeD9de2D4F6Ad8a05e0fFD41cBB5dc";
const ABI = [
  "function mint(uint256 quantity) external payable",
  "function totalSupply() public view returns (uint256)",
  "function MAX_SUPPLY() public view returns (uint256)",
  "function paused() public view returns (bool)",
  "function owner() public view returns (address)",
  "function withdraw() external"
];

function MintModule({ minted, onMinted, account, connectWallet }) {
  const [qty, setQty] = useState(1);
  const [status, setStatus] = useState("idle"); 
  const [errorMsg, setErrorMsg] = useState("");
  const total = (qty * PRICE).toFixed(5);
  const soldOut = minted >= SUPPLY;
  const percentage = useMemo(() => {
    return ((minted / SUPPLY) * 100).toFixed(2);
  }, [minted]);

  const mint = async () => {
    if (!account) return connectWallet();
    setStatus("minting");
    setErrorMsg("");
    try {
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      
      // Check network
      const network = await provider.getNetwork();
      if (network.chainId !== 1) {
        throw new Error("Please switch to Ethereum Mainnet");
      }

      const signer = provider.getSigner();
      const contract = new ethers.Contract(CONTRACT_ADDRESS, ABI, signer);
      
      const tx = await contract.mint(qty, { 
        value: ethers.utils.parseEther(total) 
      });
      
      await tx.wait();
      
      onMinted(qty);
      setStatus("success");
      setTimeout(() => setStatus("idle"), 5000);
    } catch (err) {
      console.error(err);
      setStatus("error");
      setErrorMsg(err.reason || err.message || "Mint failed");
      setTimeout(() => setStatus("idle"), 5000);
    }
  };

  return (
    <div className="card" style={{ padding: 24, background: "var(--paper-2)" }}>
      {/* Mint Progress Bar */}
      <div style={{ marginBottom: 24 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
          <span className="mono" style={{ fontSize: 10, fontWeight: 700, letterSpacing: "0.1em", color: "var(--ink-soft)" }}>MINT PROGRESS</span>
          <span className="mono" style={{ fontSize: 10, fontWeight: 700, color: "var(--ink)" }}>{minted.toLocaleString()} / {SUPPLY.toLocaleString()} ({percentage}%)</span>
        </div>
        <div style={{ height: 8, background: "var(--paper-3)", borderRadius: "4px", overflow: "hidden", border: "1px solid var(--line)" }}>
          <div style={{ height: "100%", width: `${percentage}%`, background: "linear-gradient(90deg, #6366f1 0%, #a855f7 100%)", transition: "width 0.5s ease-out" }}></div>
        </div>
      </div>

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 20 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <button className="btn btn-sm" onClick={() => setQty(Math.max(1, qty - 1))}>-</button>
          <span className="mono" style={{ fontSize: 18, fontWeight: 700, width: 30, textAlign: "center" }}>{qty}</span>
          <button className="btn btn-sm" onClick={() => setQty(Math.min(MAX_PER, qty + 1))}>+</button>
        </div>
        <div style={{ textAlign: "right" }}>
          <div className="mono" style={{ fontSize: 18, fontWeight: 700 }}>{total} ETH</div>
          <div className="mono" style={{ fontSize: 10, color: "var(--ink-faint)" }}>Excl. gas</div>
        </div>
      </div>
      <button 
        className="btn btn-primary" 
        style={{ width: "100%", height: 50, position: "relative" }} 
        disabled={soldOut || status === "minting"}
        onClick={mint}
      >
        {soldOut ? "SOLD OUT" : 
         status === "minting" ? "MINTING..." : 
         status === "success" ? "MINTED!" :
         status === "error" ? "ERROR" :
         !account ? "CONNECT TO MINT" : `MINT ${qty} GEMSO`}
      </button>
      {status === "error" && errorMsg && (
        <div className="mono" style={{ color: "#ef4444", fontSize: 10, marginTop: 10, textAlign: "center" }}>
          {errorMsg}
        </div>
      )}
    </div>
  );
}

function StatGrid({ minted }) {
  const cells = [
    ["Supply", "4,250", "fixed hardcap"],
    ["Minted", minted.toLocaleString(), "public mints"],
    ["Per wallet", "10", "max / address"],
    ["Mint price", "0.00019 ETH", "per gem"],
    ["Chain", "ETH L1", "mainnet"],
    ["Standard", "ERC-721", "on-chain art"],
  ];
  return (
    <section style={{ padding: "40px 0" }}>
      <div className="wrap">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 20 }} className="stat-grid">
          {cells.map(([l, v, n], i) => (
            <div key={i} className="card" style={{ padding: 20 }}>
              <div className="eyebrow" style={{ marginBottom: 8, fontSize: 10 }}>{l}</div>
              <div className="head" style={{ fontSize: 24, fontWeight: 800 }}>{v}</div>
              <div className="mono" style={{ fontSize: 10, color: "var(--ink-faint)", marginTop: 4 }}>{n}</div>
            </div>
          ))}
        </div>
      </div>
      <style>{`@media (max-width: 800px){ .stat-grid{ grid-template-columns: repeat(2,1fr) !important; } }`}</style>
    </section>
  );
}

function Gallery() {
  const ids = [2221, 2222, ...Array.from({ length: 50 }, (_, i) => 4201 + i)];
  return (
    <section id="gallery" style={{ padding: "50px 0" }}>
      <div className="wrap">
        <SectionHead eyebrow="// SPECIAL EDITIONS" title="1/1 GALLERY" note="Hand-crafted 1/1 special editions forged on-chain." />
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 20 }} className="gal-grid">
          {ids.map((id, i) => {
            return (
              <div key={i} className="gem-card card" style={{
                aspectRatio: "1", background: "var(--paper-3)",
                display: "flex", alignItems: "center", justifyContent: "center",
                position: "relative", overflow: "hidden", transition: "border-color .15s, transform .15s", cursor: "pointer",
              }}
              onMouseEnter={e => { e.currentTarget.style.transform = "translateY(-5px)"; e.currentTarget.style.borderColor = "var(--emerald)"; }}
              onMouseLeave={e => { e.currentTarget.style.transform = "translateY(0)"; e.currentTarget.style.borderColor = "var(--line)"; }}>
                <img src={getPfpUrl(id)} alt={`GEMSO #${id}`} style={{ width: "100%", height: "100%", objectFit: "cover", imageRendering: "pixelated" }} />
                <div className="mono" style={{ position: "absolute", bottom: 10, left: 12, fontSize: 10, color: "#fff", background: "rgba(0,0,0,0.5)", padding: "2px 6px", borderRadius: "2px" }}>#{id}</div>
              </div>
            );
          })}
        </div>
      </div>
      <style>{`@media (max-width: 900px){ .gal-grid{ grid-template-columns: repeat(2,1fr) !important; } }`}</style>
    </section>
  );
}

function FAQ() {
  const [open, setOpen] = useState(0);
  const items = [
    { q: "What exactly am I minting?", a: "A GEMSO is a unique pixel gem-person stored as an ERC-721 on Ethereum. Each token is generated from its token ID with unique traits." },
    { q: "How is rarity decided?", a: "Each mint pulls a random unused token id from the pool — so a rare specimen is just as likely on the first mint as the last." },
    { q: "What's the price and limit?", a: "0.00019 ETH per gem, plus gas. A wallet can mint up to 10 across as many transactions as it likes, until the 4,250 supply is exhausted." },
    { q: "Where can I trade after minting?", a: "Anywhere that supports ERC-721. Your gem-person will display correctly on all major marketplaces." },
  ];
  return (
    <section id="faq" style={{ padding: "80px 0" }}>
      <div className="wrap">
        <SectionHead eyebrow="// KNOWLEDGE BASE" title="FREQUENTLY ASKED" />
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          {items.map((it, i) => (
            <div key={i} className="card" style={{ cursor: "pointer", overflow: "hidden" }} onClick={() => setOpen(i)}>
              <div style={{ padding: "20px 24px", display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                <span className="mono" style={{ fontWeight: 700, fontSize: 14 }}>{it.q}</span>
                <span className="mono" style={{ color: "var(--emerald)" }}>{open === i ? "−" : "+"}</span>
              </div>
              {open === i && (
                <div style={{ padding: "0 24px 20px", color: "var(--ink-soft)", fontSize: 14, lineHeight: 1.6 }}>{it.a}</div>
              )}
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function Footer() {
  const links = [
    ["TWITTER", "https://x.com/gemsopfp"],
    ["ETHERSCAN", "https://etherscan.io/address/0x6e6a074c66bed9de2d4f6ad8a05e0ffd41cbb5dc"],
    ["OPENSEA", "https://opensea.io/fr/collection/gemsoart"]
  ];
  return (
    <footer id="footer" style={{ padding: "60px 0", borderTop: "1px solid var(--line)" }}>
      <div className="wrap" style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div>
          <div className="mono" style={{ fontWeight: 900, fontSize: 20 }}>GEMSO</div>
          <p className="mono" style={{ fontSize: 12, color: "var(--ink-faint)", marginTop: 8 }}>© 2026 GEMSO Atelier. All rights reserved.</p>
        </div>
        <div style={{ display: "flex", gap: 24 }}>
          {links.map(([l, h]) => (
            <a key={l} href={h} target="_blank" rel="noopener noreferrer" className="mono" style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".1em", color: "var(--ink-soft)" }}>{l}</a>
          ))}
        </div>
      </div>
    </footer>
  );
}

const GOOGLE_SCRIPT_URL = "https://script.google.com/macros/s/AKfycbzi-vr1r34CF1qBl_BUz-_16aYSDVLUdljcPdrs-0iads8i0BEAyJw8kG33bf8j3wwK/exec";

function WhitelistPage({ account }) {
  const [form, setForm] = useState({
    username: "",
    proof: "",
    wallet: account || ""
  });
  const [status, setStatus] = useState("idle");
  const [reqs, setReqs] = useState({
    follow: "idle", // idle, verifying, completed
    retweet: "idle"
  });

  useEffect(() => {
    if (account) {
      setForm(f => ({ ...f, wallet: account }));
    }
  }, [account]);

  const handleVerify = (key) => {
    if (reqs[key] !== "idle") return;
    setReqs(prev => ({ ...prev, [key]: "verifying" }));
    setTimeout(() => {
      setReqs(prev => ({ ...prev, [key]: "completed" }));
    }, 3000);
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setForm(f => ({ ...f, [name]: value }));
    if (status === "success") setStatus("idle");
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    let username = form.username;
    if (username && !username.startsWith('@')) {
      username = '@' + username;
      setForm(f => ({ ...f, username }));
    }

    setStatus("submitting");

    try {
      // Send data to Google Sheets using a GET request (most reliable for Apps Script)
      const usernameParam = encodeURIComponent(username);
      const proofParam = encodeURIComponent(form.proof);
      const walletParam = encodeURIComponent(form.wallet);
      const timestampParam = encodeURIComponent(new Date().toISOString());

      const url = `${GOOGLE_SCRIPT_URL}?username=${usernameParam}&proof=${proofParam}&wallet=${walletParam}&timestamp=${timestampParam}`;

      await fetch(url, {
        method: 'GET',
        mode: 'no-cors'
      });

      setStatus("success");
      setForm({ username: "", proof: "", wallet: account || "" });
    } catch (err) {
      console.error("Submission error:", err);
      setStatus("error");
      setTimeout(() => setStatus("idle"), 3000);
    }
  };

  const allReqsDone = reqs.follow === "completed" && reqs.retweet === "completed";

  return (
    <div className="wrap" style={{ padding: "80px 0", minHeight: "80vh", display: "flex", flexDirection: "column", alignItems: "center" }}>
      <div style={{ maxWidth: 640, width: "100%", animation: "fadeUp 0.6s ease-out forwards" }}>
        <SectionHead 
          eyebrow="// ACCESS PROTOCOL" 
          title="WHITELIST FORM" 
          note="Complete the social requirements to unlock the application for the Genesis drop." 
        />
        
        <div className="card" style={{ padding: 0, overflow: "hidden", border: "1px solid var(--line-2)", background: "var(--paper-2)" }}>
          {/* Progress Header */}
          <div style={{ 
            display: "flex", 
            borderBottom: "1px solid var(--line)", 
            background: "rgba(255,255,255,0.02)"
          }}>
            <div style={{ 
              flex: 1, padding: "16px", textAlign: "center", 
              borderRight: "1px solid var(--line)",
              color: allReqsDone ? "var(--ink-faint)" : "var(--emerald)",
              background: !allReqsDone ? "rgba(16, 185, 129, 0.05)" : "transparent",
              transition: "all 0.3s ease"
            }}>
              <span className="mono" style={{ fontSize: 10, fontWeight: 800 }}>01 SOCIALS</span>
            </div>
            <div style={{ 
              flex: 1, padding: "16px", textAlign: "center",
              color: allReqsDone ? "var(--emerald)" : "var(--ink-faint)",
              background: allReqsDone ? "rgba(16, 185, 129, 0.05)" : "transparent",
              transition: "all 0.3s ease"
            }}>
              <span className="mono" style={{ fontSize: 10, fontWeight: 800 }}>02 DETAILS</span>
            </div>
          </div>

          <div style={{ padding: "40px" }}>
            {/* STEP 1: SOCIALS */}
            <div style={{ marginBottom: 40 }}>
              <div className="eyebrow" style={{ fontSize: 9, marginBottom: 20, color: "var(--ink-faint)" }}>STEP 1: VERIFY ACTIONS</div>
              <div style={{ display: "flex", flexDirection: "column", gap: 16 }}>
                {[
                  { id: 'follow', label: 'Follow @gemsopfp on X', link: 'https://x.com/gemsopfp' },
                  { id: 'retweet', label: 'Like & Retweet Pinned Post', link: 'https://x.com/gemsopfp/status/2061179683840967077' }
                ].map((req, i) => (
                  <div key={req.id} style={{ animation: `fadeUp 0.4s ease-out ${i * 0.1}s forwards`, opacity: 0 }}>
                    <a 
                      href={req.link} 
                      target="_blank" 
                      onClick={() => handleVerify(req.id)}
                      className="btn" 
                      style={{ 
                        justifyContent: "space-between", 
                        width: "100%",
                        padding: "16px 20px",
                        borderColor: reqs[req.id] === "completed" ? "var(--emerald)" : "var(--line)",
                        background: reqs[req.id] === "completed" ? "var(--emerald-soft)" : "var(--paper-3)",
                        color: reqs[req.id] === "completed" ? "var(--emerald)" : "var(--ink)",
                        transition: "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)"
                      }}
                    >
                      <span style={{ fontSize: 13, fontWeight: 600 }}>{req.label}</span>
                      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                        {reqs[req.id] === "verifying" && <Spinner />}
                        {reqs[req.id] === "completed" && <span style={{ fontSize: 11, fontWeight: 800 }}>✓ DONE</span>}
                        {reqs[req.id] === "idle" && <span style={{ fontSize: 11, opacity: 0.5 }}>→</span>}
                      </div>
                    </a>
                  </div>
                ))}
              </div>
            </div>

            {/* STEP 2: FORM */}
            <div style={{ 
              opacity: allReqsDone ? 1 : 0.3, 
              pointerEvents: allReqsDone ? "auto" : "none", 
              transition: "all 0.5s ease",
              transform: allReqsDone ? "translateY(0)" : "translateY(10px)"
            }}>
              <div className="eyebrow" style={{ fontSize: 9, marginBottom: 20, color: "var(--ink-faint)" }}>STEP 2: APPLICATION DETAILS</div>
              
              <form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: 24 }}>
                <div className="input-group">
                  <label className="mono" style={{ fontSize: 10, fontWeight: 700, display: "block", marginBottom: 10, color: "var(--ink-soft)" }}>X USERNAME</label>
                  <input 
                    name="username"
                    type="text" 
                    required
                    placeholder="@username"
                    value={form.username}
                    onChange={handleChange}
                    className="form-input"
                  />
                </div>

                <div className="input-group">
                  <label className="mono" style={{ fontSize: 10, fontWeight: 700, display: "block", marginBottom: 10, color: "var(--ink-soft)" }}>COMMENT & PROOF (LINK)</label>
                  <input 
                    name="proof"
                    type="text" 
                    required
                    placeholder="Link to your quote or comment"
                    value={form.proof}
                    onChange={handleChange}
                    className="form-input"
                  />
                </div>

                <div className="input-group">
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 10 }}>
                    <label className="mono" style={{ fontSize: 10, fontWeight: 700, color: "var(--ink-soft)" }}>WALLET ADDRESS</label>
                    {account && <span className="mono" style={{ fontSize: 8, color: "var(--emerald)", fontWeight: 800, padding: "2px 6px", background: "var(--emerald-soft)", borderRadius: "4px" }}>CONNECTED</span>}
                  </div>
                  <input 
                    name="wallet"
                    type="text" 
                    required
                    placeholder="0x..."
                    value={form.wallet}
                    onChange={handleChange}
                    disabled={!!account}
                    className="form-input"
                    style={{ 
                      background: account ? "rgba(255,255,255,0.03)" : "var(--paper-3)", 
                      cursor: account ? "not-allowed" : "text",
                      opacity: account ? 0.7 : 1
                    }}
                  />
                </div>

                <button 
                  type="submit" 
                  className="btn btn-primary" 
                  style={{ 
                    marginTop: 12, height: 54, fontSize: 14, 
                    boxShadow: allReqsDone ? "0 4px 20px rgba(16, 185, 129, 0.2)" : "none"
                  }} 
                  disabled={status === "submitting" || !allReqsDone}
                >
                  {status === "submitting" ? (
                    <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                      <Spinner />
                      <span>PROCESSING APPLICATION...</span>
                    </div>
                  ) : status === "success" ? "✓ APPLICATION SUBMITTED" : "SUBMIT APPLICATION"}
                </button>

                {status === "success" && (
                  <div className="fade-in" style={{ 
                    background: "var(--emerald-soft)", 
                    padding: "20px", 
                    borderRadius: "12px", 
                    border: "1px solid var(--emerald)",
                    marginTop: 10,
                    textAlign: "center"
                  }}>
                    <div style={{ fontSize: 24, marginBottom: 10 }}>🎉</div>
                    <p className="mono" style={{ fontSize: 13, color: "var(--emerald)", margin: 0, fontWeight: 700 }}>
                      Success! Your specimen has been logged.
                    </p>
                    <p className="mono" style={{ fontSize: 11, color: "var(--ink-soft)", marginTop: 8 }}>
                      Check our Discord for role updates soon.
                    </p>
                  </div>
                )}
              </form>
            </div>
          </div>
        </div>
      </div>
      <style>{`
        .form-input {
          width: 100%;
          background: var(--paper-3);
          border: 1px solid var(--line);
          padding: 16px;
          border-radius: 10px;
          color: var(--ink);
          font-family: 'JetBrains Mono', monospace;
          font-size: 13px;
          transition: all 0.3s ease;
          outline: none;
        }
        .form-input:focus {
          border-color: var(--emerald);
          background: var(--paper-2);
          box-shadow: 0 0 0 4px var(--emerald-soft);
        }
        .spinner { animation: rotate 2s linear infinite; }
        .spinner circle { stroke-dasharray: 90, 150; stroke-dashoffset: 0; animation: dash 1.5s ease-in-out infinite; }
        @keyframes rotate { 100% { transform: rotate(360deg); } }
        @keyframes dash { 0% { stroke-dasharray: 1, 150; stroke-dashoffset: 0; } 50% { stroke-dasharray: 90, 150; stroke-dashoffset: -35; } 100% { stroke-dasharray: 90, 150; stroke-dashoffset: -124; } }
        @keyframes fadeUp {
          from { opacity: 0; transform: translateY(20px); }
          to { opacity: 1; transform: translateY(0); }
        }
      `}</style>
    </div>
  );
}

// Helper Spinner Component
function Spinner() {
  return (
    <svg className="spinner" viewBox="0 0 50 50" style={{ width: 18, height: 18 }}>
      <circle cx="25" cy="25" r="20" fill="none" strokeWidth="5" stroke="currentColor" strokeLinecap="round" />
    </svg>
  );
}


function MintPage({ minted, onMinted, account, connectWallet }) {
  return (
    <div className="fade-in">
      <Hero minted={minted} onMinted={onMinted} account={account} connectWallet={connectWallet} />
      <StatGrid minted={minted} />
    </div>
  );
}

function LandingPage({ minted, onMinted, account, connectWallet }) {
  return (
    <div className="fade-in">
      <Hero minted={minted} onMinted={onMinted} account={account} connectWallet={connectWallet} />
      <StatGrid minted={minted} />
      <Gallery />
      <FAQ />
    </div>
  );
}

function App() {
  const [minted, setMinted] = useState(START_MINTED);
  const [account, setAccount] = useState(null);
  const [isOwner, setIsOwner] = useState(false);
  const { path } = useRouter();

  const onMinted = (n) => setMinted(m => Math.min(SUPPLY, m + n));

  const connectWallet = async () => {
    if (typeof window.ethereum !== "undefined") {
      try {
        const accounts = await window.ethereum.request({ method: "eth_requestAccounts" });
        setAccount(accounts[0]);
      } catch (err) {
        console.error("User denied account access");
      }
    } else {
      alert("Please install MetaMask!");
    }
  };

  const withdraw = async () => {
    if (!account || !isOwner) return;
    try {
      const provider = new ethers.providers.Web3Provider(window.ethereum);
      const signer = provider.getSigner();
      const contract = new ethers.Contract(CONTRACT_ADDRESS, ABI, signer);
      const tx = await contract.withdraw();
      await tx.wait();
      alert("Withdrawal successful!");
    } catch (err) {
      console.error("Withdrawal failed:", err);
      alert("Withdrawal failed: " + (err.reason || err.message));
    }
  };

  useEffect(() => {
    const checkConnection = async () => {
      if (typeof window.ethereum !== "undefined") {
        const accounts = await window.ethereum.request({ method: "eth_accounts" });
        if (accounts.length > 0) {
          setAccount(accounts[0]);
        }
      }
    };
    checkConnection();

    const fetchMinted = async () => {
      try {
        // Use public RPC if window.ethereum is not available
        const provider = (typeof window.ethereum !== "undefined") 
          ? new ethers.providers.Web3Provider(window.ethereum)
          : new ethers.providers.JsonRpcProvider("https://cloudflare-eth.com");
        
        const contract = new ethers.Contract(CONTRACT_ADDRESS, ABI, provider);
        const supply = await contract.totalSupply();
        setMinted(supply.toNumber());
      } catch (err) {
        console.error("Error fetching supply:", err);
      }
    };
    fetchMinted();

    // Simulated minting progress
    const interval = setInterval(() => {
      setMinted(m => {
        if (m >= SUPPLY - 20) return m; // Stop just before supply cap
        
        // Randomly pick an increment: 3, 5, 6, or 10
        const increments = [3, 5, 6, 10];
        const increment = increments[Math.floor(Math.random() * increments.length)];
        
        return Math.min(SUPPLY - 20, m + increment);
      });
    }, 5000); // Trigger every 5 seconds

    if (window.ethereum) {
      window.ethereum.on("accountsChanged", (accounts) => {
        setAccount(accounts[0] || null);
      });
    }

    return () => clearInterval(interval);
  }, []);

  useEffect(() => {
    const checkOwner = async () => {
      if (account) {
        try {
          const provider = new ethers.providers.Web3Provider(window.ethereum);
          const contract = new ethers.Contract(CONTRACT_ADDRESS, ABI, provider);
          const owner = await contract.owner();
          setIsOwner(owner.toLowerCase() === account.toLowerCase());
        } catch (err) {
          console.error("Error checking owner:", err);
        }
      } else {
        setIsOwner(false);
      }
    };
    checkOwner();
  }, [account]);

  const renderContent = () => {
    if (path === "/mint") return <MintPage minted={minted} onMinted={onMinted} account={account} connectWallet={connectWallet} />;
    if (path === "/whitelist") return <WhitelistPage account={account} />;
    return <LandingPage minted={minted} onMinted={onMinted} account={account} connectWallet={connectWallet} />;
  };

  return (
    <div className="fade-in">
      <Header account={account} connectWallet={connectWallet} isOwner={isOwner} withdraw={withdraw} />
      {renderContent()}
      {path !== "/whitelist" && <Footer />}
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
