/* Wanted Poster Generator — the viral feature */

const { useState: useState_p, useEffect: useEffect_p, useMemo: useMemo_p, useRef: useRef_p } = React;

/* deterministic pseudo-random from string */
function seedFrom(str) {
  let h = 2166136261 >>> 0;
  for (let i = 0; i < str.length; i++) {
    h = Math.imul(h ^ str.charCodeAt(i), 16777619);
  }
  return () => {
    h = Math.imul(h ^ (h >>> 15), 2246822507);
    h = Math.imul(h ^ (h >>> 13), 3266489909);
    h ^= h >>> 16;
    return ((h >>> 0) % 100000) / 100000;
  };
}

/* Generate 8x8 mirrored pixel avatar from seed */
function PixelAvatar({ seed }) {
  const rng = useMemo_p(() => seedFrom(seed || "anonymous"), [seed]);
  const cells = useMemo_p(() => {
    const palettes = [
      ["#ff1b8d", "#ffc23a", "#1ce4ff", "#f0c040"],
      ["#ff6b1a", "#c033ff", "#ffd23a", "#1ce4ff"],
      ["#ff1b8d", "#6a2bff", "#ff6b1a", "#ffc23a"],
      ["#1ce4ff", "#ff1b8d", "#ffc23a", "#c033ff"],
    ];
    const pal = palettes[Math.floor(rng() * palettes.length)];
    const grid = [];
    // 8x8, mirrored on x — only generate 4 cols, mirror to right
    for (let y = 0; y < 8; y++) {
      const row = [];
      for (let x = 0; x < 4; x++) {
        const r = rng();
        // hair/top rows dense, middle rows for face
        let v;
        if (y === 0) v = r > 0.85 ? pal[0] : "transparent";
        else if (y === 1) v = r > 0.55 ? pal[0] : "transparent";
        else if (y === 2 || y === 3) v = pal[1];   // face
        else if (y === 4) v = (x === 1 || x === 0) ? "#000" : pal[1]; // eyes
        else if (y === 5) v = pal[1];
        else if (y === 6) v = r > 0.5 ? pal[2] : pal[3];
        else v = r > 0.4 ? pal[3] : "transparent";
        row.push(v);
      }
      // mirror
      const full = [...row, ...row.slice().reverse()];
      grid.push(full);
    }
    return grid;
  }, [seed]);

  return (
    <div className="pixel-grid">
      {cells.flatMap((row, y) =>
        row.map((c, x) => (
          <div key={`${x}-${y}`} className="px" style={{ background: c === "transparent" ? "#1c0a2c" : c }} />
        ))
      )}
    </div>
  );
}

/* The Poster itself — uses real wanted-poster-frame.png as background */
function WantedPoster({ alias, address, stars, holdings, bounty, crimes, live, matchInfo, seed, useCharacter = true }) {
  return (
    <div className="poster-frame">
      <div className="poster-inner">
        <div className="poster-stars">
          {Array.from({ length: 5 }, (_, i) => (
            <StarIcon key={i} className={`ps ${i < stars ? "" : "off"}`} style={{ width: 18, height: 18 }} />
          ))}
        </div>

        <div className="poster-wanted">wanted</div>
        <div className="poster-dora">DEAD · OR · BULLISH</div>

        <div className="poster-avatar-wrap">
          <div className={`poster-avatar ${useCharacter ? "has-photo" : ""}`}>
            {useCharacter ? (
              <img className="character" src="assets/character-sm.png" alt="" />
            ) : (
              <PixelAvatar seed={seed} />
            )}
          </div>
        </div>

        <div className="poster-alias">&ldquo;{alias || "the hodlr"}&rdquo;</div>
        <div className="poster-addr">{address}</div>

        <div className="poster-crimes">
          <div className="ttl">CRIMES</div>
          <ul>
            {crimes.map((c, i) => <li key={i}>{c}</li>)}
          </ul>
        </div>

        <div className="poster-bounty">
          <div className="lbl">BOUNTY</div>
          <div className="val">◎ {bounty} sol</div>
        </div>

        <div className="poster-foot">
          <span className="ca">GCA9X4hH3vC1m2QkTzs7N6pL3Y8jR4nZ7aBgFmK2vP</span>
          $GCA · GRANDCUPAUTO.COM
        </div>
      </div>

      {live && matchInfo && (
        <div className="poster-match-overlay">
          <div>wanted during</div>
          <div style={{fontSize:9, letterSpacing:"0.18em"}}>{matchInfo.home.code} vs {matchInfo.away.code}</div>
          <div className="sc">{matchInfo.homeScore}-{matchInfo.awayScore}</div>
        </div>
      )}
    </div>
  );
}

