// app.jsx — BRRR landing page v2 (dark, Printr-style)

const { useState, useEffect, useMemo } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "ticker": "BRRR",
  "primary": "#7C4DFF",
  "secondary": "#FF4DCB",
  "feePercent": 3,
  "buybackSplit": 80,
  "liveTicker": true
}/*EDITMODE-END*/;

const fmtUSD = (n, dp = 0) =>
  "$" + n.toLocaleString("en-US", { minimumFractionDigits: dp, maximumFractionDigits: dp });
const fmtNum = (n, dp = 0) =>
  n.toLocaleString("en-US", { minimumFractionDigits: dp, maximumFractionDigits: dp });

const rand = (seed) => {
  let s = seed; return () => { s = (s * 9301 + 49297) % 233280; return s / 233280; };
};

// ---------- NAV ----------
function Nav({ t }) {
  return (
    <nav className="nav">
      <div className="nav-inner">
        <a className="brand" href="#top">
          <span className="brand-mark">B</span>
          <span>{t.ticker}</span>
          <span className="brand-price">
            /usd · 0.0428 <span className="chg">+12.4%</span>
          </span>
        </a>
        <div className="nav-links">
          <a href="#how">How it works</a>
          <a href="#ledger" className="active">Buybacks</a>
          <a href="#roadmap">Roadmap</a>
          <a href="#buy">Buy</a>
          <a href="#faq">FAQ</a>
        </div>
        <div style={{ display: "flex", gap: 10 }}>
          <a className="btn btn-ghost" href="#ledger">Live feed</a>
          <a className="btn btn-primary" href="#buy">Buy {t.ticker} ↗</a>
        </div>
      </div>
    </nav>
  );
}

// ---------- HERO ----------
function Hero({ t }) {
  const [live, setLive] = useState({
    lastBuyback: 12480,
    totalBought: 2_418_902,
    pending: 248.32,
    block: 8_421_904,
  });

  useEffect(() => {
    if (!t.liveTicker) return;
    const id = setInterval(() => {
      setLive((p) => ({
        lastBuyback: p.lastBuyback + Math.round(Math.random() * 60),
        totalBought: p.totalBought + Math.round(Math.random() * 80),
        pending: +(p.pending + Math.random() * 2.3).toFixed(2),
        block: p.block + 1,
      }));
    }, 1400);
    return () => clearInterval(id);
  }, [t.liveTicker]);

  return (
    <section id="top" className="hero">
      <span className="chip">
        <span className="dot"></span>
        BUYBACK ACTIVE · BLOCK #{fmtNum(live.block)}
      </span>
      <h1>
        Every fee <span className="stroke">compounds.</span>
        <span className="line2">The printer runs <span className="grad-text">in reverse.</span></span>
      </h1>
      <p className="lede">
        {t.ticker} is a self-reinforcing token. A {t.feePercent}% fee on every trade —
        {" "}{t.buybackSplit}% routes on-chain to buy back and burn supply. No admin key, no pause button.
        Just code that keeps bidding.
      </p>
      <div className="hero-cta">
        <a className="btn btn-primary" href="#buy">
          Buy {t.ticker} <span className="mono" style={{ opacity: .8 }}>↗</span>
        </a>
        <a className="btn" href="#how">See the mechanism</a>
        <a className="btn btn-ghost" href="#ledger">
          <span style={{ color: "var(--green)" }}>●</span> Live buybacks
        </a>
      </div>

      {/* featured live buyback card */}
      <div className="buyback-card card-glow">
        <div className="inner">
          <div className="buyback-inner">
            <div style={{ textAlign: "left" }}>
              <div className="live-head">
                <span className="live-dot"></span>
                Live · last buyback executed
              </div>
              <div className="bb-big tnum">{fmtUSD(live.lastBuyback)}</div>
              <div className="bb-sub">
                Spent from the fee vault to market-buy {t.ticker}. Bought tokens
                were routed to <span style={{ color: "var(--pink)" }}>0x000…dead</span>.
              </div>
            </div>
            <div className="bb-right">
              <div className="bb-kv">
                <span className="k">Block</span>
                <span className="v tnum">{fmtNum(live.block)}</span>
              </div>
              <div className="bb-kv">
                <span className="k">Tokens bought</span>
                <span className="v cyan tnum">{fmtNum(291_428)} {t.ticker}</span>
              </div>
              <div className="bb-kv">
                <span className="k">30d bought back</span>
                <span className="v cyan tnum">{fmtUSD(live.totalBought)}</span>
              </div>
              <div className="bb-kv">
                <span className="k">Pending in vault</span>
                <span className="v pink tnum">{fmtUSD(live.pending, 2)}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* meta grid */}
      <div className="hero-meta">
        <div className="hmc">
          <div className="k">Market cap</div>
          <div className="v tnum">{fmtUSD(4_280_000)}</div>
          <div className="d"><span style={{ color: "var(--green)" }}>▲</span> +$520k · 24h</div>
        </div>
        <div className="hmc">
          <div className="k">Holders</div>
          <div className="v tnum">{fmtNum(12_408)}</div>
          <div className="d"><span style={{ color: "var(--green)" }}>▲</span> +342 today</div>
        </div>
        <div className="hmc">
          <div className="k">Burned supply</div>
          <div className="v cyan tnum">5.82%</div>
          <div className="d">of 1,000,000,000 {t.ticker}</div>
        </div>
        <div className="hmc">
          <div className="k">Chain</div>
          <div className="v">Solana · SPL</div>
          <div className="d">Immutable · no proxy</div>
        </div>
      </div>
    </section>
  );
}

