function CaseStudiesPage() {
  const [filter, setFilter] = React.useState('all');
  const [search, setSearch] = React.useState('');
  const [visible, setVisible] = React.useState(30);
  const [cases, setCases] = React.useState([]);
  const [modal, setModal] = React.useState(false);

  React.useEffect(() => {
    fetch('./case-studies-data.json')
      .then(r => r.json())
      .then(data => {
        // Enrich each case with a category + normalized amount
        const enriched = data.map((c, i) => {
          const amt = c.amount || '';
          let numericValue = 0;
          const m = amt.match(/\$?([\d,.]+)\s*([KMkm])?/);
          if (m) {
            const n = parseFloat(m[1].replace(/,/g, ''));
            const mult = m[2] && /[Kk]/.test(m[2]) ? 1000 : (m[2] && /[Mm]/.test(m[2]) ? 1000000 : 1);
            numericValue = n * mult;
          }
          const isMRR = /\/mo|\/month/i.test(amt);
          const isFast = /(1\s*day|days?)/i.test(c.timeframe) && !/week|month/i.test(c.timeframe);
          const isBig = numericValue >= 100000;
          const hasAmount = numericValue > 0;

          // Pick category tag for visual variety
          const verb = (c.action.split(' ')[0] || '').toLowerCase();
          const cat = isMRR ? 'mrr' :
                     isBig ? 'big' :
                     verb === 'added' ? 'added' :
                     verb === 'closed' ? 'closed' :
                     verb === 'scaled' || verb === 'went' || verb === '3x' || verb === '10x' ? 'scaled' :
                     'other';

          return { ...c, numericValue, isMRR, isFast, isBig, cat, idx: i };
        });
        setCases(enriched);
      });
  }, []);

  // Filter + search
  const filtered = React.useMemo(() => {
    let r = cases;
    if (filter === 'big') r = r.filter(c => c.isBig);
    else if (filter === 'fast') r = r.filter(c => c.isFast);
    else if (filter === 'retainers') r = r.filter(c => /retainer/i.test(c.title));
    else if (filter === 'mrr') r = r.filter(c => c.isMRR);
    if (search.trim()) {
      const s = search.toLowerCase();
      r = r.filter(c => c.title.toLowerCase().includes(s));
    }
    return r;
  }, [cases, filter, search]);

  const counts = React.useMemo(() => ({
    all: cases.length,
    big: cases.filter(c => c.isBig).length,
    fast: cases.filter(c => c.isFast).length,
    retainers: cases.filter(c => /retainer/i.test(c.title)).length,
    mrr: cases.filter(c => c.isMRR).length,
  }), [cases]);

  // Aggregate stats
  const totalDeals = React.useMemo(() => {
    return cases.reduce((sum, c) => sum + (c.isMRR ? 0 : c.numericValue), 0);
  }, [cases]);

  const biggestDeal = React.useMemo(() => {
    return cases.filter(c => !c.isMRR).reduce((max, c) => c.numericValue > max.numericValue ? c : max, { numericValue: 0, name: '', amount: '' });
  }, [cases]);

  const shown = filtered.slice(0, visible);
  const canLoadMore = visible < filtered.length;

  const onCTA = () => setModal(true);

  return (
    <>
      <NavBar onCTA={onCTA}/>
      <main>
        <CasesHero stats={{ total: cases.length, deals: totalDeals, biggest: biggestDeal }}/>
        <CasesFilterBar
          filter={filter} setFilter={setFilter}
          search={search} setSearch={setSearch}
          counts={counts}
          resultCount={filtered.length}
        />
        <CasesGrid cases={shown} />
        {canLoadMore && (
          <div style={{ textAlign: 'center', padding: '48px 20px 0' }}>
            <button onClick={() => setVisible(v => v + 30)} style={{
              background: 'transparent', border: '1px solid rgba(255,255,255,0.18)',
              color: '#fff', padding: '14px 32px', borderRadius: 999,
              fontFamily: 'Poppins', fontWeight: 600, fontSize: 14,
              cursor: 'pointer',
            }}>Load {Math.min(30, filtered.length - visible)} more</button>
          </div>
        )}
        <section data-mf="section" style={{ padding: '80px 44px 40px', textAlign: 'center' }}>
          <p style={{
            maxWidth: 840, margin: '0 auto', fontSize: 13, lineHeight: 1.6,
            color: 'rgba(255,255,255,0.5)',
          }}>
            All testimonials on this page are from real clients. The results depicted are not typical
            and are not guaranteed. Success is highly dependent on individual effort, dedication, skills,
            and market conditions. The examples shown are intended to illustrate what some clients have
            achieved; your own results may vary based on these factors.
          </p>
        </section>
        <FinalCTA onCTA={onCTA}/>
      </main>
      <Footer/>

      {modal && <IClosedModal onClose={() => setModal(false)}/>}
    </>
  );
}
window.CaseStudiesPage = CaseStudiesPage;

