/* global React */
const { useState, useEffect, useRef } = React;

// =========================================================
// Terminal (animated, type-on)
// =========================================================
function Terminal() {
  const lines = [
    { t: '<span class="com">// audit your contract before mainnet</span>' },
    { t: '<span class="kw">contract</span> <span class="fn">Vault</span> <span class="kw">is</span> ReentrancyGuard {' },
    { t: '<span class="ind"></span><span class="kw">function</span> <span class="fn">withdraw</span>(<span class="kw">uint256</span> amount)' },
    { t: '<span class="ind"></span><span class="ind"></span><span class="kw">external</span> nonReentrant {' },
    { t: '<span class="ind"></span><span class="ind"></span>require(balance[msg.sender] &gt;= amount, <span class="str">"insufficient"</span>);' },
    { t: '<span class="ind"></span><span class="ind"></span>balance[msg.sender] -= amount;' },
    { t: '<span class="ind"></span><span class="ind"></span>(<span class="kw">bool</span> ok, ) = msg.sender.call{value: amount}(<span class="str">""</span>);' },
    { t: '<span class="ind"></span><span class="ind"></span>require(ok, <span class="str">"transfer failed"</span>);' },
    { t: '<span class="ind"></span>}' },
    { t: '}' },
    { t: '' },
    { t: '<span class="com">$ forge test --gas-report</span>' },
    { t: '<span class="com">[PASS] testWithdrawHappy() (gas: 41,202)</span>' },
    { t: '<span class="com">[PASS] testReentrancyBlocked() (gas: 28,914)</span>' },
  ];
  const [shown, setShown] = useState(0);
  useEffect(() => {
    if (shown >= lines.length) return;
    const id = setTimeout(() => setShown((s) => s + 1), shown < 11 ? 220 : 380);
    return () => clearTimeout(id);
  }, [shown]);

  return (
    <div className="terminal">
      <div className="term-bar">
        <div className="lights"><span/><span/><span/></div>
        <span className="path">~/super-dapps/vault/contracts/Vault.sol</span>
        <span className="net"><span className="dot"/>mainnet · 18s ago</span>
      </div>
      <div className="term-body">
        {lines.slice(0, shown).map((l, i) => (
          <span key={i} className="ln" dangerouslySetInnerHTML={{ __html: l.t || '&nbsp;' }} />
        ))}
        {shown < lines.length && <span className="caret" />}
      </div>
      <div className="term-foot">
        <span className="pill ok">● compiled</span>
        <span className="pill">solc 0.8.24</span>
        <span className="pill">14 tests passed</span>
        <span style={{ marginLeft: 'auto' }}>0 vulnerabilities</span>
      </div>
    </div>
  );
}

// =========================================================
// Hero
// =========================================================
function Hero({ heroVariant, onBook }) {
  return (
    <section className="hero">
      <div className="wrap">
        <div className="hero-grid">
          <div className="hero-main">
            <span className="hero-eyebrow">
              <span className="dot" />
              <span>Booking Q3 · 2 slots left</span>
            </span>
            <h1 className="hero-title">
              Ship Web3 <em>without</em> the<br/>
              <span className="acc">six-figure</span> exploits.
            </h1>
            <p className="hero-sub">
              I build production-grade dApps and audited smart contracts for small businesses moving on-chain. Tokens, payments, NFTs, escrow — written, tested, deployed, and explained in plain English.
            </p>
            <div className="hero-ctas">
              <button className="btn btn-primary" onClick={onBook}>
                Book a 30-min demo
                <svg className="arrow" width="14" height="14" viewBox="0 0 14 14" fill="none">
                  <path d="M3 11L11 3M11 3H5M11 3V9" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              </button>
              <a className="btn" href="#work">
                See recent work
              </a>
              <span style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-mute)', marginLeft: 4 }}>
                ⌘K to chat
              </span>
            </div>

            <div className="hero-meta">
              <div><span className="n">$42M+</span><span className="l">TVL secured</span></div>
              <div><span className="n">38</span><span className="l">Contracts shipped</span></div>
              <div><span className="n">0</span><span className="l">Exploits to date</span></div>
              <div><span className="n">14d</span><span className="l">Avg. delivery</span></div>
            </div>

            <div className="hero-block">
              <div>
                <div className="eyebrow">stack</div>
                <div style={{ marginTop: 8, fontSize: 15 }}>Solidity · Foundry · Hardhat · Viem</div>
              </div>
              <div>
                <div className="eyebrow">chains</div>
                <div style={{ marginTop: 8, fontSize: 15 }}>Ethereum · Base · Arbitrum · Polygon</div>
              </div>
              <div>
                <div className="eyebrow">frontends</div>
                <div style={{ marginTop: 8, fontSize: 15 }}>Next.js · wagmi · RainbowKit</div>
              </div>
              <div>
                <div className="eyebrow">based in</div>
                <div style={{ marginTop: 8, fontSize: 15 }}>Lisbon · Available globally</div>
              </div>
            </div>
          </div>

          <aside className="hero-aside">
            <Terminal />
          </aside>
        </div>
      </div>

      {heroVariant === 'bands' && (
        <div className="hero-bands">
          <div className="band">
            <div className="band-track">
              {Array.from({ length: 2 }).flatMap((_, k) =>
                ['SMART CONTRACTS', 'AUDITS', 'DAPPS', 'TOKEN LAUNCH', 'NFT', 'PAYMENTS', 'ESCROW', 'INDEXING'].map((w, i) => (
                  <span key={`${k}-${i}`}>{w} ✦</span>
                ))
              )}
            </div>
          </div>
          <div className="band fill">
            <div className="band-track rev">
              {Array.from({ length: 2 }).flatMap((_, k) =>
                ['SUPER DAPPS', 'WEB3 STUDIO', 'SHIP IT', 'NO RUGS', 'OPEN SOURCE'].map((w, i) => (
                  <span key={`${k}-${i}`}>{w} ✦</span>
                ))
              )}
            </div>
          </div>
        </div>
      )}
    </section>
  );
}