// ---------- MARQUEE ----------
function Marquee({ t }) {
  const items = [
    [`${t.ticker}/USD  0.04281`, "up"],
    [`24H  +12.4%`, "up"],
    [`VOL  $1.28M`, null],
    [`BUYBACK POOL  $248.32`, null],
    [`LAST BB  $12,480`, "up"],
    [`HOLDERS  12,408`, null],
    [`FEE  ${t.feePercent}%`, null],
    [`SPLIT  ${t.buybackSplit}% → BB / ${100 - t.buybackSplit}% → LP`, null],
    [`CHAIN  SOLANA`, null],
    [`STATUS  RUNNING IN REVERSE`, null],
  ];
  const row = [...items, ...items].map(([txt, cls], i) => (
    <span key={i}>
      <span className="sep">◆</span>
      <span className={cls || ""}>{txt}</span>
    </span>
  ));
  return (
    <div className="marquee">
      <div className="marquee-track">{row}</div>
    </div>
  );
}

// ---------- MECHANISM ----------
function Mechanism({ t }) {
  const steps = [
    { n: "01", icon: "$", h: "User trades", d: `Any buy or sell on ${t.ticker} triggers a ${t.feePercent}% fee, collected automatically at the protocol layer.` },
    { n: "02", icon: "/", h: "Fees pool", d: "Fees accumulate in a transparent on-chain vault. Anyone can read it — nobody can withdraw it." },
    { n: "03", icon: "⇢", h: "Auto-route", d: `Every 200 blocks, ${t.buybackSplit}% of the vault market-buys ${t.ticker} from the open market.`, hot: true },
    { n: "04", icon: "×", h: "Supply burned", d: `Bought tokens are sent to a dead address. Float shrinks. Floor compounds.` },
  ];
  return (
    <section id="how" className="wrap">
      <div className="mech-head">
        <div>
          <div className="section-label">01 · Mechanism</div>
          <h2 style={{ marginTop: 18 }}>The fees don't leave.<br/><span className="grad-text">They come home.</span></h2>
        </div>
        <p>
          Most tokens leak value to treasuries, LPs, or a dev wallet. {t.ticker} routes{" "}
          <b style={{ color: "var(--text-hi)" }}>{t.buybackSplit}%</b> of every fee directly into
          on-chain buybacks. It's a tight loop, written into the token itself — no multisig,
          no timelock, no trust required.
        </p>
      </div>

      <div className="flow">
        {steps.map((s) => (
          <div key={s.n} className={"step" + (s.hot ? " hot" : "")}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start" }}>
              <div className="step-icon">{s.icon}</div>
              <div className="step-n">STEP {s.n}</div>
            </div>
            <div>
              <div className="step-h">{s.h}</div>
              <div className="step-d">{s.d}</div>
            </div>
          </div>
        ))}
      </div>

      <div className="fof">
        <div>
          <div className="section-label" style={{ marginBottom: 18 }}>Flow of funds</div>
          <pre>
{`   TRADE              FEE                VAULT
   ┌─────┐   ${t.feePercent}%    ┌─────┐           ┌──────────┐
   │ USD │ ───────→ │ FEE │ ────────→ │  VAULT   │
   └─────┘          └─────┘           └────┬─────┘
                                           │ every 200 blocks
                           ${t.buybackSplit}% ┌──────────┴──────────┐ ${100 - t.buybackSplit}%
                              ↓                           ↓
                         ┌────────┐                 ┌─────────┐
                         │ BUYBACK│ ──→ BURN       │   LP    │
                         └────────┘                 └─────────┘
`}
          </pre>
        </div>
        <div className="why">
          <div className="section-label" style={{ marginBottom: 18 }}>Why it works</div>
          <ul>
            {[
              ["Demand floor", "Every fee becomes a buy. Volume alone sustains price pressure."],
              ["Supply sink", "Bought tokens go to a dead address. Float only shrinks."],
              ["No gatekeeper", "The buyback runs in the contract. No admin key. No pausing."],
              ["Fully auditable", "Every receipt is on-chain. We print them to the ledger below."],
            ].map(([h, d]) => (
              <li key={h}>
                <span className="mark">→</span>
                <div>
                  <h4>{h}</h4>
                  <p>{d}</p>
                </div>
              </li>
            ))}
          </ul>
        </div>
      </div>
    </section>
  );
}