const WORLD_AUDIENCES = [
  {
    id: "boss",
    icon: "🏆",
    label: "$GCA Boss",
    title: "If you hold $GCA",
    bullets: [
      "Five cartels burn your supply: every trade, every day, five engines, one boss.",
      "Every bounty hunter is a forced buyer of $GCA or a Cartel through the hold-gate.",
      "You own the token all five families feed. The boss does not work. The boss collects.",
    ],
  },
  {
    id: "cartel",
    icon: "💼",
    label: "Cartel holder",
    title: "If you hold a Cartel token",
    bullets: [
      "Your coin pays for its own marketing: bounties create reach, reach creates volume, volume wakes the bag.",
      "Holding qualifies you to hunt every bounty in that family.",
      "Half your fees still pump $GCA, and a stronger boss lifts the whole bloodline.",
    ],
  },
  {
    id: "creator",
    icon: "🎯",
    label: "Creator hunter",
    title: "If you are a creator or bounty hunter",
    bullets: [
      "Get paid in SOL to make memes, clips, stunts, art and chaos. Earn on skill, not capital.",
      "Tiny ticket in: hold a bag to qualify, then collect.",
      "Go viral and the pots get fatter next round. You are pumping your own paychecks.",
    ],
  },
  {
    id: "ecosystem",
    icon: "🌎",
    label: "Ecosystem",
    title: "For the whole ecosystem",
    bullets: [
      "Self-funding marketing: paid by live trading fees, not a team wallet that runs dry.",
      "Scales with attention: more hype automatically means more fuel.",
      "Anti-fragile: chop and dumping still generate fees that burn supply and fund growth. The wheel turns on green and red.",
    ],
  },
];

