const { useState, useEffect, useMemo } = React;

// --- Custom Vector Icons ---
const Icon = ({ name, className = "w-4 h-4" }) => {
  switch (name) {
    case 'sparkles':
      return <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/><path d="M5 3v4"/><path d="M19 17v4"/><path d="M3 5h4"/><path d="M17 19h4"/></svg>;
    case 'check':
      return <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>;
    case 'copy':
      return <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>;
    case 'download':
      return <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" 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="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>;
    case 'trash':
      return <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>;
    case 'wallet':
      return <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"/><path d="M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"/></svg>;
    case 'users':
      return <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>;
    case 'search':
      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"/><path d="m21 21-4.3-4.3"/></svg>;
    case 'crown':
      return <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M11.562 3.266a.5.5 0 0 1 .876 0L15.39 8.87a1 1 0 0 0 1.516.294L21.183 5.5a.5.5 0 0 1 .798.519l-2.834 10.201a4 4 0 0 1-3.854 2.93H8.707a4 4 0 0 1-3.854-2.93L2.019 6.019a.5.5 0 0 1 .798-.519l4.276 3.664a1 1 0 0 0 1.516-.294z"/></svg>;
    case 'x':
    case 'twitter':
      return <svg className={className} viewBox="0 0 24 24" fill="currentColor"><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>;
    case 'external':
      return <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/></svg>;
    default:
      return <svg className={className} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><circle cx="12" cy="12" r="10"/></svg>;
  }
};