// ---------- STATS + LEDGER ----------
function StatsAndLedger({ t }) {
  const stats = [
    { k: "Fees collected · all-time", v: fmtUSD(3_124_820), d: "+$8,240 today", cls: "" },
    { k: `${t.ticker} bought back`, v: fmtNum(58_204_910), d: "73.2% of fee pool", cls: "cyan" },
    { k: `${t.ticker} burned`, v: fmtNum(58_204_910), d: "100% of buybacks", cls: "pink" },
    { k: "Buyback events", v: fmtNum(1842), d: "every ~200 blocks", cls: "green" },
  ];

  const rows = useMemo(() => {
    const r = rand(11);
    const out = [];
    for (let i = 0; i < 8; i++) {
      const amt = Math.round((120 + r() * 24_000));
      const tokens = Math.round(amt / 0.0428);
      const mins = Math.round(r() * 600);
      out.push({
        id: `BB-${String(8421904 - i * 200).slice(-6)}`,
        time: mins < 60 ? `${mins}m ago` : `${Math.floor(mins / 60)}h ${mins % 60}m ago`,
        amt, tokens,
      });
    }
    return out;
  }, []);

  return (
    <section id="ledger" className="wrap" style={{ paddingTop: 60 }}>
      <div className="section-label">02 · By the numbers</div>
      <h2 style={{ marginTop: 18, maxWidth: 22 + "ch" }}>
        Proof, not <span className="grad-text">promises.</span>
      </h2>
      <p style={{ color: "var(--text-md)", fontSize: 16, lineHeight: 1.55, maxWidth: "58ch", marginTop: 16 }}>
        Every fee collected, every token bought, every burn — printed to the ledger.
        Updated block-by-block. This page reflects the on-chain state.
      </p>

      <div className="stats">
        {stats.map((s) => (
          <div className="stat" key={s.k}>
            <div className="stat-k">{s.k}</div>
            <div className={"stat-v " + s.cls}>{s.v}</div>
            <div className="stat-d"><span className="up">▲</span> {s.d}</div>
          </div>
        ))}
      </div>

      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginTop: 56, marginBottom: 8 }}>
        <div className="section-label">Recent buybacks</div>
        <div className="mono" style={{ fontSize: 11, color: "var(--text-lo)" }}>
          <span style={{ color: "var(--green)" }}>●</span> LIVE · refreshes every block
        </div>
      </div>

      <div className="ledger">
        <div className="ledger-head">
          <span>ID</span>
          <span>Time</span>
          <span>Tokens bought</span>
          <span>USD routed</span>
          <span>Status</span>
        </div>
        {rows.map((r) => (
          <div className="ledger-row" key={r.id}>
            <span style={{ color: "var(--text-md)" }}>{r.id}</span>
            <span style={{ color: "var(--text-md)" }}>{r.time}</span>
            <span className="tnum">{fmtNum(r.tokens)} {t.ticker}</span>
            <span className="tnum amt">{fmtUSD(r.amt)}</span>
            <span>
              <span className="status"><span className="d"></span>BURN</span>
            </span>
          </div>
        ))}
      </div>
    </section>
  );
}