function IClosedModal({ onClose }) {
  React.useEffect(() => {
    if (!document.querySelector('script[src*="app.iclosed.io/assets/widget.js"]')) {
      const s = document.createElement('script');
      s.src = 'https://app.iclosed.io/assets/widget.js';
      s.async = true;
      document.body.appendChild(s);
    } else if (window.iClosed && typeof window.iClosed.init === 'function') {
      try { window.iClosed.init(); } catch(e) {}
    }
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => {
      document.body.style.overflow = prev;
      window.removeEventListener('keydown', onKey);
    };
  }, [onClose]);

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.85)',
      display: 'flex', alignItems: 'flex-start', justifyContent: 'center', zIndex: 300,
      backdropFilter: 'blur(8px)', padding: 20,
      overflowY: 'auto', WebkitOverflowScrolling: 'touch',
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 'min(980px, 100%)', margin: 'auto', background: '#1A0A10',
        border: '1px solid rgba(255,255,255,0.1)', borderRadius: 20,
        position: 'relative', overflow: 'hidden',
        boxShadow: '0 40px 120px rgba(0,0,0,0.7)',
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: '18px 22px', borderBottom: '1px solid rgba(255,255,255,0.08)',
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <span style={{
              width: 8, height: 8, borderRadius: '50%', background: '#E8123C',
              boxShadow: '0 0 8px rgba(232,18,60,0.8)',
            }}/>
            <div style={{
              fontFamily: 'Poppins', fontWeight: 700, fontSize: 14,
              letterSpacing: '0.08em', color: '#fff', textTransform: 'uppercase',
            }}>Schedule Your Roadmap Call</div>
          </div>
          <button onClick={onClose} style={{
            width: 34, height: 34, border: 'none',
            background: 'rgba(255,255,255,0.08)', borderRadius: '50%',
            color: '#fff', fontSize: 18, cursor: 'pointer', lineHeight: 1,
          }}>×</button>
        </div>
        {/* iClosed inline widget begin */}
        <div
          className="iclosed-widget"
          data-url="https://app.iclosed.io/e/Edeeran/master-filmmaker-roadmap-call"
          title="Apply Now"
          style={{ width: '100%', height: 620 }}
        />
        {/* iClosed inline widget end */}

        <div style={{
          padding: '16px 22px 20px',
          borderTop: '1px solid rgba(255,255,255,0.08)',
          fontFamily: 'Poppins', fontSize: '8pt', lineHeight: 1.5,
          color: 'rgba(255,255,255,0.55)',
        }}>
          By submitting your information, you agree to receive marketing calls and text messages (including calls and texts sent using automated technology), and emails from Deeran Films LLC d/b/a Master Filmmaker at the contact information provided. This includes communications about this offer, related products or services, training content, and promotional updates. Consent is not a condition of purchase. Message and data rates may apply. You may unsubscribe from emails at any time by clicking the link in our emails, or opt out of texts by replying STOP. View our{' '}
          <a href="https://www.masterfilmmaker.com/termsofuse" target="_blank" rel="noopener noreferrer"
             style={{ color: 'rgba(255,255,255,0.85)', textDecoration: 'underline' }}>Terms of Use</a>
          {' '}and{' '}
          <a href="https://www.masterfilmmaker.com/terms-of-service" target="_blank" rel="noopener noreferrer"
             style={{ color: 'rgba(255,255,255,0.85)', textDecoration: 'underline' }}>Privacy Policy</a>.
        </div>
      </div>
    </div>
  );
}
window.IClosedModal = IClosedModal;
