// @ts-nocheck
// Remove imports for browser environment (Babel Standalone uses globals)
const { useState, useEffect, useRef } = React;
const { createRoot } = ReactDOM;

// --- STYLES ---
const styles = `
  :root {
    --bg-color: #040404;
    --card-bg: #111111;
    --text-main: #e0e0e0;
    --text-muted: #888888;
    --accent-gold: #c5a059;
    --accent-gold-dim: #8a703d;
    --accent-red: #8f2a2a;
    --border-color: #222222;
    --spacing-section: 100px;
  }

  @keyframes subtleShift {
    0% { background-position: 0% 50%; }
    50% { background-position: 100% 50%; }
    100% { background-position: 0% 50%; }
  }

  @keyframes pulse {
    0% { transform: scale(1); box-shadow: 0 0 0 0 rgba(197, 160, 89, 0.7); }
    70% { transform: scale(1.5); box-shadow: 0 0 0 10px rgba(197, 160, 89, 0); }
    100% { transform: scale(1); box-shadow: 0 0 0 0 rgba(197, 160, 89, 0); }
  }

  * { margin: 0; padding: 0; box-sizing: border-box; }
  html { scroll-behavior: smooth; }
  body {
    background: linear-gradient(270deg, #040404, #0a0a0a, #101010, #040404);
    background-size: 600% 600%;
    animation: subtleShift 60s ease infinite;
    color: var(--text-main);
    font-family: 'Inter', sans-serif;
    line-height: 1.6;
    overflow-x: hidden;
  }

  h1, h2, h3, h4, h5, h6 {
    font-family: 'Oswald', sans-serif;
    text-transform: uppercase;
    letter-spacing: 1px;
    color: white;
  }

  a { text-decoration: none; color: inherit; transition: 0.3s; cursor: pointer; }
  ul { list-style: none; }
  
  .container { max-width: 1200px; margin: 0 auto; padding: 0 20px; }

  .btn {
    display: inline-block;
    padding: 14px 28px;
    font-family: 'Oswald', sans-serif;
    text-transform: uppercase;
    font-weight: 500;
    letter-spacing: 1px;
    cursor: pointer;
    border: 1px solid transparent;
    transition: all 0.3s ease;
    text-align: center;
  }
  .btn-primary { background-color: var(--accent-gold); color: #000; }
  .btn-primary:hover { background-color: var(--text-main); }
  .btn-outline { border-color: var(--text-main); color: var(--text-main); background: transparent; }
  .btn-outline:hover { background: var(--text-main); color: #000; }

  .text-gold { color: var(--accent-gold); }
  .section-title {
    font-size: 2.5rem;
    margin-bottom: 1rem;
    border-left: 4px solid var(--accent-gold);
    padding-left: 20px;
  }

  /* Fade Section */
  .fade-section {
    opacity: 0;
    transform: translateY(30px);
    transition: opacity 0.8s ease-out, transform 0.8s ease-out;
  }
  .fade-section.visible { opacity: 1; transform: translateY(0); }

  /* Navbar */
  nav {
    position: fixed; top: 0; width: 100%;
    background: rgba(5, 5, 5, 0.9);
    backdrop-filter: blur(10px);
    border-bottom: 1px solid var(--border-color);
    z-index: 1000; padding: 15px 0;
  }
  .nav-content { display: flex; justify-content: space-between; align-items: center; }
  .logo { 
    font-family: 'Oswald', sans-serif; font-size: 1.5rem; font-weight: 700; letter-spacing: 2px; 
    display: flex; align-items: center; cursor: pointer;
  }
  .logo img { height: 40px; width: auto; }
  .nav-links { display: flex; gap: 30px; align-items: center; }
  .nav-links a { font-size: 0.9rem; color: var(--text-muted); font-weight: 500; }
  .nav-links a:hover { color: var(--accent-gold); }
  .nav-cta {
    border: 1px solid var(--accent-gold); color: var(--accent-gold);
    padding: 8px 16px; font-size: 0.85rem;
  }
  .nav-cta:hover { background: var(--accent-gold); color: #000; }

  /* Hero */
  #hero {
    min-height: 100vh; display: flex; align-items: center;
    padding-top: 80px; position: relative;
  }
  .hero-grid { display: grid; grid-template-columns: 1.2fr 0.8fr; gap: 50px; align-items: center; width: 100%; }
  .hero-content h1 { font-size: 4rem; line-height: 1.1; margin-bottom: 20px; }
  .hero-sub { font-size: 1.1rem; color: var(--text-muted); margin-bottom: 40px; max-width: 90%; }
  .hero-buttons { display: flex; gap: 20px; margin-bottom: 15px; }
  
  .hero-panel {
    background: #000; border: 1px solid var(--border-color); height: 400px;
    position: relative; display: flex; justify-content: center; align-items: center;
    flex-direction: column; box-shadow: 0 20px 50px rgba(0,0,0,0.8);
    overflow: hidden; cursor: pointer; transition: border-color 0.3s;
  }
  .hero-panel:hover { border-color: var(--accent-gold); }
  .hero-panel iframe { width: 100%; height: 100%; border: none; }
  
  .play-icon {
    width: 60px; height: 60px; border: 2px solid var(--accent-gold); border-radius: 50%;
    display: flex; justify-content: center; align-items: center; margin-bottom: 15px; z-index: 2;
    transition: transform 0.3s;
  }
  .hero-panel:hover .play-icon { transform: scale(1.1); }
  .play-triangle {
    width: 0; height: 0; 
    border-top: 8px solid transparent; border-bottom: 8px solid transparent;
    border-left: 12px solid var(--accent-gold); margin-left: 4px;
  }

  /* Sections */
  section { padding: var(--spacing-section) 0; border-bottom: 1px solid #111; }
  .grid-3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 30px; margin-top: 40px; }
  .grid-4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-top: 40px; }
  
  .reason-card { border-top: 1px solid var(--accent-gold); padding-top: 20px; }
  .role-card {
    background: var(--card-bg); padding: 30px; border: 1px solid var(--border-color); transition: 0.3s;
  }
  .role-card:hover { border-color: var(--accent-gold); transform: translateY(-5px); }
  .role-list li {
    font-size: 0.85rem; color: var(--text-muted); margin-bottom: 8px; padding-left: 15px; position: relative;
  }
  .role-list li::before { content: '•'; color: var(--accent-gold); position: absolute; left: 0; }
  
  .timeline { display: flex; justify-content: space-between; margin-top: 50px; position: relative; }
  .timeline::before {
    content: ''; position: absolute; top: 20px; left: 0; width: 100%; height: 1px; background: #222; z-index: 0;
  }
  .timeline-step { background: var(--bg-color); z-index: 1; padding-right: 20px; width: 23%; }
  
  /* Rituals */
  .ritual-card {
    display: flex; align-items: flex-start; gap: 20px; margin-bottom: 30px;
    background: linear-gradient(90deg, #111 0%, transparent 100%);
    padding: 20px; border-left: 2px solid var(--border-color);
  }

  /* Code */
  .code-list { counter-reset: code-counter; margin: 40px 0; }
  .code-item { position: relative; padding-left: 50px; margin-bottom: 25px; }
  .code-item::before {
    counter-increment: code-counter; content: "0" counter(code-counter);
    position: absolute; left: 0; top: 2px; font-family: 'Oswald', sans-serif;
    color: var(--accent-gold); font-size: 1.2rem;
  }
  .warning-bar {
    background: rgba(74, 27, 27, 0.3); border-top: 1px solid var(--accent-red);
    border-bottom: 1px solid var(--accent-red); color: #ffaaaa; text-align: center;
    padding: 15px; font-family: 'Oswald', sans-serif; letter-spacing: 1px;
    text-transform: uppercase; font-size: 0.9rem; margin-top: 40px;
  }

  /* Map */
  .map-container {
    position: relative; width: 100%; height: 400px; background: #0e0e0e;
    border: 1px solid var(--border-color); margin-top: 40px; overflow: hidden;
  }
  .map-grid {
    position: absolute; width: 100%; height: 100%;
    background-image: linear-gradient(#1a1a1a 1px, transparent 1px), linear-gradient(90deg, #1a1a1a 1px, transparent 1px);
    background-size: 40px 40px; opacity: 0.3;
  }
  .map-dot {
    position: absolute; width: 10px; height: 10px; background: var(--accent-gold);
    border-radius: 50%; box-shadow: 0 0 10px var(--accent-gold);
    animation: pulse 3s infinite;
  }
  .dot-1 { top: 40%; left: 65%; animation-delay: 0s; }
  .dot-2 { top: 55%; left: 72%; animation-delay: 0.5s; }
  .dot-3 { top: 52%; left: 74%; animation-delay: 1s; }
  .dot-4 { top: 30%; left: 20%; animation-delay: 1.5s; }
  .dot-5 { top: 35%; left: 50%; animation-delay: 2s; }
  .map-label {
    position: absolute; color: #fff; font-size: 0.7rem; text-transform: uppercase;
    transform: translate(15px, -5px); opacity: 0.6;
  }

  /* FAQ */
  .faq-grid {
    display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-bottom: 60px;
  }
  .faq-item h4 { color: var(--accent-gold); margin-bottom: 10px; font-size: 1rem; }
  .faq-item p { color: var(--text-muted); font-size: 0.9rem; }

  /* Form */
  input, select, textarea {
    width: 100%; background: #050505; border: 1px solid #333; color: white;
    padding: 12px; font-family: 'Inter', sans-serif; font-size: 0.95rem; transition: 0.3s;
  }
  input:focus, select:focus, textarea:focus { outline: none; border-color: var(--accent-gold); }
  .form-row { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px; }
  
  /* Scroll to top */
  .scroll-top {
    position: fixed; bottom: 30px; right: 30px; width: 50px; height: 50px;
    background: rgba(5,5,5,0.7); backdrop-filter: blur(5px);
    border: 1px solid var(--accent-gold); color: var(--accent-gold);
    display: flex; justify-content: center; align-items: center;
    cursor: pointer; z-index: 999; opacity: 0; pointer-events: none;
    transition: opacity 0.4s, transform 0.4s;
    border-radius: 50%;
  }
  .scroll-top.visible { opacity: 1; pointer-events: auto; }
  .scroll-top:hover { background: var(--accent-gold); color: black; transform: translateY(-3px); }

  /* Admin */
  .admin-panel { padding: 40px; background: #080808; min-height: 100vh; }
  .admin-table { width: 100%; border-collapse: collapse; margin-top: 20px; font-size: 0.85rem; }
  .admin-table th, .admin-table td { padding: 12px; text-align: left; border-bottom: 1px solid #222; }
  .admin-table th { color: var(--accent-gold); }
  .admin-table tr:hover { background: #111; }
  
  .modal-overlay {
    position: fixed; top: 0; left: 0; width: 100%; height: 100%;
    background: rgba(0,0,0,0.8); z-index: 2000;
    display: flex; justify-content: center; align-items: center;
  }
  .modal-content {
    background: #111; border: 1px solid var(--accent-gold); padding: 40px;
    max-width: 800px; width: 90%; max-height: 90vh; overflow-y: auto;
    position: relative;
  }

  @media (max-width: 768px) {
    .hero-grid, .grid-3, .grid-4, .timeline, .form-row, .faq-grid {
      grid-template-columns: 1fr;
    }
    .hero-content h1 { font-size: 2.5rem; }
    .nav-links { display: none; }
    .timeline::before { display: none; }
    .timeline-step { width: 100%; margin-bottom: 30px; }
  }
`;