// ---------- WORDMARK ----------
function Wordmark({ t }) {
  const block = (key) => [
    <span key={`${key}-1`} className="stroke">PRINT.</span>,
    <span key={`${key}-2`} className="sep">◆</span>,
    <span key={`${key}-3`} className="grad">BURN.</span>,
    <span key={`${key}-4`} className="sep">◆</span>,
    <span key={`${key}-5`} className="stroke">REPEAT.</span>,
    <span key={`${key}-6`} className="sep">///</span>,
    <span key={`${key}-7`} className="grad">{t.ticker}</span>,
    <span key={`${key}-8`} className="sep">◆</span>,
  ];
  return (
    <div className="wordmark">
      <div className="wm-track">
        {block("a")}{block("b")}{block("c")}
      </div>
    </div>
  );
}

// ---------- ROADMAP ----------
function Roadmap({ t }) {
  const phases = [
    { n: "Phase 01", title: "Press start", done: true,
      items: ["Token deployed on Solana", "Buyback contract audited", "Liquidity locked · 24 months", "First 10k holders"] },
    { n: "Phase 02", title: "Distribute", done: true,
      items: ["CEX listings · 3 major", "Ledger explorer v1", "Auto-burn activated", "Community grants open"] },
    { n: "Phase 03", title: "Print loop", done: false,
      items: ["Cross-chain buybacks · Base, BNB", "On-chain receipts widget", "Partner integrations", "Dashboard v2"] },
    { n: "Phase 04", title: "The endgame", done: false,
      items: ["Buyback-as-a-service SDK", "Public index of BB tokens", "Sub-second settlement", "Float approaches zero"] },
  ];
  return (
    <section id="roadmap" className="wrap">
      <div className="section-label">03 · Roadmap</div>
      <h2 style={{ marginTop: 18 }}>From fee loop to <span className="grad-text">infrastructure.</span></h2>
      <p style={{ color: "var(--text-md)", fontSize: 16, lineHeight: 1.55, maxWidth: "58ch", marginTop: 16 }}>
        {t.ticker} starts as a memecoin with a working mechanism. The goal is to make that
        mechanism the default — a standard every new token can plug into.
      </p>

      <div className="roadmap">
        {phases.map((p) => (
          <div key={p.n} className={"phase" + (p.done ? " done" : "")}>
            <span className="phase-dot"></span>
            <div className="phase-h">{p.n} · {p.done ? "shipped" : "in flight"}</div>
            <div className="phase-title">{p.title}</div>
            <ul>{p.items.map((it) => <li key={it}>{it}</li>)}</ul>
          </div>
        ))}
      </div>
    </section>
  );
}

