// /challenge — the Pantry Challenge — viral mechanic #2
// "Paste 5 brands, get a composite household plastic load score, share."

const challengeBrands = {
  'COCA-COLA': 12, 'COKE': 12, 'PEPSI': 14, 'OREO': 17, 'P&G': 18, 'NESTLE': 19, 'PROCTER': 18,
  'L\'OREAL': 21, 'LOREAL': 21, 'KRAFT': 22, 'MARS': 23, 'JOHNSON': 24,
  'UNILEVER': 26, 'COLGATE': 31, 'TESCO': 36, 'WOOLWORTHS': 38, 'COLES': 41,
  'WHOLE FOODS': 58, 'TRADER JOE': 62, 'ALDI': 64, 'OAT MILK': 94, 'WHO GIVES': 91,
  'BLUE LAND': 93, 'WHO GIVES A CRAP': 91,
};

function ChallengePage({ onNav }) {
  const [brands, setBrands] = React.useState(['', '', '', '', '']);
  const [scores, setScores] = React.useState([null, null, null, null, null]);
  const [composite, setComposite] = React.useState(null);

  function update(i, v) {
    const next = [...brands]; next[i] = v; setBrands(next);
    const sNext = [...scores];
    const key = v.trim().toUpperCase();
    sNext[i] = challengeBrands[key] !== undefined
      ? challengeBrands[key]
      : (key.length > 1 ? Math.max(15, 90 - key.length * 5) : null);
    setScores(sNext);
  }

  function calc() {
    const valid = scores.filter(s => s != null);
    if (valid.length < 3) return;
    const avg = Math.round(valid.reduce((a, b) => a + b, 0) / valid.length);
    setComposite({
      score: avg,
      load: Math.round((100 - avg) * 1.4 * 10) / 10, // kg/yr — placeholder math
      worst: brands[scores.indexOf(Math.min(...valid))]?.trim().toUpperCase() || 'YOUR PANTRY',
    });
  }

  const filled = brands.filter(b => b.trim()).length;

  return (
    <div className="page">
      <DocBar onNav={onNav} crumb="CHALLENGE · v1" />
      <Subnav page="/challenge" onNav={onNav} />

      <section className="page-hero">
        <div className="eyebrow">PANTRY CHALLENGE · ~30 SECS</div>
        <h1>Score five<br/>things in<br/>your house.</h1>
        <p className="lede">Paste five brand names. We composite. You post. Bragging rights or shame — your choice.</p>
      </section>

      <div className="section-h">
        <span>STEP 1 · PASTE FIVE</span>
        <span>{filled}/5</span>
      </div>

      <div style={{ paddingTop: 8 }}>
        {brands.map((b, i) => (
          <div key={i} className="pantry-input">
            <span className="ix">{i + 1}</span>
            <input
              className="field"
              placeholder={['Coca-Cola', 'Oreo', 'Coles', 'Oat Milk', 'L\'Oreal'][i]}
              value={b}
              onChange={(e) => update(i, e.target.value)}
            />
            {scores[i] != null ? (
              <div className={'pill ' + pillClassFor(scores[i])} style={{ width: 44, height: 44, fontSize: 18 }}>
                {scores[i]}
              </div>
            ) : (
              <div className="scoreSlot">—</div>
            )}
          </div>
        ))}
      </div>

      <div style={{ padding: '16px 20px 0' }}>
        <button className="btn" onClick={calc} disabled={filled < 3}>
          Calculate composite <Icon.arrow />
        </button>
        {filled < 3 && (
          <div className="mono mute" style={{ marginTop: 8, fontSize: 10 }}>
            FILL AT LEAST 3 TO COMPOSITE
          </div>
        )}
      </div>

      {composite && (
        <>
          <div className="section-h" style={{ marginTop: 24 }}>
            <span>STEP 2 · YOUR HOUSEHOLD</span>
            <span>SHARE-READY</span>
          </div>

          <section style={{ padding: '0 20px 8px' }}>
            <div className={'score-card ' + bandFor(composite.score) + ' snap-in'}>
              <div className="band"></div>
              <div className="label">PANTRY CHALLENGE · COMPOSITE</div>
              <div className="number">
                <CountUp to={composite.score} dur={600} />
                <span className="of">/100</span>
              </div>
              <div className="verdict">{verdictFor(composite.score)}</div>
              <div className="meta-row">
                <span>~{composite.load} KG PLASTIC / YR</span>
                <span>WORST: {composite.worst}</span>
              </div>
            </div>
          </section>

          <div className="section-h">
            <span>POSTABLE</span>
            <span>1080 × 1920</span>
          </div>
          <ShareCardPreview
            score={composite.score}
            brand={'YOUR PANTRY'}
            product={`5 BRANDS · ~${composite.load} KG/YR`}
            variant="dramatic"
          />

          <div style={{ padding: '12px 20px 0', display: 'flex', flexDirection: 'column', gap: 10 }}>
            <a className="btn coral" href="#" onClick={(e) => e.preventDefault()}>
              <Icon.share /> Share to TikTok
            </a>
            <a className="btn ghost" href="#" onClick={(e) => e.preventDefault()}>
              <Icon.download /> Download · PNG
            </a>
            <a className="btn ghost" href="#/" onClick={(e) => { e.preventDefault(); onNav('/'); }}>
              <Icon.scan /> Scan more in the app →
            </a>
          </div>
        </>
      )}

      {/* Leaderboard */}
      <div className="section-h" style={{ marginTop: 32 }}>
        <span>YESTERDAY'S CHALLENGES</span>
        <span>4,128 RUNS</span>
      </div>
      <div style={{ borderTop: '1px solid var(--plassic-line-200)' }}>
        {[
          { who: '@bellaplx', s: 28 }, { who: '@kanetx', s: 41 }, { who: '@plant.bb', s: 78 },
          { who: '@homechef', s: 52 }, { who: '@shopwell', s: 64 },
        ].map((r, i) => (
          <div key={i} style={{
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
            padding: '14px 20px', borderBottom: '1px solid var(--plassic-line-200)'
          }}>
            <div>
              <div style={{ fontFamily: 'var(--plassic-font-display)', fontSize: 18, letterSpacing: -.5, textTransform: 'uppercase' }}>{r.who}</div>
              <div className="mono mute" style={{ fontSize: 10, marginTop: 2 }}>5 BRANDS · {Math.round((100-r.s)*1.4*10)/10} KG/YR</div>
            </div>
            <div className={'pill ' + pillClassFor(r.s)}>{r.s}</div>
          </div>
        ))}
      </div>

      <Foot onNav={onNav} />
    </div>
  );
}

window.ChallengePage = ChallengePage;