// --- LOGO COMPONENT ---
const Logo = () => {
  const [error, setError] = useState(false);
  const logoUrl = "business_syndicate_logo_new.jpg";

  if (error) {
    return <span style={{ fontFamily: 'Oswald', fontSize: '1.5rem', fontWeight: 700, letterSpacing: '2px', color: 'white' }}>BUSINESS SYNDICATE</span>;
  }

  return (
    <img 
      src={logoUrl} 
      alt="Business Syndicate" 
      onError={() => setError(true)}
      style={{ height: '40px', width: 'auto' }}
    />
  );
};

// --- ADMIN PANEL COMPONENT ---
const AdminPanel = ({ onClose }) => {
  const [password, setPassword] = useState('');
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [applicants, setApplicants] = useState([]);
  const [videoUrl, setVideoUrl] = useState('');
  const [selectedApplicant, setSelectedApplicant] = useState(null);
  const [loading, setLoading] = useState(false);
  
  // Pagination
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 10;

  const fetchApplicants = async () => {
    setLoading(true);
    try {
      const res = await fetch('api/applicants.php');
      const data = await res.json();
      if(Array.isArray(data)) setApplicants(data);
    } catch (e) {
      console.error("Failed to load applicants", e);
    } finally {
      setLoading(false);
    }
  };

  const fetchVideo = async () => {
    try {
      const res = await fetch('api/video.php');
      const data = await res.json();
      if(data.url) setVideoUrl(data.url);
    } catch(e) {}
  };

  useEffect(() => {
    if(isAuthenticated) {
        fetchApplicants();
        fetchVideo();
    }
  }, [isAuthenticated]);

  const handleLogin = () => {
    if (password === 'admin@123#') {
      setIsAuthenticated(true);
      setCurrentPage(1);
    } else {
      alert('Access Denied.');
    }
  };

  const saveVideo = async () => {
    try {
        await fetch('api/video.php', {
            method: 'POST',
            body: JSON.stringify({ url: videoUrl })
        });
        alert('Video URL updated');
    } catch(e) {
        alert('Failed to save');
    }
  };

  const downloadCSV = () => {
    // Sort by timestamp descending
    const sorted = [...applicants].sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
    
    const headers = ["Date", "Name", "Email", "Phone", "Location", "LinkedIn", "Instagram", "Role", "Business", "Revenue", "Team", "Challenges", "Contribution", "Score"];
    const rows = sorted.map(a => [
      new Date(parseInt(a.timestamp) * 1000).toLocaleDateString(),
      `"${a.fullName}"`, a.email, a.phone, `"${a.location}"`, a.linkedin, a.instagram,
      a.role, `"${a.businessName}"`, a.revenue, a.teamSize,
      `"${(a.challenges || '').replace(/"/g, '""')}"`, `"${(a.contribution || '').replace(/"/g, '""')}"`, a.score
    ]);

    const csvContent = "data:text/csv;charset=utf-8," 
      + headers.join(",") + "\n" 
      + rows.map(e => e.join(",")).join("\n");

    const encodedUri = encodeURI(csvContent);
    const link = document.createElement("a");
    link.setAttribute("href", encodedUri);
    link.setAttribute("download", `syndicate_applicants_${new Date().toISOString().slice(0,10)}.csv`);
    document.body.appendChild(link);
    link.click();
  };

  if (!isAuthenticated) {
    return (
      <div className="admin-panel" style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
        <div style={{ background: '#111', padding: '40px', border: '1px solid #333', textAlign: 'center' }}>
          <div style={{ marginBottom: '20px', display: 'flex', justifyContent: 'center' }}><Logo /></div>
          <h3>Restricted Access</h3>
          <input 
            type="password" 
            placeholder="Passkey" 
            value={password}
            onChange={e => setPassword(e.target.value)}
            style={{ margin: '20px 0' }}
          />
          <button className="btn btn-primary" onClick={handleLogin}>Enter</button>
          <button className="btn btn-outline" style={{ marginTop: '10px', marginLeft: '10px' }} onClick={onClose}>Exit</button>
        </div>
      </div>
    );
  }

  // Pagination Logic
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentApplicants = applicants.slice(indexOfFirstItem, indexOfLastItem);
  const totalPages = Math.ceil(applicants.length / itemsPerPage);

  return (
    <div className="admin-panel">
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '40px' }}>
        <h2>Syndicate Mainframe</h2>
        <div>
          <button className="btn btn-primary" onClick={downloadCSV} style={{ marginRight: '15px' }}>Export CSV</button>
          <button className="btn btn-outline" onClick={onClose}>Exit</button>
        </div>
      </div>

      <div style={{ background: '#111', padding: '20px', marginBottom: '40px', border: '1px solid #333' }}>
        <h4 style={{ color: 'var(--accent-gold)', marginBottom: '15px' }}>Configuration</h4>
        <div style={{ display: 'flex', gap: '10px' }}>
          <input 
            placeholder="Hero Video URL (YouTube Embed or MP4)" 
            value={videoUrl} 
            onChange={e => setVideoUrl(e.target.value)} 
          />
          <button className="btn btn-outline" onClick={saveVideo}>Save Video</button>
        </div>
      </div>

      <h4 style={{ color: 'var(--text-muted)' }}>
          Applicant Database ({applicants.length}) {loading && <span style={{fontSize:'0.8rem', color:'yellow'}}> Syncing...</span>}
      </h4>
      <div style={{ overflowX: 'auto' }}>
        <table className="admin-table">
          <thead>
            <tr>
              <th>Date</th>
              <th>Identity</th>
              <th>Business Profile</th>
              <th>Score</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            {currentApplicants.map((app, idx) => (
              <tr key={idx}>
                <td>{new Date(parseInt(app.timestamp) * 1000).toLocaleDateString()}</td>
                <td>
                  <div style={{ fontWeight: 'bold', color: 'white' }}>{app.fullName}</div>
                  <div style={{ color: '#888' }}>{app.email}</div>
                  <div style={{ color: '#888' }}>{app.location}</div>
                  <div style={{ fontSize: '0.75rem', marginTop: '4px' }}>
                    {app.linkedin && <a href={app.linkedin} target="_blank" style={{ color: 'var(--accent-gold)', marginRight:'8px' }}>LN</a>}
                    {app.instagram && <a href={`https://instagram.com/${app.instagram.replace('@','')}`} target="_blank" style={{ color: 'var(--accent-gold)' }}>IG</a>}
                  </div>
                </td>
                <td>
                  <div style={{ color: 'var(--accent-gold)' }}>{app.role.toUpperCase()}</div>
                  <div>{app.businessName}</div>
                  <div style={{ color: '#666', fontSize: '0.8rem' }}>{app.revenue} • {app.teamSize} Team</div>
                </td>
                <td>
                  <span style={{ 
                    padding: '2px 6px', 
                    background: app.score > 75 ? 'var(--accent-gold)' : '#333',
                    color: app.score > 75 ? 'black' : 'white',
                    fontWeight: 'bold'
                  }}>
                    {app.score}
                  </span>
                </td>
                <td>
                  <button 
                    style={{ background: 'none', border: '1px solid #444', color: '#ccc', padding: '4px 8px', cursor: 'pointer' }}
                    onClick={() => setSelectedApplicant(app)}
                  >
                    VIEW FULL
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Pagination Controls */}
      <div style={{ marginTop: '20px', display: 'flex', justifyContent: 'center', gap: '10px' }}>
        <button 
          className="btn btn-outline" 
          disabled={currentPage === 1}
          onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
          style={{ padding: '8px 16px', opacity: currentPage === 1 ? 0.5 : 1 }}
        >
          Previous
        </button>
        <span style={{ display: 'flex', alignItems: 'center', color: '#888' }}>
          Page {currentPage} of {totalPages || 1}
        </span>
        <button 
          className="btn btn-outline" 
          disabled={currentPage === totalPages || totalPages === 0}
          onClick={() => setCurrentPage(prev => Math.min(prev + 1, totalPages))}
          style={{ padding: '8px 16px', opacity: (currentPage === totalPages || totalPages === 0) ? 0.5 : 1 }}
        >
          Next
        </button>
      </div>

      {selectedApplicant && (
        <div className="modal-overlay" onClick={() => setSelectedApplicant(null)}>
          <div className="modal-content" onClick={e => e.stopPropagation()}>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '20px' }}>
              <h2 style={{ color: 'var(--accent-gold)' }}>Applicant Dossier</h2>
              <button onClick={() => setSelectedApplicant(null)} style={{ background: 'none', border: 'none', color: 'white', fontSize: '1.5rem', cursor: 'pointer' }}>×</button>
            </div>
            
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '40px', marginBottom: '30px' }}>
              <div>
                <h4 style={{ borderBottom: '1px solid #333', paddingBottom: '10px', marginBottom: '15px' }}>Identity</h4>
                <p><strong>Name:</strong> {selectedApplicant.fullName}</p>
                <p><strong>Email:</strong> {selectedApplicant.email}</p>
                <p><strong>Phone:</strong> {selectedApplicant.phone}</p>
                <p><strong>Location:</strong> {selectedApplicant.location}</p>
                <p><strong>LinkedIn:</strong> {selectedApplicant.linkedin || 'N/A'}</p>
                <p><strong>Instagram:</strong> {selectedApplicant.instagram || 'N/A'}</p>
              </div>
              <div>
                <h4 style={{ borderBottom: '1px solid #333', paddingBottom: '10px', marginBottom: '15px' }}>Business</h4>
                <p><strong>Role:</strong> {selectedApplicant.role}</p>
                <p><strong>Company:</strong> {selectedApplicant.businessName}</p>
                <p><strong>Revenue:</strong> {selectedApplicant.revenue}</p>
                <p><strong>Team Size:</strong> {selectedApplicant.teamSize}</p>
                <p><strong>Entry Score:</strong> {selectedApplicant.score}/100</p>
              </div>
            </div>

            <h4 style={{ color: 'var(--accent-gold)', marginBottom: '10px' }}>Challenges</h4>
            <p style={{ background: '#050505', padding: '15px', border: '1px solid #222', marginBottom: '20px', whiteSpace: 'pre-wrap' }}>
              {selectedApplicant.challenges}
            </p>

            <h4 style={{ color: 'var(--accent-gold)', marginBottom: '10px' }}>Contribution</h4>
            <p style={{ background: '#050505', padding: '15px', border: '1px solid #222', whiteSpace: 'pre-wrap' }}>
              {selectedApplicant.contribution}
            </p>
          </div>
        </div>
      )}
    </div>
  );
};