// =========================================================
// Services
// =========================================================
function Services() {
  const svcs = [
    {
      ix: '01',
      tag: 'core',
      title: <>Smart <em>contracts</em></>,
      blurb: 'Audited Solidity contracts written test-first with Foundry. Every branch covered, every assumption documented.',
      list: ['ERC-20 / 721 / 1155 tokens', 'Vaults, staking, escrow', 'On-chain governance', 'Upgradeable proxies (UUPS)'],
      time: 'from 2 weeks',
    },
    {
      ix: '02',
      tag: 'flagship',
      title: <>Full-stack <em>dApps</em></>,
      blurb: 'End-to-end products. Next.js front-end, indexed data layer, wallet UX that non-crypto users actually understand.',
      list: ['Wallet onboarding flows', 'Gasless transactions', 'The Graph subgraphs', 'Stripe → crypto rails'],
      time: 'from 4 weeks',
    },
    {
      ix: '03',
      tag: 'rescue',
      title: <>Audits &amp; <em>security</em></>,
      blurb: 'Independent review before you go live. Or a full incident response if something already went wrong on-chain.',
      list: ['Threat modeling', 'Slither + manual review', 'Fuzz & invariant tests', 'Post-mortem reports'],
      time: 'from 1 week',
    },
  ];
  return (
    <section className="section" id="services">
      <div className="wrap">
        <header className="section-head">
          <div>
            <span className="eyebrow">/ services</span>
          </div>
          <div>
            <h2>Three ways to <em>get on-chain</em> without burning your runway.</h2>
          </div>
        </header>
        <div className="services">
          {svcs.map((s) => (
            <div className="svc" key={s.ix}>
              <div className="ix"><span>{s.ix}</span><span className="tag">{s.tag}</span></div>
              <h3>{s.title}</h3>
              <p>{s.blurb}</p>
              <ul>{s.list.map((l) => <li key={l}>{l}</li>)}</ul>
              <div className="foot"><span>{s.time}</span><span>fixed scope</span></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// =========================================================
// Stack marquee
// =========================================================
function StackMarquee() {
  const items = ['Solidity', 'Foundry', 'Hardhat', 'Ethereum', 'Base', 'Arbitrum', 'Polygon', 'Viem', 'Wagmi', 'RainbowKit', 'The Graph', 'IPFS', 'OpenZeppelin', 'Chainlink', 'Safe', 'Slither', 'Echidna'];
  return (
    <section className="stack" aria-hidden="true">
      <div className="stack-track">
        {Array.from({ length: 3 }).flatMap((_, k) => items.map((it, i) => (
          <span key={`${k}-${i}`}>{it}<span className="sep"/></span>
        )))}
      </div>
    </section>
  );
}

// =========================================================
// Process
// =========================================================
function Process() {
  const steps = [
    { n: '01', t: 'Scope call', d: '30 minutes. We map the contract surface, threat model, and what "done" looks like.', time: 'day 0' },
    { n: '02', t: 'Spec & quote', d: 'Fixed-price proposal with milestones, deliverables, and a hard date. No hourly games.', time: 'day 1–3' },
    { n: '03', t: 'Build in public', d: 'Daily commits, weekly demo. You get the Foundry repo, the dashboard, my Telegram.', time: 'weeks 1–N' },
    { n: '04', t: 'Ship & sign-off', d: 'Audit pass, deploy to mainnet, hand off keys + a runbook a non-engineer can follow.', time: 'last week' },
  ];
  return (
    <section className="section" id="process">
      <div className="wrap">
        <header className="section-head">
          <div><span className="eyebrow">/ how it works</span></div>
          <div>
            <h2>From <em>"can we even do this?"</em> to mainnet in under a month.</h2>
          </div>
        </header>
        <div className="process">
          {steps.map((s) => (
            <div className="step" key={s.n}>
              <span className="num">step {s.n}</span>
              <h4>{s.t}</h4>
              <p>{s.d}</p>
              <span className="time">{s.time}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// =========================================================
// Work
// =========================================================
function Work() {
  const cases = [
    { tag: 'ESCROW · BASE', t: 'Freelance escrow contract', d: 'On-chain milestone payments with arbitration for a small-agency client.', stats: [['$1.2M', 'flowed'], ['0', 'disputes']] },
    { tag: 'TOKEN · ETHEREUM', t: 'Loyalty token launch', d: 'ERC-20 + claim portal for a 4,000-customer DTC brand. Gas-sponsored claims.', stats: [['4.2k', 'claims'], ['$0', 'user gas']] },
    { tag: 'NFT · ARBITRUM', t: 'Membership pass', d: 'Soulbound membership with off-chain perks gating. Stripe + crypto checkout.', stats: [['820', 'minted'], ['1.4s', 'checkout']] },
  ];
  return (
    <section className="section" id="work">
      <div className="wrap">
        <header className="section-head">
          <div><span className="eyebrow">/ selected work</span></div>
          <div>
            <h2>Quiet projects for businesses that just <em>needed it to work.</em></h2>
          </div>
        </header>
        <div className="work">
          {cases.map((c, i) => (
            <article className="case" key={i}>
              <div className="img"><span className="lbl">screenshot</span></div>
              <div className="meta">
                <span className="tag">{c.tag}</span>
                <h4>{c.t}</h4>
                <p>{c.d}</p>
              </div>
              <div className="stats">
                {c.stats.map(([n, l]) => <span key={l}><b>{n}</b> {l}</span>)}
              </div>
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

// =========================================================
// Stats strip
// =========================================================
function StatsStrip() {
  const items = [
    { n: '$42', u: 'M+', l: 'TVL secured', h: 'Across deployed vaults & escrow' },
    { n: '38', u: '', l: 'Contracts shipped', h: 'Mainnet + L2 deployments since 2021' },
    { n: '0', u: '', l: 'Exploits to date', h: 'Every contract still holds funds' },
    { n: '4.9', u: '/5', l: 'Client rating', h: 'Across 24 finished engagements' },
  ];
  return (
    <section className="section">
      <div className="wrap">
        <header className="section-head">
          <div><span className="eyebrow">/ track record</span></div>
          <div>
            <h2>Numbers I'll show you in the demo, with the <em>receipts</em>.</h2>
          </div>
        </header>
        <div className="stats-strip">
          {items.map((s, i) => (
            <div className="stat" key={i}>
              <span className="n">{s.n}<span className="u">{s.u}</span></span>
              <span className="l">{s.l}</span>
              <span className="h">{s.h}</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// =========================================================
// FAQ
// =========================================================
function FAQ() {
  const qs = [
    { q: 'I have no idea what Web3 actually means for my business. Can we still talk?', a: 'Yes — most demos start there. I\'ll spend the first 15 minutes asking what you sell, who buys it, and whether on-chain even makes sense. If it doesn\'t, I\'ll tell you and we\'re done.' },
    { q: 'How much does a typical project cost?', a: 'A standalone smart contract starts at $8k. A full dApp (contract + frontend + indexer + deploy) starts at $24k. Audits are quoted per LOC. Everything is fixed-price with milestones.' },
    { q: 'What chains do you ship on?', a: 'Ethereum mainnet and any EVM L2 — Base, Arbitrum, Optimism, Polygon, zkSync. For your use case I\'ll usually recommend Base or Arbitrum because the gas math is friendlier for small businesses.' },
    { q: 'Do you handle the legal / compliance side?', a: 'No. I\'ll work with your counsel and point out things that have regulatory weight (tokens that look like securities, etc.), but I don\'t give legal advice. I keep a short list of crypto-native lawyers I can refer you to.' },
    { q: 'What if something goes wrong after launch?', a: 'Every engagement includes 30 days of post-launch support. After that, retainer is $2k/month for monitoring, bug-fixes, and a same-day response SLA. Most clients drop it after 90 days.' },
    { q: 'Do I have to pay in crypto?', a: 'No — I invoice in USD via Stripe or wire. If you want to pay in USDC on Base, that works too and saves you the wire fee.' },
  ];
  const [open, setOpen] = useState(0);
  return (
    <section className="section" id="faq">
      <div className="wrap">
        <header className="section-head">
          <div><span className="eyebrow">/ frequently asked</span></div>
          <div>
            <h2>Questions other founders <em>asked first</em>.</h2>
          </div>
        </header>
        <div className="faq">
          {qs.map((row, i) => (
            <div
              key={i}
              className="faq-row"
              data-open={open === i}
              onClick={() => setOpen(open === i ? -1 : i)}
            >
              <span className="ix">0{i + 1}</span>
              <div>
                <div className="q">{row.q}</div>
                <div className="a">{row.a}</div>
              </div>
              <span className="tog">+</span>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

// =========================================================
// CTA + Footer
// =========================================================
function CTA({ onBook }) {
  return (
    <section className="section" id="book">
      <div className="wrap">
        <div className="cta-block">
          <div>
            <span className="eyebrow">/ ready when you are</span>
            <h2>Bring the idea. I'll bring the <em>contracts</em>.</h2>
            <p>30 minutes, no slides, no pitch deck. Tell me what you're trying to build and I'll tell you what it actually takes — chain, scope, price, timeline. If it's not a fit I'll point you somewhere that is.</p>
            <button className="btn btn-primary" onClick={onBook}>
              Book a 30-min demo
              <svg className="arrow" width="14" height="14" viewBox="0 0 14 14" fill="none">
                <path d="M3 11L11 3M11 3H5M11 3V9" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            </button>
          </div>
          <div className="side">
            <div><div className="l">where</div><div className="v">Google Meet — link arrives by email</div></div>
            <div><div className="l">when</div><div className="v">Tue–Thu, 9am–6pm WET</div></div>
            <div><div className="l">prep</div><div className="v">None. Bring questions, not docs.</div></div>
            <div><div className="l">followup</div><div className="v">Written quote within 48 hours</div></div>
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer() {
  return (
    <footer className="foot">
      <div className="wrap">
        <div className="foot-top">
          <div>
            <a className="brand" href="#top">
              <span className="glyph">⌬</span>
              <span className="word"><b>Super</b> <i>Dapps</i></span>
            </a>
            <p style={{ color: 'var(--text-dim)', fontSize: 14, marginTop: 16, maxWidth: '32ch' }}>
              An independent Web3 studio. Smart contracts, dApps, audits — built for small businesses that need it to just work.
            </p>
          </div>
          <div>
            <h5>Services</h5>
            <ul>
              <li><a href="#services">Smart contracts</a></li>
              <li><a href="#services">Full-stack dApps</a></li>
              <li><a href="#services">Audits & security</a></li>
              <li><a href="#services">Retainer</a></li>
            </ul>
          </div>
          <div>
            <h5>Studio</h5>
            <ul>
              <li><a href="#work">Selected work</a></li>
              <li><a href="#process">Process</a></li>
              <li><a href="#faq">FAQ</a></li>
              <li><a href="#book">Book demo</a></li>
            </ul>
          </div>
          <div>
            <h5>Reach</h5>
            <ul>
              <li><a>hello@superdapps.xyz</a></li>
              <li><a>github.com/superdapps</a></li>
              <li><a>x.com/superdapps</a></li>
              <li><a>Telegram: @superdapps</a></li>
            </ul>
          </div>
        </div>
        <div className="foot-bottom">
          <span>© 2026 SUPER DAPPS — independent studio</span>
          <span>Built in Lisbon · Available globally · v2.4.0</span>
        </div>
      </div>
    </footer>
  );
}

Object.assign(window, { Hero, Services, StackMarquee, Process, Work, StatsStrip, FAQ, CTA, Footer, Terminal });
