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

  var FILTERS   = ['All','Live in AR','Completed','Pending','Citizen','Business','Government'];
  var COLOR_MAP = { violet:'var(--violet)', lime:'var(--lime)', cyan:'var(--cyan)', rose:'var(--rose)', amber:'var(--amber)' };
  var CHIP_MAP  = { government:'c-c', business:'c-l', citizen:'c-v' };
  var STAGE_MAP = { live:'c-l', completed:'c-c', pending:'c-r', ar_processing:'c-v', in_review:'c-a' };
  var STAGE_LABEL = { live:'Live in AR', completed:'Completed', pending:'Pending', ar_processing:'AI Enhancing', in_review:'In Review' };
  var FILL_MAP  = {
    lime:'linear-gradient(90deg,var(--lime),var(--cyan))', cyan:'linear-gradient(90deg,var(--cyan),var(--violet))',
    rose:'linear-gradient(90deg,var(--rose),var(--violet))', amber:'linear-gradient(90deg,var(--amber),var(--lime))',
    violet:'linear-gradient(90deg,var(--violet),var(--cyan))',
  };
  var COLOR_BY_INDEX = ['lime','cyan','violet','amber','rose'];

  function apiToCard(p, i) {
    return {
      _id:         p._id,
      name:        p.title,
      loc:         (p.location && p.location.district) || '—',
      stage:       STAGE_LABEL[p.status] || p.status || 'Pending',
      statusRaw:   p.status,
      contributor: (p.submittedBy && p.submittedBy.role) || 'citizen',
      funded:      Math.round((p.funding && p.funding.raised || 0) / 1000),
      target:      Math.round((p.funding && p.funding.goal   || 1) / 1000) || 1,
      views:       (p.ar && p.ar.views || 0).toLocaleString(),
      color:       COLOR_BY_INDEX[i % COLOR_BY_INDEX.length],
      emoji:       ['🏙','🌳','🚲','🏗','🎭','🌿','🏛','💡','🛤','🎪'][i % 10],
    };
  }

  function Projects() {
    var _filter   = useState('All');                       var filter = _filter[0], setFilter = _filter[1];
    var _projects = useState(window.USER_PROJECTS || []); var projects = _projects[0], setProjects = _projects[1];
    var _loading  = useState(false);                       var loading = _loading[0], setLoading = _loading[1];
    var ref = useRef(null);
    window.useReveal(ref);

    useEffect(function() {
      if (!window.ApiClient) return;
      setLoading(true);
      window.ApiClient.get('/projects?limit=12&sort=-ar.views').then(function(d) {
        if (d && d.projects && d.projects.length) setProjects(d.projects.map(apiToCard));
        setLoading(false);
      }).catch(function() { setLoading(false); });
    }, []);

    var STATUS_FOR_FILTER = { 'Live in AR':'live', 'Completed':'completed', 'Pending':'pending' };
    var filtered = filter === 'All'
      ? projects
      : projects.filter(function(p) {
          if (STATUS_FOR_FILTER[filter]) return p.statusRaw === STATUS_FOR_FILTER[filter] || p.stage === filter;
          return p.contributor === filter.toLowerCase();
        });

    return (
      <div ref={ref}>
        <div className="section">
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginBottom:40, flexWrap:'wrap', gap:16 }}>
            <div>
              <div className="eyebrow reveal">Live Projects</div>
              <h2 className="heading-lg reveal rd1">Ideas <span className="gradient-text">Already</span><br />Reshaping the City</h2>
            </div>
            <button className="btn btn-o reveal rd2"
              onMouseEnter={function(){ document.body.classList.add('hov'); }}
              onMouseLeave={function(){ document.body.classList.remove('hov'); }}
              onClick={function(){ window.navigate('projects'); }}>
              View All {projects.length}+ →
            </button>
          </div>

          <div className="filter-bar reveal rd1">
            {FILTERS.map(function(f) {
              return (
                <button key={f} className={'ftab'+(filter===f?' on':'')}
                  onMouseEnter={function(){ document.body.classList.add('hov'); }}
                  onMouseLeave={function(){ document.body.classList.remove('hov'); }}
                  onClick={function(){ setFilter(f); }}>
                  {f}
                </button>
              );
            })}
          </div>

          {loading && <div style={{ textAlign:'center', fontFamily:'DM Mono,monospace', fontSize:10, color:'var(--text-faint)', padding:'40px 0' }}>LOADING PROJECTS…</div>}

          <div className="proj-grid">
            {filtered.slice(0, 8).map(function(p, i) {
              var pct       = Math.min(100, p.target > 0 ? Math.round((p.funded/p.target)*100) : 0);
              var fillColor = FILL_MAP[p.color] || 'linear-gradient(90deg,var(--violet),var(--cyan))';
              var chipClass = CHIP_MAP[p.contributor] || 'c-v';
              var stageClass = STAGE_MAP[p.statusRaw] || 'c-v';
              return (
                <div key={p._id || i} className={'proj-card reveal rd'+Math.min(i+1,6)}
                  onMouseEnter={function(){ document.body.classList.add('hov'); }}
                  onMouseLeave={function(){ document.body.classList.remove('hov'); }}
                  onMouseMove={function(e){
                    var r = e.currentTarget.getBoundingClientRect();
                    e.currentTarget.style.setProperty('--mx', ((e.clientX - r.left) / r.width * 100).toFixed(1) + '%');
                    e.currentTarget.style.setProperty('--my', ((e.clientY - r.top) / r.height * 100).toFixed(1) + '%');
                  }}
                  onClick={function(){
                    window.CBGame && window.CBGame.award('project-open', 15, 'Project Scout');
                    window.navigate('project-detail', { id: p._id });
                  }}
                  style={{ cursor:'none' }}>
                  <div className="proj-thumb">
                    <div className="proj-thumb-art" style={{ fontSize:88, zIndex:0 }} aria-hidden="true">{p.emoji}</div>
                    <div className="proj-thumb-overlay" />
                    <div className="proj-scan" />
                    <div className="proj-ar-hover"><span>→</span> View Project</div>
                    <div className="proj-stage-badge"><span className={'chip '+stageClass}>{p.stage}</span></div>
                  </div>
                  <div className="proj-body">
                    <div className="proj-title">{p.name}</div>
                    <div className="proj-loc"><window.CBIcon name="map-pin" size={11} /> {p.loc} · <span className={'chip '+chipClass} style={{ fontSize:9, padding:'2px 7px' }}>{p.contributor}</span></div>
                    <div className="proj-bar">
                      <div style={{ display:'flex', justifyContent:'space-between', marginBottom:5, fontFamily:'DM Mono,monospace', fontSize:9, color:'var(--text-faint)' }}>
                        <span>{pct}% funded</span><span>${p.target}K goal</span>
                      </div>
                      <div className="proj-bar-track">
                        <div className="proj-bar-fill" style={{ width:pct+'%', background:fillColor }} />
                      </div>
                    </div>
                    <div className="proj-meta">
                      <div className="proj-funded" style={{ color:COLOR_MAP[p.color]||'var(--lime)' }}>${p.funded}K</div>
                      <div className="proj-views"><window.CBIcon name="eye" size={12} /> {p.views} views</div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    );
  }

  window.UserProjects = Projects;
})();