// --- MAIN APP COMPONENT ---
function App() {
  const [isAdminOpen, setAdminOpen] = useState(false);
  const [showScrollTop, setShowScrollTop] = useState(false);
  const [role, setRole] = useState('');
  
  // Hero Video State
  const [heroVideoUrl, setHeroVideoUrl] = useState('');
  const [isVideoPlaying, setIsVideoPlaying] = useState(false);

  // Form State
  const [formState, setFormState] = useState('form');
  const [formData, setFormData] = useState({});
  const [phrase, setPhrase] = useState('');
  const [phraseError, setPhraseError] = useState(false);
  const [score, setScore] = useState(0);

  useEffect(() => {
    // Styles Injection
    const styleEl = document.createElement('style');
    styleEl.innerHTML = styles;
    document.head.appendChild(styleEl);

    // Scroll Observer
    const handleScroll = () => {
      if (window.scrollY > 400) setShowScrollTop(true);
      else setShowScrollTop(false);
    };
    window.addEventListener('scroll', handleScroll);

    // Fade Observer
    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) entry.target.classList.add('visible');
      });
    }, { threshold: 0.1 });
    
    document.querySelectorAll('.fade-section').forEach(el => observer.observe(el));

    // Video Config - Load from API
    fetch('api/video.php')
        .then(res => res.json())
        .then(data => { if(data.url) setHeroVideoUrl(data.url) })
        .catch(err => console.log('Video fetch error', err));

    return () => {
      window.removeEventListener('scroll', handleScroll);
      observer.disconnect();
    };
  }, []);

  const scrollToTop = () => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const scrollToSection = (id) => {
    const el = document.getElementById(id);
    if (el) {
      // Offset for fixed header
      const headerOffset = 70;
      const elementPosition = el.getBoundingClientRect().top;
      const offsetPosition = elementPosition + window.pageYOffset - headerOffset;
      window.scrollTo({ top: offsetPosition, behavior: "smooth" });
    }
  };

  const preSelectRole = (r) => {
    setRole(r);
    scrollToSection('apply');
  };

  const handleInputChange = (e) => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    
    // Code Phrase Check
    let cleanVal = phrase.trim();
    if ((cleanVal.startsWith('"') && cleanVal.endsWith('"')) || (cleanVal.startsWith("'") && cleanVal.endsWith("'"))) {
        cleanVal = cleanVal.slice(1, -1);
    }
    if (cleanVal !== "I sit at the table.") {
        setPhraseError(true);
        return;
    }
    setPhraseError(false);
    setFormState('processing');

    // Generate Score & Prepare Payload
    const finalScore = Math.floor(Math.random() * (85 - 55 + 1) + 55);
    setScore(finalScore);
    
    const newApplicant = {
        fullName: formData.fullName,
        email: formData.email,
        phone: formData.phone,
        location: formData.location,
        linkedin: formData.linkedin || '',
        instagram: formData.instagram || '',
        role: role || formData.role,
        businessName: formData.businessName,
        revenue: formData.revenue,
        teamSize: formData.teamSize,
        challenges: formData.challenges,
        contribution: formData.contribution,
        score: finalScore
    };

    // Send to PHP Backend
    try {
        const response = await fetch('api/submit.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(newApplicant)
        });
        
        if (response.ok) {
            setTimeout(() => setFormState('done'), 1500); // Slight delay for effect
        } else {
            alert("Connection error. Please try again.");
            setFormState('form');
        }
    } catch(error) {
        console.error("Submission failed", error);
        alert("Server error. Please try again.");
        setFormState('form');
    }
  };

  if (isAdminOpen) {
    return <AdminPanel onClose={() => setAdminOpen(false)} />;
  }

  return (
    <>
      <nav>
        <div className="container nav-content">
          <div className="logo" onClick={scrollToTop}>
            <Logo />
          </div>
          <div className="nav-links">
            <a onClick={() => scrollToSection('why')}>Why</a>
            <a onClick={() => scrollToSection('who')}>Who</a>
            <a onClick={() => scrollToSection('inside')}>Inside</a>
            <a onClick={() => scrollToSection('code')}>The Code</a>
            <a onClick={() => scrollToSection('apply')} className="nav-cta">Request to Join</a>
          </div>
        </div>
      </nav>

      {/* Hero */}
      <header id="hero">
        <div className="container hero-grid fade-section">
          <div className="hero-content">
            <h1>WHERE SERIOUS OPERATORS<br/>SIT AT THE SAME TABLE.</h1>
            <p className="hero-sub">A private circle for business owners, entrepreneurs, and investors who are tired of noise and want real conversations, real deals, and real people.</p>
            <div className="hero-buttons">
              <a onClick={() => scrollToSection('apply')} className="btn btn-primary">Request to Join</a>
              <a onClick={() => scrollToSection('code')} className="btn btn-outline">Read The Code</a>
            </div>
            <p style={{ fontSize: '0.75rem', color: '#888', opacity: 0.7 }}>Entry is curated. Not everyone gets in.</p>
          </div>
          
          <div className="hero-panel" onClick={() => setIsVideoPlaying(true)}>
            {isVideoPlaying && heroVideoUrl ? (
              <iframe src={heroVideoUrl} title="Hero Video" allow="autoplay; encrypted-media"></iframe>
            ) : (
              <>
                <div className="play-icon">
                  <div className="play-triangle"></div>
                </div>
                {isVideoPlaying ? (
                   <p style={{ color: 'var(--accent-gold)', fontWeight: 'bold', animation: 'pulse 1s infinite' }}>NOW STREAMING...</p>
                ) : (
                  <p style={{ fontSize: '0.8rem', letterSpacing: '2px', textTransform: 'uppercase' }}>Not a networking group.<br/>A table.</p>
                )}
              </>
            )}
          </div>
        </div>
      </header>

      {/* Why */}
      <section id="why">
        <div className="container fade-section">
          <h2 className="section-title">WHY THIS SYNDICATE EXISTS</h2>
          <div style={{ maxWidth: '800px', marginBottom: '40px', color: '#888' }}>
            <p style={{ marginBottom: '20px' }}>Most business groups are noisy, salesy, or fake. You walk into a room and everyone is trying to pitch you something you don't need, or they are "wantrepreneurs" with no skin in the game.</p>
            <p>Operators need a place to talk about real issues: cashflow crunches, firing senior staff, regulatory battles, and exit strategies. These aren't conversations you have on LinkedIn.</p>
            <p>Business Syndicate is built for people who have payroll to meet and equity on the line.</p>
          </div>
          <div className="grid-3">
            <div className="reason-card"><h4>NO FLUFF, JUST OPERATORS</h4><p style={{ color: '#888', fontSize: '0.9rem' }}>We verify business ownership and operational roles. No life coaches, no multi-level marketers.</p></div>
            <div className="reason-card"><h4>CROSS-INDUSTRY INTEL</h4><p style={{ color: '#888', fontSize: '0.9rem' }}>Learn how a manufacturer solves supply chain issues and apply it to your software scaling.</p></div>
            <div className="reason-card"><h4>CONFIDENTIALITY FIRST</h4><p style={{ color: '#888', fontSize: '0.9rem' }}>What is said at the table stays at the table. A safe harbor for hard truths.</p></div>
          </div>
        </div>
      </section>

      {/* Who */}
      <section id="who">
        <div className="container fade-section">
          <h2 className="section-title">WHO WE LET INSIDE</h2>
          <div className="grid-4">
            <div className="role-card">
                <h3>THE BUILDER</h3><div style={{ fontSize:'0.9rem', marginBottom:'20px', minHeight:'40px' }}>Founders currently building a product or service from 0 to 1.</div>
                <ul className="role-list"><li>Seeking rapid feedback loops</li><li>Needs tactical hiring advice</li><li>Building MVP or Early Growth</li></ul>
                <a onClick={() => preSelectRole('builder')} style={{ display:'block', marginTop:'20px', fontSize:'0.8rem', textTransform:'uppercase', borderBottom:'1px solid #333', paddingBottom:'5px' }}>Apply as Builder &rarr;</a>
            </div>
            <div className="role-card">
                <h3>THE OWNER</h3><div style={{ fontSize:'0.9rem', marginBottom:'20px', minHeight:'40px' }}>Established business owners with revenue and teams.</div>
                <ul className="role-list"><li>Focus on systems & scale</li><li>Managing cashflow & margin</li><li>Looking at M&A or Exit</li></ul>
                <a onClick={() => preSelectRole('owner')} style={{ display:'block', marginTop:'20px', fontSize:'0.8rem', textTransform:'uppercase', borderBottom:'1px solid #333', paddingBottom:'5px' }}>Apply as Owner &rarr;</a>
            </div>
            <div className="role-card">
                <h3>THE OPERATOR</h3><div style={{ fontSize:'0.9rem', marginBottom:'20px', minHeight:'40px' }}>Key managers, GMs, and COOs running the show.</div>
                <ul className="role-list"><li>Execution focused</li><li>Managing large teams</li><li>Optimizing P&L</li></ul>
                <a onClick={() => preSelectRole('operator')} style={{ display:'block', marginTop:'20px', fontSize:'0.8rem', textTransform:'uppercase', borderBottom:'1px solid #333', paddingBottom:'5px' }}>Apply as Operator &rarr;</a>
            </div>
            <div className="role-card">
                <h3>THE INVESTOR</h3><div style={{ fontSize:'0.9rem', marginBottom:'20px', minHeight:'40px' }}>Individuals with capital or strategic expertise.</div>
                <ul className="role-list"><li>Seeking deal flow</li><li>Backing verified operators</li><li>Mentoring for equity</li></ul>
                <a onClick={() => preSelectRole('investor')} style={{ display:'block', marginTop:'20px', fontSize:'0.8rem', textTransform:'uppercase', borderBottom:'1px solid #333', paddingBottom:'5px' }}>Apply as Investor &rarr;</a>
            </div>
          </div>
        </div>
      </section>

      {/* Inside */}
      <section id="inside">
        <div className="container fade-section">
          <h2 className="section-title">INSIDE THE SYNDICATE</h2>
          <div className="timeline">
            <div className="timeline-step"><div style={{ fontSize:'2rem', color:'var(--accent-gold-dim)', fontFamily:'Oswald' }}>01</div><h4>ENTER</h4><p style={{ fontSize:'0.9rem', color:'#888' }}>Get vetted by the Shadow Board. Sign the NDA. Join your specific sector table.</p></div>
            <div className="timeline-step"><div style={{ fontSize:'2rem', color:'var(--accent-gold-dim)', fontFamily:'Oswald' }}>02</div><h4>CONNECT</h4><p style={{ fontSize:'0.9rem', color:'#888' }}>Access the member directory. Direct lines to suppliers, potential partners, and advisors.</p></div>
            <div className="timeline-step"><div style={{ fontSize:'2rem', color:'var(--accent-gold-dim)', fontFamily:'Oswald' }}>03</div><h4>CONTRIBUTE</h4><p style={{ fontSize:'0.9rem', color:'#888' }}>Bring your challenges to the Firepit. Offer your expertise to others. Earn trust.</p></div>
            <div className="timeline-step"><div style={{ fontSize:'2rem', color:'var(--accent-gold-dim)', fontFamily:'Oswald' }}>04</div><h4>COLLABORATE</h4><p style={{ fontSize:'0.9rem', color:'#888' }}>Form JVs. Invest in deals. Hire vetted talent. Execute together.</p></div>
          </div>
        </div>
      </section>

      {/* Rituals */}
      <section>
        <div className="container fade-section">
          <h2 className="section-title">SYNDICATE RITUALS</h2>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))', gap: '30px', marginTop: '40px' }}>
             <div className="ritual-card"><div style={{ fontSize:'1.5rem', color:'var(--accent-gold)' }}>&#9632;</div><div><h4>BLACK TABLE NIGHT</h4><p style={{ color:'#888', fontSize:'0.9rem' }}>A mini-mastermind. 6 members, 1 table, deep dive into one specific strategic bottleneck.</p></div></div>
             <div className="ritual-card"><div style={{ fontSize:'1.5rem', color:'var(--accent-gold)' }}>&#9670;</div><div><h4>THE DEAL ROOM</h4><p style={{ color:'#888', fontSize:'0.9rem' }}>Curated investment opportunities, partnership offers, and business-for-sale listings.</p></div></div>
             <div className="ritual-card"><div style={{ fontSize:'1.5rem', color:'var(--accent-gold)' }}>&#9650;</div><div><h4>THE FIREPIT</h4><p style={{ color:'#888', fontSize:'0.9rem' }}>Anonymous failure stories. We share the scars so others don't have to bleed.</p></div></div>
             <div className="ritual-card"><div style={{ fontSize:'1.5rem', color:'var(--accent-gold)' }}>&#10010;</div><div><h4>OPERATOR'S CLINIC</h4><p style={{ color:'#888', fontSize:'0.9rem' }}>20-minute hot seat. The group dissects your current operational problem and offers solutions.</p></div></div>
          </div>
        </div>
      </section>

      {/* Code */}
      <section id="code">
        <div className="container fade-section">
          <h2 className="section-title">THE SYNDICATE CODE</h2>
          <div className="code-list">
            <div className="code-item"><h4>CONFIDENTIALITY IS ABSOLUTE</h4><p>What happens at the table, stays at the table. Breach this and you are blacklisted.</p></div>
            <div className="code-item"><h4>GIVE BEFORE YOU TAKE</h4><p>Come with value. Offer introductions, advice, or perspective before you ask for favors.</p></div>
            <div className="code-item"><h4>NO FAKE FLEX</h4><p>We know what real success looks like. Check your ego at the door. Be raw, be real.</p></div>
            <div className="code-item"><h4>RESPECT THE COMMITMENT</h4><p>If you say you will do something, it gets done. If you book a seat, you show up.</p></div>
          </div>
          <div className="warning-bar">If you are here only to sell, spam, or seek validation, this is not your table.</div>
        </div>
      </section>

      {/* Shadow Board + Map */}
      <section>
        <div className="container fade-section">
          <h2 className="section-title">THE SHADOW BOARD</h2>
          <p style={{ maxWidth:'700px', color:'#888', marginBottom:'30px' }}>Applications are reviewed by a small council of experienced operators. Their identities are not publicly listed.</p>
          <div style={{ background:'#111', padding:'20px', borderLeft:'3px solid var(--accent-gold)' }}>
             <h4 style={{ color:'white', marginBottom:'5px' }}>THE INNER CIRCLE</h4>
             <p style={{ fontSize:'0.9rem', color:'#888' }}>A premium, invite-only tier within the Syndicate. Entry is by invitation only.</p>
          </div>
          <h2 className="section-title" style={{ marginTop:'80px' }}>WHERE THE SYNDICATE LIVES</h2>
          <div className="map-container">
             <div className="map-grid"></div>
             <div className="map-dot dot-1"><span className="map-label">Dubai</span></div>
             <div className="map-dot dot-2"><span className="map-label">Kochi</span></div>
             <div className="map-dot dot-3"><span className="map-label">Bangalore</span></div>
             <div className="map-dot dot-4"><span className="map-label">USA</span></div>
             <div className="map-dot dot-5"><span className="map-label">EU</span></div>
          </div>
        </div>
      </section>

      {/* FAQ */}
      <section>
        <div className="container fade-section">
           <div className="faq-grid">
              <div className="faq-item"><h4>Is there a fee to join?</h4><p>Yes. Quality filters price. If you have to ask "how much", you probably aren't ready.</p></div>
              <div className="faq-item"><h4>How long does review take?</h4><p>7-14 days. The Shadow Board meets bi-weekly. We don't rush vetting.</p></div>
              <div className="faq-item"><h4>Is this only for Kerala / India?</h4><p>No. We have operators in Dubai, UK, and the US. But the core ethos is grounded.</p></div>
              <div className="faq-item"><h4>Can I join if I haven't started yet?</h4><p>No. We don't babysit "idea guys". Build something, get revenue, then come back.</p></div>
           </div>
        </div>
      </section>

      {/* Application */}
      <section id="apply">
        <div className="container fade-section">
          <h2 className="section-title">REQUEST TO JOIN</h2>
          
          {formState === 'form' && (
            <form onSubmit={handleSubmit} style={{ background:'#0f0f0f', padding:'40px', border:'1px solid #222', maxWidth:'800px', margin:'0 auto' }}>
              <h4 style={{ marginBottom:'20px', color:'var(--accent-gold)' }}>01. Identity</h4>
              <div className="form-row">
                 <div><label style={{ display:'block', color:'#888', fontSize:'0.8rem', marginBottom:'5px' }}>Full Name</label><input name="fullName" onChange={handleInputChange} required /></div>
                 <div><label style={{ display:'block', color:'#888', fontSize:'0.8rem', marginBottom:'5px' }}>Email</label><input name="email" type="email" onChange={handleInputChange} required /></div>
              </div>
              <div className="form-row">
                 <div><label style={{ display:'block', color:'#888', fontSize:'0.8rem', marginBottom:'5px' }}>Phone / WhatsApp</label><input name="phone" type="tel" onChange={handleInputChange} required /></div>
                 <div><label style={{ display:'block', color:'#888', fontSize:'0.8rem', marginBottom:'5px' }}>City & Country</label><input name="location" onChange={handleInputChange} required /></div>
              </div>
              <div className="form-row">
                 <div><label style={{ display:'block', color:'#888', fontSize:'0.8rem', marginBottom:'5px' }}>LinkedIn URL</label><input name="linkedin" type="url" onChange={handleInputChange} /></div>
                 <div><label style={{ display:'block', color:'#888', fontSize:'0.8rem', marginBottom:'5px' }}>Instagram Handle</label><input name="instagram" placeholder="@handle" onChange={handleInputChange} /></div>
              </div>

              <h4 style={{ margin:'30px 0 20px', color:'var(--accent-gold)' }}>02. Role & Business</h4>
              <div className="form-row">
                 <div><label style={{ display:'block', color:'#888', fontSize:'0.8rem', marginBottom:'5px' }}>Role</label>
                 <select name="role" value={role} onChange={(e) => { setRole(e.target.value); handleInputChange(e); }} required>
                    <option value="">Select...</option>
                    <option value="builder">The Builder</option>
                    <option value="owner">The Owner</option>
                    <option value="operator">The Operator</option>
                    <option value="investor">The Investor</option>
                 </select></div>
                 <div><label style={{ display:'block', color:'#888', fontSize:'0.8rem', marginBottom:'5px' }}>Business Name</label><input name="businessName" onChange={handleInputChange} required /></div>
              </div>
              <div className="form-row">
                 <div><label style={{ display:'block', color:'#888', fontSize:'0.8rem', marginBottom:'5px' }}>Revenue</label>
                 <select name="revenue" onChange={handleInputChange}>
                    <option>Pre-revenue</option>
                    <option>&lt; $100k</option>
                    <option>$100k - $1M</option>
                    <option>$1M - $10M</option>
                    <option>$10M+</option>
                 </select></div>
                 <div><label style={{ display:'block', color:'#888', fontSize:'0.8rem', marginBottom:'5px' }}>Team Size</label>
                 <select name="teamSize" onChange={handleInputChange}>
                    <option>Solo</option>
                    <option>2 - 10</option>
                    <option>11 - 50</option>
                    <option>50+</option>
                 </select></div>
              </div>

              <h4 style={{ margin:'30px 0 20px', color:'var(--accent-gold)' }}>03. Intent</h4>
              <div style={{ marginBottom:'20px' }}><label style={{ display:'block', color:'#888', fontSize:'0.8rem', marginBottom:'5px' }}>Top 2 Challenges?</label><textarea name="challenges" onChange={handleInputChange} required></textarea></div>
              <div style={{ marginBottom:'20px' }}><label style={{ display:'block', color:'#888', fontSize:'0.8rem', marginBottom:'5px' }}>What do you bring?</label><textarea name="contribution" onChange={handleInputChange} required></textarea></div>

              <div style={{ background:'#1a1a1a', padding:'20px', borderLeft:'2px solid var(--accent-gold)', marginBottom:'25px' }}>
                 <label style={{ color:'white', marginBottom:'10px', display:'block' }}>To confirm, type: <span style={{ color:'var(--accent-gold)' }}>"I sit at the table."</span></label>
                 <input value={phrase} onChange={e => setPhrase(e.target.value)} placeholder="Type phrase exactly..." style={{ borderColor: phraseError ? 'var(--accent-red)' : 'var(--accent-gold)' }} required />
                 {phraseError && <p style={{ color:'var(--accent-red)', fontSize:'0.8rem', marginTop:'5px' }}>Incorrect phrase.</p>}
              </div>

              <button type="submit" className="btn btn-primary" style={{ width:'100%' }}>Submit Application</button>
            </form>
          )}

          {formState === 'processing' && (
             <div style={{ padding:'60px', textAlign:'center', background:'#111', border:'1px solid #333' }}>
                <h3 style={{ animation:'pulse 1s infinite', color:'var(--accent-gold)' }}>PROCESSING APPLICATION...</h3>
                <p style={{ color:'#888', marginTop:'20px' }}>Encrypting data. Hashing to Shadow Board...</p>
             </div>
          )}

          {formState === 'done' && (
             <div style={{ padding:'40px', background:'#0f0f0f', border:'1px solid #333', maxWidth:'800px', margin:'0 auto', textAlign:'center' }}>
                <div style={{ display:'inline-block', background:'#222', color:'var(--accent-gold)', padding:'5px 10px', fontSize:'0.8rem', letterSpacing:'1px', textTransform:'uppercase', marginBottom:'20px' }}>Application Received</div>
                <h3 style={{ marginBottom:'20px' }}>STATUS DOSSIER: #{Date.now().toString().slice(-6)}</h3>
                
                <div style={{ width:'120px', height:'120px', border:'4px solid var(--accent-gold)', borderRadius:'50%', display:'flex', justifyContent:'center', alignItems:'center', fontSize:'2.5rem', fontFamily:'Oswald', margin:'0 auto 30px auto', color:'white' }}>
                   {score}/100
                </div>
                
                <div style={{ textAlign:'left', borderTop:'1px solid #333', paddingTop:'30px', marginTop:'30px' }}>
                   <h4 style={{ color:'var(--accent-gold)', marginBottom:'15px' }}>NEXT STEPS PROTOCOL</h4>
                   <div style={{ marginBottom:'15px' }}><strong style={{ color:'white' }}>01. Shadow Board Review:</strong> <span style={{ color:'#888' }}>Manual verification of revenue and role (48-72 hours).</span></div>
                   <div style={{ marginBottom:'15px' }}><strong style={{ color:'white' }}>02. Background Check:</strong> <span style={{ color:'#888' }}>Digital footprint analysis to ensure no fake guru history.</span></div>
                   <div style={{ marginBottom:'15px' }}><strong style={{ color:'white' }}>03. Final Decision:</strong> <span style={{ color:'#888' }}>If accepted, you receive an encrypted invite link via email.</span></div>
                </div>

                <button onClick={() => window.print()} className="btn btn-outline" style={{ marginTop:'30px', fontSize:'0.8rem' }}>PRINT REFERENCE</button>
             </div>
          )}
        </div>
      </section>

      {/* Founder Strip */}
      <section style={{ padding:'40px 0', borderTop:'1px solid #222', background:'#080808' }}>
         <div className="container">
            <h4 style={{ fontSize:'0.9rem', color:'#666', marginBottom:'15px' }}>FROM THE FOUNDER</h4>
            <div style={{ borderLeft:'2px solid var(--accent-gold)', paddingLeft:'20px', fontStyle:'italic', color:'#aaa' }}>
               <p>"I’ve built brands the hard way — no shortcuts, no family money.</p>
               <p>Business Syndicate is the room I wish I had 10 years ago.</p>
               <p>If you’re like that, you’ll feel at home here."</p>
               <div style={{ marginTop:'10px', fontStyle:'normal', color:'var(--accent-gold)', fontSize:'0.85rem' }}>- Kamarudheen PKM</div>
            </div>
         </div>
      </section>

      {/* Footer */}
      <footer>
        <div className="container" style={{ padding:'60px 0', borderTop:'1px solid #111', textAlign:'center' }}>
          <div style={{ display:'flex', justifyContent:'center', marginBottom:'20px' }}><Logo /></div>
          <p style={{ opacity:0.6 }}>For people who actually build.</p>
          
          <div style={{ marginTop:'30px' }}>
             <a href="https://instagram.com/businesssyndicate" target="_blank" className="btn btn-outline" style={{ display:'inline-flex', alignItems:'center', gap:'10px', fontSize:'0.8rem', padding:'10px 20px' }}>
               <span>INSTAGRAM</span>
             </a>
          </div>

          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', paddingTop:'40px', flexDirection:'column', gap:'20px' }}>
             <div style={{ fontSize:'0.8rem', color:'#444' }}>&copy; 2023 Syndicate. All Rights Reserved.</div>
             <div style={{ fontFamily:'Oswald', letterSpacing:'1px', color:'var(--accent-gold)' }}>STAY OUTSIDE. OR SIT AT THE TABLE.</div>
             <a onClick={() => setAdminOpen(true)} style={{ fontSize:'0.7rem', color:'#222', cursor:'pointer' }}>Admin Login</a>
          </div>
        </div>
      </footer>

      {/* Scroll Top */}
      <div 
         className={`scroll-top ${showScrollTop ? 'visible' : ''}`}
         onClick={scrollToTop}
      >
         &#8593;
      </div>
    </>
  );
}

const rootElement = document.getElementById('root');
if (rootElement) {
  const root = createRoot(rootElement);
  root.render(<App />);
}