// ---------- BUY ----------
function Buy({ t }) {
  const [copied, setCopied] = useState(false);
  const addr = "BrRRfeeP1nTrXm0n3yP0w3rM1ntF33dL00pS0l";
  const copy = () => {
    navigator.clipboard?.writeText(addr);
    setCopied(true); setTimeout(() => setCopied(false), 1500);
  };

  return (
    <section id="buy" className="wrap" style={{ paddingTop: 60 }}>
      <div className="section-label">04 · How to buy</div>
      <h2 style={{ marginTop: 18 }}>Four steps. <span className="grad-text">No permission slip.</span></h2>

      <div className="buy-grid">
        <div>
          {[
            ["Get a Solana wallet", "Phantom, Solflare, Backpack — any SPL-compatible wallet works. Fund it with SOL from your exchange of choice."],
            [`Copy the ${t.ticker} contract`, "Use the official contract address on the right. Always verify the first and last 6 characters — impostors are inevitable."],
            ["Swap on Jupiter or Raydium", "Paste the contract into your DEX of choice. Set slippage to 2%. Hit confirm. Your trade itself contributes to the next buyback."],
            ["Hold. Watch the ledger.", `Every 200 blocks you'll see a new entry in the ledger above. That's your fee — coming home as a buyback.`],
          ].map(([h, d], i) => (
            <div className="buy-step" key={h}>
              <div className="n">0{i + 1}</div>
              <div>
                <h4>{h}</h4>
                <p>{d}</p>
              </div>
            </div>
          ))}
        </div>

        <div className="addr-box">
          <div>
            <div className="lbl">Contract · Solana</div>
            <div className="addr-row">
              <code>{addr}</code>
              <button className="copy-btn" onClick={copy}>{copied ? "✓ COPIED" : "COPY"}</button>
            </div>
          </div>
          <div className="addr-divider"></div>
          <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
            <div className="minirow"><span>Chain</span><b>Solana · SPL</b></div>
            <div className="minirow"><span>Supply</span><b className="tnum">1,000,000,000</b></div>
            <div className="minirow"><span>Fee</span><b>{t.feePercent}% · buy + sell</b></div>
            <div className="minirow"><span>Buyback split</span><b className="cyan">{t.buybackSplit}%</b></div>
            <div className="minirow"><span>Burn</span><b>Automatic</b></div>
            <div className="minirow"><span>LP lock</span><b>24 months</b></div>
            <div className="minirow"><span>Taxes</span><b>Immutable</b></div>
          </div>
          <div className="addr-divider"></div>
          <div style={{ display: "flex", gap: 8 }}>
            <a className="btn" style={{ flex: 1, justifyContent: "center" }} href="#">Jupiter ↗</a>
            <a className="btn btn-primary" style={{ flex: 1, justifyContent: "center" }} href="#">Raydium ↗</a>
          </div>
        </div>
      </div>
    </section>
  );
}

// ---------- FAQ ----------
function FAQ({ t }) {
  const [open, setOpen] = useState(0);
  const qs = [
    [`Is ${t.ticker} a memecoin or a utility token?`,
      `Both. The meme is the mechanism. ${t.ticker} is transparently a memecoin — no pretense of product-market fit — but it carries a working buyback loop that behaves more like protocol infrastructure than marketing copy.`],
    ["Where does the fee go if it's not buying back?",
      `The ${100 - t.buybackSplit}% that doesn't go to buybacks refills the liquidity pool, which keeps slippage low and trades deep. Nothing is sent to a team wallet. There is no team wallet.`],
    ["Can the buyback be paused or rug-pulled?",
      "No. The buyback logic lives inside the token itself, not a separate contract controlled by an admin. There is no pause function, no upgrade proxy, and no admin key. The code is the contract."],
    ["How often does the buyback execute?",
      "Every 200 blocks on Solana — roughly every 80 seconds. Each execution prints a receipt to the on-chain ledger, mirrored on this page."],
    ["What happens to the bought tokens?",
      `They're sent to 0x000…dead — a provably-unspendable address. This permanently shrinks float. Every fee makes the remaining supply scarcer.`],
    ["Who pays for the buyback transaction gas?",
      "The buyback tx is paid from the fee vault itself — never from users. On Solana, the cost is under a cent per execution."],
  ];
  return (
    <section id="faq" className="wrap">
      <div className="section-label">05 · FAQ</div>
      <h2 style={{ marginTop: 18 }}>Questions, answered <span className="grad-text">on the record.</span></h2>
      <div className="faq">
        {qs.map(([q, a], i) => (
          <div key={q} className={"q" + (open === i ? " open" : "")} onClick={() => setOpen(open === i ? -1 : i)}>
            <div className="q-h">
              <h4>{q}</h4>
              <div className="q-toggle">+</div>
            </div>
            <div className="q-a">{a}</div>
          </div>
        ))}
      </div>
    </section>
  );
}