function App() {
  const [twitterHandle, setTwitterHandle] = useState('');
  const [walletAddress, setWalletAddress] = useState('');
  const [proofLink, setProofLink] = useState('');
  
  const [followedX, setFollowedX] = useState(false);
  const [repostedX, setRepostedX] = useState(false);

  const [isSubmitting, setIsSubmitting] = useState(false);
  const [submittedWL, setSubmittedWL] = useState(null);
  const [toast, setToast] = useState(null);

  // Admin / Wallet Extractor State
  const [isAdminOpen, setIsAdminOpen] = useState(false);
  const [allEntries, setAllEntries] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [copiedKey, setCopiedKey] = useState(null);

  // Live 24-Hour Countdown Timer
  const [timeLeft, setTimeLeft] = useState({ hours: 23, minutes: 59, seconds: 59 });

  useEffect(() => {
    let target = localStorage.getItem('ink_apply_deadline');
    if (!target) {
      target = String(Date.now() + 24 * 60 * 60 * 1000);
      localStorage.setItem('ink_apply_deadline', target);
    }
    const targetMs = Number(target);

    const updateTimer = () => {
      const now = Date.now();
      const diff = Math.max(0, targetMs - now);
      const hours = Math.floor(diff / (1000 * 60 * 60));
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((diff % (1000 * 60)) / 1000);
      setTimeLeft({ hours, minutes, seconds });
    };

    updateTimer();
    const interval = setInterval(updateTimer, 1000);
    return () => clearInterval(interval);
  }, []);

  // Load entries & User previous submission
  useEffect(() => {
    try {
      const saved = JSON.parse(localStorage.getItem('ink_wl_entries') || '[]');
      setAllEntries(saved);
      const mySaved = JSON.parse(localStorage.getItem('ink_my_wl_entry') || 'null');
      if (mySaved) {
        setSubmittedWL(mySaved);
      }
    } catch (e) {
      console.warn(e);
    }
  }, []);

  // Real-time Duplicate Detection
  const isWalletAlreadyUsed = useMemo(() => {
    if (!walletAddress.trim() || walletAddress.trim().length < 10) return false;
    const clean = walletAddress.trim().toLowerCase();
    return allEntries.some(e => e.wallet && e.wallet.trim().toLowerCase() === clean);
  }, [walletAddress, allEntries]);

  const isHandleAlreadyUsed = useMemo(() => {
    if (!twitterHandle.trim()) return false;
    const clean = ('@' + twitterHandle.trim().replace(/^@/, '')).toLowerCase();
    return allEntries.some(e => e.handle && e.handle.trim().toLowerCase() === clean);
  }, [twitterHandle, allEntries]);

  const showToast = (msg) => {
    setToast(msg);
    setTimeout(() => setToast(null), 3000);
  };

  const connectAndFill = async () => {
    if (typeof window !== 'undefined' && window.ethereum) {
      try {
        const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
        if (accounts && accounts.length > 0) {
          setWalletAddress(accounts[0]);
          showToast(`Wallet connected: ${accounts[0].slice(0, 6)}...${accounts[0].slice(-4)}`);
        }
      } catch (e) {
        showToast('Connection rejected');
      }
    } else {
      const demo = '0x8bACa8406610d82a23CaBd1E40318971616f9fCC';
      setWalletAddress(demo);
      showToast('Autofilled demo wallet');
    }
  };

  const GOOGLE_SHEETS_URL = 'https://script.google.com/macros/s/AKfycbzuo-No3k9JB3Zlw5UwYtVVNUooKj3bUlApfDKsgKSJDMQX6gjJWk-pDhFZipQK2cUj/exec';

  const handleSubmit = (e) => {
    e.preventDefault();
    const cleanHandle = twitterHandle.trim().replace(/^@/, '');
    if (!cleanHandle) {
      showToast('Please enter your X / Twitter handle');
      return;
    }
    if (!walletAddress.trim() || walletAddress.trim().length < 10) {
      showToast('Please enter a valid EVM Wallet Address');
      return;
    }
    if (!proofLink.trim()) {
      showToast('Please provide your Like, RT & Comment link');
      return;
    }

    // --- Duplicate Prevention Check ---
    const existing = JSON.parse(localStorage.getItem('ink_wl_entries') || '[]');
    const handleCheck = ('@' + cleanHandle).toLowerCase();
    const walletCheck = walletAddress.trim().toLowerCase();

    const isDuplicate = existing.some(e => 
      (e.handle && e.handle.toLowerCase() === handleCheck) || 
      (e.wallet && e.wallet.toLowerCase() === walletCheck)
    );

    if (isDuplicate) {
      showToast('⚠️ This Twitter handle or wallet has already applied!');
      return;
    }

    setIsSubmitting(true);

    const entryId = 'INK-WL-' + Math.floor(10000 + Math.random() * 90000);
    const entry = {
      id: entryId,
      handle: '@' + cleanHandle,
      wallet: walletAddress.trim(),
      proofLink: proofLink.trim(),
      submittedAt: new Date().toISOString()
    };

    // 1. Live real-time sync to Google Sheets
    try {
      fetch(GOOGLE_SHEETS_URL, {
        method: 'POST',
        mode: 'no-cors',
        headers: { 'Content-Type': 'text/plain;charset=utf-8' },
        body: JSON.stringify({
          handle: entry.handle,
          wallet: entry.wallet,
          proofLink: entry.proofLink,
          id: entry.id
        })
      }).catch(err => console.warn('Google Sheets sync note:', err));
    } catch (sheetErr) {
      console.warn('Google Sheets error:', sheetErr);
    }

    // 2. Backup to local storage
    try {
      const existing = JSON.parse(localStorage.getItem('ink_wl_entries') || '[]');
      const updated = [entry, ...existing];
      localStorage.setItem('ink_wl_entries', JSON.stringify(updated));
      localStorage.setItem('ink_my_wl_entry', JSON.stringify(entry));
      setAllEntries(updated);
    } catch (err) {
      console.warn(err);
    }

    setTimeout(() => {
      setIsSubmitting(false);
      setSubmittedWL(entry);

      if (window.confetti) {
        window.confetti({ particleCount: 120, spread: 80, origin: { y: 0.6 } });
      }
    }, 600);
  };

  // --- Export Actions ---
  const copyAllWallets = (format = 'lines') => {
    if (allEntries.length === 0) {
      showToast('No submitted wallets yet');
      return;
    }
    const wallets = allEntries.map(e => e.wallet);
    let text = '';
    if (format === 'lines') {
      text = wallets.join('\n');
    } else if (format === 'json') {
      text = JSON.stringify(wallets, null, 2);
    } else {
      text = wallets.join(', ');
    }
    navigator.clipboard.writeText(text);
    setCopiedKey(format);
    showToast(`Copied ${wallets.length} wallet addresses!`);
    setTimeout(() => setCopiedKey(null), 2000);
  };

  const exportCSV = () => {
    if (allEntries.length === 0) {
      showToast('No entries to export');
      return;
    }
    let csv = 'Entry ID,Twitter Handle,EVM Wallet Address,Proof Link,Submitted At\n';
    allEntries.forEach(e => {
      csv += `"${e.id}","${e.handle}","${e.wallet}","${e.proofLink}","${e.submittedAt}"\n`;
    });
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `ink_whitelist_wallets_${Date.now()}.csv`;
    link.click();
    showToast('Downloaded Whitelist CSV!');
  };

  const exportJSON = () => {
    if (allEntries.length === 0) {
      showToast('No entries to export');
      return;
    }
    const blob = new Blob([JSON.stringify(allEntries, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `ink_whitelist_entries_${Date.now()}.json`;
    link.click();
    showToast('Downloaded Whitelist JSON!');
  };

  const deleteEntry = (id) => {
    const updated = allEntries.filter(e => e.id !== id);
    setAllEntries(updated);
    localStorage.setItem('ink_wl_entries', JSON.stringify(updated));
    showToast('Entry removed');
  };

  const filteredEntries = useMemo(() => {
    if (!searchTerm.trim()) return allEntries;
    const term = searchTerm.toLowerCase();
    return allEntries.filter(e => 
      e.handle.toLowerCase().includes(term) ||
      e.wallet.toLowerCase().includes(term) ||
      e.id.toLowerCase().includes(term)
    );
  }, [allEntries, searchTerm]);

  return (
    <div className="min-h-screen flex flex-col justify-between text-gray-100">
      
      {/* Toast */}
      {toast && (
        <div className="fixed top-5 right-5 z-50 px-4 py-3 rounded-2xl glass-card border border-ink-500/40 text-white font-mono text-xs flex items-center gap-2 shadow-2xl animate-bounce">
          <span className="w-2 h-2 rounded-full bg-emerald-400"></span>
          <span>{toast}</span>
        </div>
      )}

      {/* Header */}
      <header className="px-4 lg:px-8 py-5">
        <div className="max-w-xl mx-auto flex items-center justify-between">
          <div className="flex items-center gap-3">
            <img src="logo.png" alt="INK Logo" className="w-9 h-9 rounded-xl object-cover border border-white/10 shadow-md" />
            <span className="font-bold text-lg text-white">INK Protocol</span>
          </div>
        </div>
      </header>

      {/* Main Content */}
      <main className="max-w-xl mx-auto w-full px-4 py-6 flex-1 flex flex-col justify-center">
        
        {!submittedWL ? (
          <div className="glass-card p-6 sm:p-8 rounded-3xl border border-white/10 shadow-2xl space-y-6">
            
            {/* Title */}
            <div className="text-center space-y-2">
              <div className="inline-flex items-center px-3 py-1 rounded-full bg-ink-500/10 text-ink-300 border border-ink-500/30 text-xs font-mono font-semibold">
                <span>Free Mint Application</span>
              </div>
              <h1 className="text-3xl sm:text-4xl font-extrabold text-white tracking-tight">
                Get In Early
              </h1>
              <p className="text-xs sm:text-sm text-gray-400 font-sans">
                Secure your Guaranteed Free Mint on Ink. Submit your X handle, wallet address, and proof link below.
              </p>
            </div>

            {/* Live 24-Hour Countdown Timer */}
            <div className="p-3.5 rounded-2xl bg-black/40 border border-amber-500/30 flex items-center justify-between gap-2 shadow-inner">
              <div className="flex items-center gap-2">
                <span className="w-2.5 h-2.5 rounded-full bg-amber-400 animate-pulse"></span>
                <span className="text-xs font-mono font-bold text-gray-200 uppercase tracking-wider">
                  Applications Close In:
                </span>
              </div>
              <div className="flex items-center gap-1 font-mono text-xs sm:text-sm font-black">
                <span className="px-2 py-1 rounded-lg bg-white/5 border border-white/10 text-amber-300">
                  {String(timeLeft.hours).padStart(2, '0')}h
                </span>
                <span className="text-gray-500 font-bold">:</span>
                <span className="px-2 py-1 rounded-lg bg-white/5 border border-white/10 text-amber-300">
                  {String(timeLeft.minutes).padStart(2, '0')}m
                </span>
                <span className="text-gray-500 font-bold">:</span>
                <span className="px-2 py-1 rounded-lg bg-white/5 border border-white/10 text-amber-300">
                  {String(timeLeft.seconds).padStart(2, '0')}s
                </span>
              </div>
            </div>

            {/* Quick Tasks */}
            <div className="space-y-2.5 pt-1">
              <p className="text-xs font-bold text-gray-300 uppercase tracking-wider font-mono">1. Complete Steps on X</p>
              
              <a
                href="https://x.com/Ink20Protocol"
                target="_blank"
                rel="noreferrer"
                onClick={() => setFollowedX(true)}
                className={`w-full p-3 rounded-2xl flex items-center justify-between transition border ${
                  followedX
                    ? 'bg-emerald-500/10 border-emerald-500/30 text-emerald-400'
                    : 'bg-white/5 hover:bg-white/10 border-white/10 text-gray-200'
                }`}
              >
                <div className="flex items-center gap-2.5">
                  <Icon name="x" className="w-4 h-4" />
                  <span className="text-xs font-semibold">Follow @Ink20Protocol on X</span>
                </div>
                <div className="flex items-center gap-1 text-xs font-mono">
                  {followedX ? (
                    <span className="flex items-center gap-1 text-emerald-400"><Icon name="check" className="w-3.5 h-3.5" /> Followed</span>
                  ) : (
                    <span className="text-ink-400 flex items-center gap-1">Open <Icon name="external" className="w-3 h-3" /></span>
                  )}
                </div>
              </a>

              <a
                href="https://x.com/Ink20Protocol"
                target="_blank"
                rel="noreferrer"
                onClick={() => setRepostedX(true)}
                className={`w-full p-3 rounded-2xl flex items-center justify-between transition border ${
                  repostedX
                    ? 'bg-emerald-500/10 border-emerald-500/30 text-emerald-400'
                    : 'bg-white/5 hover:bg-white/10 border-white/10 text-gray-200'
                }`}
              >
                <div className="flex items-center gap-2.5">
                  <Icon name="x" className="w-4 h-4" />
                  <span className="text-xs font-semibold">Like, Repost & Comment on Pinned Post</span>
                </div>
                <div className="flex items-center gap-1 text-xs font-mono">
                  {repostedX ? (
                    <span className="flex items-center gap-1 text-emerald-400"><Icon name="check" className="w-3.5 h-3.5" /> Done</span>
                  ) : (
                    <span className="text-ink-400 flex items-center gap-1">Open <Icon name="external" className="w-3 h-3" /></span>
                  )}
                </div>
              </a>
            </div>

            {/* Form Inputs */}
            <form onSubmit={handleSubmit} className="space-y-4 pt-1">
              <p className="text-xs font-bold text-gray-300 uppercase tracking-wider font-mono">2. Submit Your Details</p>

              <div>
                <label className="block text-xs font-medium text-gray-300 mb-1.5">
                  Your X (Twitter) Handle <span className="text-rose-400">*</span>
                </label>
                <div className="relative">
                  <span className="absolute left-3.5 top-1/2 -translate-y-1/2 text-gray-400 font-mono text-sm">@</span>
                  <input
                    type="text"
                    required
                    placeholder="username"
                    value={twitterHandle}
                    onChange={(e) => setTwitterHandle(e.target.value.replace(/^@/, ''))}
                    className={`w-full pl-8 pr-3.5 py-2.5 rounded-xl glass-input text-white text-sm font-mono focus:outline-none ${isHandleAlreadyUsed ? 'border-rose-500/80 bg-rose-950/20' : ''}`}
                  />
                </div>
                {isHandleAlreadyUsed && (
                  <p className="text-xs font-mono text-rose-400 font-bold mt-1.5 flex items-center gap-1.5 bg-rose-500/10 p-2 rounded-xl border border-rose-500/30 animate-pulse">
                    <span>⚠️</span>
                    <span>This Twitter handle has already applied!</span>
                  </p>
                )}
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-300 mb-1.5">
                  EVM Wallet Address (Ink Superchain) <span className="text-rose-400">*</span>
                </label>
                <input
                  type="text"
                  required
                  placeholder="0x..."
                  value={walletAddress}
                  onChange={(e) => setWalletAddress(e.target.value)}
                  className={`w-full px-3.5 py-2.5 rounded-xl glass-input text-white text-xs font-mono focus:outline-none ${isWalletAlreadyUsed ? 'border-rose-500/80 bg-rose-950/20' : ''}`}
                />
                {isWalletAlreadyUsed && (
                  <p className="text-xs font-mono text-rose-400 font-bold mt-1.5 flex items-center gap-1.5 bg-rose-500/10 p-2 rounded-xl border border-rose-500/30 animate-pulse">
                    <span>⚠️</span>
                    <span>This wallet address has already applied!</span>
                  </p>
                )}
              </div>

              <div>
                <label className="block text-xs font-medium text-gray-300 mb-1.5">
                  Proof Link (Like, RT & Comment Link) <span className="text-rose-400">*</span>
                </label>
                <div className="relative">
                  <input
                    type="url"
                    required
                    placeholder="https://x.com/username/status/..."
                    value={proofLink}
                    onChange={(e) => setProofLink(e.target.value)}
                    className="w-full px-3.5 py-2.5 rounded-xl glass-input text-white text-xs font-mono focus:outline-none"
                  />
                </div>
              </div>

              <button
                type="submit"
                disabled={isSubmitting || isWalletAlreadyUsed || isHandleAlreadyUsed}
                className={`w-full py-3.5 rounded-2xl text-white font-bold text-sm shadow-xl transition-all flex items-center justify-center gap-2 mt-2 ${
                  isWalletAlreadyUsed || isHandleAlreadyUsed
                    ? 'bg-rose-950/40 border border-rose-500/30 text-rose-300 cursor-not-allowed'
                    : 'bg-gradient-to-r from-ink-600 to-purple-600 hover:from-ink-500 hover:to-purple-500 shadow-ink-600/30 hover:scale-[1.01] cursor-pointer'
                }`}
              >
                {isSubmitting ? (
                  <>
                    <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"></div>
                    <span>Saving Entry...</span>
                  </>
                ) : isWalletAlreadyUsed || isHandleAlreadyUsed ? (
                  <span>⚠️ Already Applied (Duplicate)</span>
                ) : (
                  <span>Apply for Guaranteed Free Mint</span>
                )}
              </button>
            </form>

          </div>
        ) : (
          /* Confirmation Success Card */
          <div className="glass-card p-6 sm:p-8 rounded-3xl border border-emerald-500/40 shadow-2xl text-center space-y-5 animate-scale">
            <div className="w-14 h-14 rounded-2xl bg-emerald-500/20 text-emerald-400 flex items-center justify-center mx-auto border border-emerald-500/30 shadow-lg">
              <Icon name="check" className="w-7 h-7" />
            </div>

            <div className="space-y-1">
              <h2 className="text-2xl font-bold text-white">You're on the list!</h2>
              <p className="text-xs text-dark-muted font-mono">Entry ID: <strong className="text-ink-300">{submittedWL.id}</strong></p>
            </div>

            <div className="p-4 rounded-2xl bg-black/50 border border-white/10 text-xs font-mono text-left space-y-2">
              <div className="flex justify-between py-1 border-b border-white/5">
                <span className="text-dark-muted">Twitter Handle:</span>
                <span className="text-white font-bold">{submittedWL.handle}</span>
              </div>
              <div className="flex justify-between py-1 border-b border-white/5">
                <span className="text-dark-muted">Wallet:</span>
                <span className="text-white">{submittedWL.wallet.slice(0, 8)}...{submittedWL.wallet.slice(-6)}</span>
              </div>
              <div className="flex justify-between py-1 border-b border-white/5">
                <span className="text-dark-muted">Proof Link:</span>
                <span className="text-emerald-400 truncate max-w-[200px]" title={submittedWL.proofLink}>{submittedWL.proofLink}</span>
              </div>
              <div className="flex justify-between py-1">
                <span className="text-dark-muted">Status:</span>
                <span className="text-emerald-400 font-bold">FREE MINT GUARANTEED</span>
              </div>
            </div>

            <div className="pt-2">
              <a
                href={`https://twitter.com/intent/tweet?text=${encodeURIComponent("Got guaranteed Free Mint for @Ink20Protocol on Ink Superchain ⚡! Get In Early 🖊️")}&url=${encodeURIComponent(typeof window !== 'undefined' ? window.location.href : '')}`}
                target="_blank"
                rel="noreferrer"
                className="w-full py-3.5 px-4 rounded-xl bg-white/10 hover:bg-white/20 text-white font-bold text-xs flex items-center justify-center gap-2 transition font-mono border border-white/10"
              >
                <Icon name="x" className="w-3.5 h-3.5" />
                <span>Share & Confirm on X</span>
              </a>
            </div>
          </div>
        )}

      </main>

      {/* ADMIN / WALLETS EXTRACTION MODAL */}
      {isAdminOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/85 backdrop-blur-md">
          <div className="glass-card p-6 sm:p-8 rounded-3xl max-w-3xl w-full space-y-5 border border-ink-500/40 shadow-2xl relative max-h-[90vh] flex flex-col">
            
            {/* Modal Header */}
            <div className="flex items-center justify-between pb-3 border-b border-white/10">
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-xl bg-ink-500/20 text-ink-300 flex items-center justify-center font-bold">
                  <Icon name="crown" className="w-5 h-5 text-amber-300" />
                </div>
                <div>
                  <h3 className="text-lg font-bold text-white flex items-center gap-2">
                    <span>Whitelist Submissions</span>
                    <span className="px-2 py-0.5 rounded-full text-xs font-mono font-bold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">
                      {allEntries.length} Wallets
                    </span>
                  </h3>
                  <p className="text-xs text-dark-muted font-mono">View, copy, and export all applicant wallet addresses</p>
                </div>
              </div>

              <button
                onClick={() => setIsAdminOpen(false)}
                className="w-8 h-8 rounded-lg bg-white/5 hover:bg-white/15 text-gray-400 hover:text-white font-mono flex items-center justify-center transition"
              >
                ✕
              </button>
            </div>

            {/* Quick Action Export Buttons */}
            <div className="grid grid-cols-2 sm:grid-cols-4 gap-2">
              <button
                onClick={() => copyAllWallets('lines')}
                className="py-2.5 px-3 rounded-xl bg-gradient-to-r from-ink-600 to-purple-600 hover:from-ink-500 hover:to-purple-500 text-white font-bold text-xs flex items-center justify-center gap-1.5 transition font-mono shadow-md"
              >
                {copiedKey === 'lines' ? <Icon name="check" className="w-3.5 h-3.5 text-emerald-300" /> : <Icon name="copy" className="w-3.5 h-3.5" />}
                <span>Copy Wallets (1/line)</span>
              </button>

              <button
                onClick={() => copyAllWallets('json')}
                className="py-2.5 px-3 rounded-xl bg-white/10 hover:bg-white/20 text-white font-bold text-xs flex items-center justify-center gap-1.5 transition font-mono border border-white/10"
              >
                {copiedKey === 'json' ? <Icon name="check" className="w-3.5 h-3.5 text-emerald-300" /> : <Icon name="copy" className="w-3.5 h-3.5" />}
                <span>Copy JSON Array</span>
              </button>

              <button
                onClick={exportCSV}
                className="py-2.5 px-3 rounded-xl bg-emerald-600/20 hover:bg-emerald-600/30 text-emerald-300 font-bold text-xs flex items-center justify-center gap-1.5 transition font-mono border border-emerald-500/30"
              >
                <Icon name="download" className="w-3.5 h-3.5" />
                <span>Export CSV</span>
              </button>

              <button
                onClick={exportJSON}
                className="py-2.5 px-3 rounded-xl bg-cyan-600/20 hover:bg-cyan-600/30 text-cyan-300 font-bold text-xs flex items-center justify-center gap-1.5 transition font-mono border border-cyan-500/30"
              >
                <Icon name="download" className="w-3.5 h-3.5" />
                <span>Export JSON</span>
              </button>
            </div>

            {/* Search Filter */}
            <div className="relative">
              <Icon name="search" className="w-4 h-4 text-gray-400 absolute left-3.5 top-1/2 -translate-y-1/2" />
              <input
                type="text"
                placeholder="Search by Twitter handle or wallet (0x...)"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full pl-10 pr-4 py-2 rounded-xl glass-input text-white text-xs font-mono focus:outline-none"
              />
            </div>

            {/* Submissions Table / List */}
            <div className="flex-1 overflow-y-auto pr-1 space-y-2 max-h-96">
              {filteredEntries.length === 0 ? (
                <div className="text-center py-10 text-dark-muted font-mono text-xs space-y-1">
                  <p>No whitelist entries found.</p>
                  <p className="text-[11px]">When visitors submit the form, their wallets will appear here instantly.</p>
                </div>
              ) : (
                filteredEntries.map((entry, idx) => (
                  <div
                    key={entry.id || idx}
                    className="p-3 rounded-2xl bg-black/40 border border-white/5 flex flex-wrap items-center justify-between gap-3 text-xs font-mono hover:border-ink-500/30 transition"
                  >
                    <div className="flex items-center gap-3">
                      <span className="w-6 text-center text-dark-muted font-bold">#{idx + 1}</span>
                      <div>
                        <div className="flex items-center gap-2">
                          <span className="text-white font-bold">{entry.handle}</span>
                          <span className="text-[10px] px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-400 font-semibold border border-emerald-500/20">
                            {entry.id}
                          </span>
                        </div>
                        <div className="text-ink-300 text-[11px] select-all font-mono mt-0.5">
                          {entry.wallet}
                        </div>
                      </div>
                    </div>

                    <div className="flex items-center gap-2">
                      <a
                        href={entry.proofLink}
                        target="_blank"
                        rel="noreferrer"
                        className="px-2.5 py-1 rounded-lg bg-white/5 hover:bg-white/10 text-gray-300 hover:text-white text-[11px] flex items-center gap-1 transition"
                        title={entry.proofLink}
                      >
                        <span>Proof</span>
                        <Icon name="external" className="w-3 h-3" />
                      </a>

                      <button
                        onClick={() => {
                          navigator.clipboard.writeText(entry.wallet);
                          showToast('Copied wallet address!');
                        }}
                        className="p-1.5 rounded-lg bg-white/5 hover:bg-white/15 text-gray-300 hover:text-white transition"
                        title="Copy this wallet"
                      >
                        <Icon name="copy" className="w-3.5 h-3.5" />
                      </button>

                      <button
                        onClick={() => deleteEntry(entry.id)}
                        className="p-1.5 rounded-lg bg-rose-500/10 hover:bg-rose-500/25 text-rose-400 transition"
                        title="Delete entry"
                      >
                        <Icon name="trash" className="w-3.5 h-3.5" />
                      </button>
                    </div>
                  </div>
                ))
              )}
            </div>

            {/* Modal Footer */}
            <div className="flex items-center justify-between pt-3 border-t border-white/10 text-xs font-mono text-dark-muted">
              <span>Auto-saved to your browser storage</span>
              <button
                onClick={() => setIsAdminOpen(false)}
                className="px-4 py-2 rounded-xl bg-white/10 hover:bg-white/20 text-white font-bold transition"
              >
                Close
              </button>
            </div>

          </div>
        </div>
      )}

      {/* Footer */}
      <footer className="px-4 py-5 text-center text-xs text-dark-muted font-mono">
        <p>Powered by <strong className="text-ink-300">INK Protocol</strong> · Ink Superchain</p>
      </footer>

    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
