(function() {
  var useState  = React.useState;
  var useRef    = React.useRef;
  var useEffect = React.useEffect;

  var COLORS = ['var(--lime)','var(--violet)','var(--cyan)','var(--amber)','var(--rose)'];

  function apiToFund(p, i) {
    var raised = p.funding && p.funding.raised || 0;
    var goal   = p.funding && p.funding.goal   || 1;
    var pct    = Math.min(100, Math.round((raised/goal)*100));
    return {
      _id:     p._id,
      name:    p.title,
      desc:    p.description ? p.description.slice(0,80)+(p.description.length>80?'…':'') : 'Community-funded city improvement project.',
      icon:    ['building','leaf','box','zap','sparkles','radio'][i%6],
      raised:  Math.round(raised/1000),
      target:  Math.round(goal/1000)||1,
      pct:     pct,
      backers: Math.floor(raised/800)||1,
      days:    Math.max(1, 30-Math.floor(pct/4)),
      color:   COLORS[i%COLORS.length],
    };
  }

  function Funding() {
    var _animated    = useState(false); var animated = _animated[0], setAnimated = _animated[1];
    var _projects    = useState(window.USER_FUND_PROJECTS||[]); var projects = _projects[0], setProjects = _projects[1];
    var _totalRaised = useState(2100000); var totalRaised = _totalRaised[0], setTotalRaised = _totalRaised[1];
    var ref = useRef(null);
    window.useReveal(ref);

    useEffect(function() {
      var obs = new IntersectionObserver(function(entries) {
        if (entries[0].isIntersecting) { setAnimated(true); obs.disconnect(); }
      }, { threshold:0.2 });
      if (ref.current) obs.observe(ref.current);
      return function() { obs.disconnect(); };
    }, []);

    useEffect(function() {
      if (!window.ApiClient) return;
      window.ApiClient.get('/projects?sort=-funding.raised&limit=6').then(function(d) {
        if (d && d.projects && d.projects.length) {
          setProjects(d.projects.map(apiToFund));
          setTotalRaised(d.projects.reduce(function(a,p){ return a+(p.funding&&p.funding.raised||0); }, 0));
        }
      }).catch(function(){});
    }, []);

    var displayTotal = totalRaised >= 1000000 ? '$'+(totalRaised/1000000).toFixed(1)+'M' : '$'+Math.round(totalRaised/1000)+'K';

    return (
      <div ref={ref}>
        <div className="section">
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:56, flexWrap:'wrap', gap:16 }}>
            <div>
              <div className="eyebrow reveal">Community Funding</div>
              <h2 className="heading-lg reveal rd1">Fund the Future<br /><span className="gradient-text">of Your City</span></h2>
            </div>
            <div className="reveal rd2" style={{ textAlign:'right', cursor:'none' }}
              onMouseEnter={function(){ document.body.classList.add('hov'); }}
              onMouseLeave={function(){ document.body.classList.remove('hov'); }}
              onClick={function(){ window.navigate('funding'); }}>
              <div style={{ fontFamily:'Bebas Neue,sans-serif', fontSize:48, letterSpacing:'.02em', color:'var(--lime)', lineHeight:1 }}>{displayTotal}</div>
              <div style={{ fontFamily:'DM Mono,monospace', fontSize:10, letterSpacing:'.12em', textTransform:'uppercase', color:'var(--text-faint)' }}>Total Community Raised ↗</div>
            </div>
          </div>

          <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:20 }}>
            {projects.slice(0,6).map(function(p, i) {
              return (
                <div key={p._id||p.name} className={'fund-card reveal rd'+(i+1)}
                  onMouseEnter={function(){ document.body.classList.add('hov'); }}
                  onMouseLeave={function(){ document.body.classList.remove('hov'); }}>
                  <span className="fund-icon" style={{ color: p.color }}><window.CBIcon name={p.icon || 'building'} size={22} /></span>
                  <div className="fund-title">{p.name}</div>
                  <div className="fund-desc">{p.desc}</div>
                  <div className="fund-amounts">
                    <div className="fund-raised" style={{ color:p.color }}>${p.raised}K</div>
                    <div className="fund-target">of ${p.target}K goal</div>
                  </div>
                  <div className="fund-track">
                    <div className="fund-fill" style={{
                      transform: animated ? 'scaleX('+(p.pct/100)+')' : 'scaleX(0)',
                      transition: animated ? 'transform '+(1+i*0.2)+'s var(--snappy) '+(i*0.15)+'s' : 'none',
                    }} />
                  </div>
                  <div className="fund-meta">
                    <span>{p.backers} backers</span>
                    <span>{p.days} days left</span>
                    <span>{p.pct}% funded</span>
                  </div>
                  <button className="btn btn-l" style={{ marginTop:18, width:'100%', justifyContent:'center' }}
                    onMouseEnter={function(){ document.body.classList.add('hov'); }}
                    onMouseLeave={function(){ document.body.classList.remove('hov'); }}
                    onClick={function(e){
                      window.CBGame && window.CBGame.award('fund-intent', 15, 'Supporter');
                      window.CBConfetti && window.CBConfetti.burst({ x: e.clientX, y: e.clientY, count: 40, power: 8 });
                      window.navigate('funding', { openProject: p._id });
                    }}>
                    Fund This Project →
                  </button>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  window.UserFunding = Funding;
})();