// ---------- FOOTER ----------
function Footer({ t }) {
  return (
    <footer>
      <div className="ft-wrap">
        <div className="ft-big">
          PRINT. BURN. <em>REPEAT.</em>
        </div>
        <div className="ft-rows">
          <div className="ft-col">
            <b>{t.ticker}</b>
            <a href="#how">How it works</a>
            <a href="#ledger">Ledger</a>
            <a href="#roadmap">Roadmap</a>
            <a href="#buy">Buy</a>
          </div>
          <div className="ft-col">
            <b>Resources</b>
            <a href="#">Whitepaper</a>
            <a href="#">Audit report</a>
            <a href="#">Contract</a>
            <a href="#">Explorer</a>
          </div>
          <div className="ft-col">
            <b>Community</b>
            <a href="#">Twitter / X</a>
            <a href="#">Telegram</a>
            <a href="#">Discord</a>
            <a href="#">Farcaster</a>
          </div>
          <div className="ft-col" style={{ maxWidth: 280 }}>
            <b>Status</b>
            <span style={{ color: "var(--green)" }}>● Buyback engine nominal</span>
            <span className="mono" style={{ fontSize: 11, color: "var(--text-lo)" }}>BLOCK 8,421,904</span>
            <span className="mono" style={{ fontSize: 11, color: "var(--text-lo)" }}>UPTIME 100.00%</span>
          </div>
        </div>
        <div className="disclaim">
          {t.ticker} is a memecoin. Crypto is volatile. You can lose everything you put into it.
          Nothing on this page is financial advice. The buyback mechanism is enforced by code, not by us —
          verify the contract before you trade. By interacting with {t.ticker} you accept that code is law,
          and that memes are, occasionally, infrastructure.
        </div>
      </div>
    </footer>
  );
}

// ---------- APP ----------
function App() {
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);

  useEffect(() => {
    const root = document.documentElement;
    root.style.setProperty("--violet", t.primary);
    root.style.setProperty("--pink", t.secondary);
    root.style.setProperty(
      "--grad-primary",
      `linear-gradient(135deg, ${t.primary} 0%, ${t.secondary} 100%)`
    );
    root.style.setProperty(
      "--grad-spectrum",
      `linear-gradient(90deg, var(--cyan) 0%, ${t.primary} 50%, ${t.secondary} 100%)`
    );
  }, [t.primary, t.secondary]);

  return (
    <>
      <Nav t={t} />
      <Hero t={t} />
      <Marquee t={t} />
      <Mechanism t={t} />
      <Wordmark t={t} />
      <StatsAndLedger t={t} />
      <Roadmap t={t} />
      <Buy t={t} />
      <FAQ t={t} />
      <Footer t={t} />

      <TweaksPanel>
        <TweakSection label="Token" />
        <TweakText label="Ticker" value={t.ticker} onChange={(v) => setTweak("ticker", v.toUpperCase().slice(0, 6))} />
        <TweakSlider label="Trade fee" value={t.feePercent} min={1} max={10} step={0.5} unit="%"
          onChange={(v) => setTweak("feePercent", v)} />
        <TweakSlider label="→ Buyback split" value={t.buybackSplit} min={30} max={100} step={5} unit="%"
          onChange={(v) => setTweak("buybackSplit", v)} />

        <TweakSection label="Gradient accents" />
        <TweakColor label="Primary (violet)" value={t.primary} onChange={(v) => setTweak("primary", v)} />
        <TweakColor label="Secondary (pink)" value={t.secondary} onChange={(v) => setTweak("secondary", v)} />
        <TweakRadio label="Preset"
          value={t.primary + "|" + t.secondary}
          options={[
            "#7C4DFF|#FF4DCB",
            "#4DE1FF|#7C4DFF",
            "#19E39A|#4DE1FF",
            "#FF4D6A|#FFB84D",
          ]}
          onChange={(v) => {
            const [a, b] = v.split("|");
            setTweak("primary", a); setTweak("secondary", b);
          }} />

        <TweakSection label="Motion" />
        <TweakToggle label="Live hero counters" value={t.liveTicker}
          onChange={(v) => setTweak("liveTicker", v)} />
      </TweaksPanel>
    </>
  );
}

ReactDOM.createRoot(document.getElementById("app")).render(<App />);