function EcosystemExplainer() {
  const [active, setActive] = useState_p("boss");
  const item = WORLD_AUDIENCES.find(x => x.id === active) || WORLD_AUDIENCES[0];

  return (
    <div className="world-wrap" data-reveal>
      <div className="world-characters" aria-hidden="true">
        <img className="world-char world-char-left" src="assets/char-superagent.png" alt="" />
        <img className="world-char world-char-right" src="assets/char-broker.png" alt="" />
      </div>

      <div className="world-head">
        <div>
          <div className="world-kicker">creator fees into cartel contracts</div>
          <h3>the boss eats first.</h3>
          <p>
            Every trade through the five cartel tokens pushes value into the same loop:
            burn pressure for $GCA, fresh bounty pots for creators, and a hold-gate that
            turns hunters into holders.
          </p>
        </div>
        <div className="world-count">
          <span>5</span>
          <b>cartels feeding one boss</b>
        </div>
      </div>

      <div className="world-grid">
        <div className="world-diagram" aria-label="Grand Cup Auto flywheel">
          <div className="diagram-loop loop-top" />
          <div className="diagram-node attention">attention</div>
          <div className="diagram-arrow down a1" />
          <div className="diagram-node trade">people trade the 5 cartels</div>
          <div className="diagram-arrow down a2" />
          <div className="diagram-node fees">creator fees</div>
          <div className="diagram-split">
            <span>split 50 / 50</span>
          </div>
          <div className="diagram-branches">
            <div className="diagram-node burn">
              <b>burn $GCA</b>
              <span>supply down forever</span>
            </div>
            <div className="diagram-node pots">
              <b>bounty pots</b>
              <span>fund the contracts</span>
            </div>
          </div>
          <div className="diagram-arrow down a3" />
          <div className="diagram-node hunters">hunters make clips, stunts, art</div>
          <div className="diagram-arrow down a4" />
          <div className="diagram-node gate">
            must hold $GCA or a Cartel to claim
            <span>hunters become holders, demand rises</span>
          </div>
          <div className="diagram-return">more reach</div>
        </div>

        <div className="world-panel">
          <div className="world-tabs" role="tablist" aria-label="Flywheel audiences">
            {WORLD_AUDIENCES.map(a => (
              <button
                key={a.id}
                className={`world-tab ${active === a.id ? "on" : ""}`}
                onClick={() => setActive(a.id)}
                role="tab"
                aria-selected={active === a.id}
              >
                <span>{a.icon}</span>
                {a.label}
              </button>
            ))}
          </div>

          <div className={`world-card world-card-${item.id}`}>
            <div className="world-card-icon">{item.icon}</div>
            <div className="world-card-copy">
              <h4>{item.title}</h4>
              <ul>
                {item.bullets.map((b, i) => <li key={i}>{b}</li>)}
              </ul>
            </div>
          </div>

          <div className="world-mini-stats">
            <div><span>cartels</span><b>5</b></div>
            <div><span>split</span><b>50 / 50</b></div>
            <div><span>claim gate</span><b>hold</b></div>
          </div>
        </div>
      </div>
    </div>
  );
}

/* Generator UI */
function PosterGenerator({ liveMatch }) {
  const data = window.GCA_DATA;
  const [walletInput, setWalletInput] = useState_p("");
  const [holdings, setHoldings] = useState_p(2400000);
  const [processing, setProcessing] = useState_p(false);
  const [generated, setGenerated] = useState_p({ aliasI: 0, addr: "", seed: "init-seed", crimes: [], bounty: 164, stars: 3, holdings: 2400000 });
  const [showLive, setShowLive] = useState_p(true);
  const [useChar, setUseChar] = useState_p(true);

  const generate = (wallet, count) => {
    setProcessing(true);
    setTimeout(() => {
      const rng = seedFrom(wallet + ":" + count);
      const aliasI = Math.floor(rng() * data.aliases.length);
      const crimesPool = data.crimePool;
      const used = new Set();
      const chosen = [];
      while (chosen.length < 4) {
        const i = Math.floor(rng() * crimesPool.length);
        if (used.has(i)) continue;
        used.add(i);
        const formatted = crimesPool[i].replace("%X%", (count / 1e6).toFixed(1) + "M");
        chosen.push(formatted);
      }
      const stars = Math.min(5, Math.max(1, Math.round(Math.log10(Math.max(count, 1000)) - 2)));
      const bountyMult = count >= 100e6 ? 0.0002 : count >= 10e6 ? 0.0001 : count >= 1e6 ? 0.00005 : 0.00001;
      const bounty = Math.round(count * bountyMult);
      const addr = wallet.length > 14
        ? wallet.slice(0, 4) + "…" + wallet.slice(-6)
        : wallet || "0x" + Math.floor(rng() * 1e10).toString(16).padStart(10, "0");
      setGenerated({ aliasI, addr, seed: wallet + count, crimes: chosen, bounty, stars, holdings: count });
      setProcessing(false);
    }, 1100);
  };

  // initial generation
  useEffect_p(() => {
    generate("PHANTOM_DEMO_AKA_THE_HODLR", holdings);
  }, []);

  // regenerate when wallet/holdings change (debounce via button only — but live for slider)
  useEffect_p(() => {
    if (!walletInput && holdings === 2400000) return;
    const t = setTimeout(() => generate(walletInput || "PHANTOM_DEMO", holdings), 350);
    return () => clearTimeout(t);
  }, [holdings]);

  const handleGen = () => generate(walletInput || "PHANTOM_DEMO", holdings);

  return (
    <div className="gen-wrap">
      <div className="gen-controls">
        <div className="gen-step">
          <div className="step-no">STEP 01</div>
          <div className="step-ttl">Identify the suspect</div>
          <div className="input-wrap">
            <span className="pref">◎</span>
            <input
              type="text"
              value={walletInput}
              onChange={e => setWalletInput(e.target.value)}
              placeholder="paste wallet or @handle"
            />
          </div>
          <div className="gen-toggle-row">
            <button className="gen-toggle" onClick={() => setWalletInput("PHANTOM_DEMO_GCA")}>USE DEMO</button>
            <button className="gen-toggle" onClick={() => { setWalletInput(""); }}>CLEAR</button>
          </div>
        </div>

        <div className="gen-step">
          <div className="step-no">STEP 02</div>
          <div className="step-ttl">Estimate the haul</div>
          <div className="slider-wrap">
            <div className="top">
              <span>$GCA holdings</span>
              <span className="val">{(holdings / 1e6).toFixed(1)}M tokens</span>
            </div>
            <input
              type="range"
              min="100000" max="200000000" step="100000"
              value={holdings}
              onChange={e => setHoldings(Number(e.target.value))}
            />
            <div className="top" style={{marginTop:4}}>
              <span>Wanted level</span>
              <span className="val">★ × {generated.stars}</span>
            </div>
          </div>
        </div>

        <div className="gen-step" style={{marginBottom: 14}}>
          <div className="step-no">step 03</div>
          <div className="step-ttl">Mission day overlay</div>
          <div className="gen-toggle-row">
            <button className={`gen-toggle ${showLive ? "on" : ""}`} onClick={() => setShowLive(true)}>live match</button>
            <button className={`gen-toggle ${!showLive ? "on" : ""}`} onClick={() => setShowLive(false)}>off</button>
          </div>
          <div className="step-ttl" style={{marginTop: 14, fontSize: 14}}>Avatar style</div>
          <div className="gen-toggle-row">
            <button className={`gen-toggle ${useChar ? "on" : ""}`} onClick={() => setUseChar(true)}>character</button>
            <button className={`gen-toggle ${!useChar ? "on" : ""}`} onClick={() => setUseChar(false)}>pixel mug</button>
          </div>
        </div>

        <div className="processing">
          {processing ? <>▸ SCANNING<span className="dots"/> CROSS-REFERENCING GCA DATABASE</> : <>▸ FILE READY · BOUNTY ISSUED</>}
        </div>

        <button className="btn-sunset" style={{ width: "100%" }} onClick={handleGen}>
          {processing ? "PROCESSING…" : "▸ ISSUE WANTED POSTER"}
        </button>

        <div className="gen-share-row">
          <button className="btn-ghost" style={{flex:1}}>↓ DOWNLOAD PNG</button>
          <a className="btn-ghost" href="https://x.com/grandcupauto" target="_blank" rel="noopener noreferrer" style={{flex:1, textAlign: "center"}}>𝕏 SHARE TO X</a>
        </div>
      </div>

      <div style={{ display: "flex", justifyContent: "center" }}>
        <div style={{ width: "min(420px, 100%)" }}>
          <WantedPoster
            alias={data.aliases[generated.aliasI]}
            address={generated.addr}
            stars={generated.stars}
            holdings={(generated.holdings / 1e6).toFixed(1) + "M"}
            bounty={generated.bounty}
            crimes={generated.crimes}
            live={showLive}
            matchInfo={liveMatch}
            seed={generated.seed}
            useCharacter={useChar}
          />
        </div>
      </div>
    </div>
  );
}

window.PosterGenerator = EcosystemExplainer;
window.EcosystemExplainer = EcosystemExplainer;
window.WantedPoster = WantedPoster;
window.PixelAvatar = PixelAvatar;
window.seedFrom = seedFrom;
