// app.jsx — SplitFast sticker chaos site

const { useState, useEffect, useRef, useCallback } = React;

const RANDOM_VIBE_KEYS = ["yellow", "pink", "cream"];
const RANDOM_VIBE = RANDOM_VIBE_KEYS[Math.floor(Math.random() * RANDOM_VIBE_KEYS.length)];

const VIBES = {
  yellow: { bg: "#FFEF00", ink: "#0A0A0A", red: "#FF3D00", blue: "#1F4DFF", green: "#00C853" },
  pink:   { bg: "#FF6FB5", ink: "#0A0A0A", red: "#FFE600", blue: "#0066FF", green: "#00FF85" },
  cream:  { bg: "#F5F1E8", ink: "#0A0A0A", red: "#FF3D00", blue: "#1F4DFF", green: "#00A86B" },
};

function fmtNum(n){ return n.toLocaleString("en-US"); }

const API_BASE = location.hostname === 'localhost'
  ? `http://localhost:3000`
  : 'https://api.splitfast.ai';

async function submitToWaitlist(email, boosted = false) {
  try {
    const res = await fetch(`${API_BASE}/waitlist`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, boosted }),
    });
    if (res.ok) return await res.json();
  } catch (e) {}
  return null;
}

// -- DRAGGABLE STICKER --
function DragSticker({ children, className, baseTransform = '' }) {
  const [offset, setOffset] = useState({ x: 0, y: 0 });
  const [dragging, setDragging] = useState(false);
  const startRef = useRef({ mx: 0, my: 0, ox: 0, oy: 0 });

  const onDown = (e) => {
    e.preventDefault();
    e.stopPropagation();
    const ev = e.touches ? e.touches[0] : e;
    startRef.current = { mx: ev.clientX, my: ev.clientY, ox: offset.x, oy: offset.y };
    setDragging(true);
  };

  useEffect(() => {
    if (!dragging) return;
    const onMove = (e) => {
      const ev = e.touches ? e.touches[0] : e;
      setOffset({
        x: startRef.current.ox + (ev.clientX - startRef.current.mx),
        y: startRef.current.oy + (ev.clientY - startRef.current.my),
      });
    };
    const onUp = () => setDragging(false);
    window.addEventListener('mousemove', onMove);
    window.addEventListener('touchmove', onMove, { passive: false });
    window.addEventListener('mouseup', onUp);
    window.addEventListener('touchend', onUp);
    return () => {
      window.removeEventListener('mousemove', onMove);
      window.removeEventListener('touchmove', onMove);
      window.removeEventListener('mouseup', onUp);
      window.removeEventListener('touchend', onUp);
    };
  }, [dragging]);

  return (
    <div
      className={className + (dragging ? ' dragging' : '')}
      style={{ transform: 'translate(' + offset.x + 'px,' + offset.y + 'px) ' + baseTransform }}
      onMouseDown={onDown}
      onTouchStart={onDown}
    >
      {children}
    </div>
  );
}

function CTopBar(){
  return (
    <header className="c-top">
      <div className="c-wm">SPLITFAST<i>.</i></div>
      <div className="c-top-pills">
        <span className="c-pill">★ COMING SOON · 2026</span>
        <span className="c-pill">BETA ✕</span>
        <span className="c-pill">EAT-PLAY-SPLIT</span>
      </div>
      <a href="#signup" className="c-cta">GET ON THE LIST →</a>
    </header>
  );
}

function CHero({ signups, onSubmit, stickersOn, konamiActive }){
  const [email, setEmail] = useState("");
  const [done, setDone] = useState(false);
  const submit = async (e) => {
    e.preventDefault();
    if (!email || !/.+@.+\..+/.test(email)) return;
    sound.coin();
    const result = await submitToWaitlist(email, konamiActive);
    onSubmit(email, result);
    setEmail(""); setDone(true); setTimeout(() => setDone(false), 2000);
  };
  return (
    <section className="c-hero">
      <div className="c-body">
        <h1 className="c-megatype">
          <span className="l1">SPLIT THE</span>
          <span className="l2"><span className="crossed">SPREADSHEET</span> <em>noooo</em></span>
          <span className="l3"><span className="ko">F*CKING BILL</span> <span className="red">!!</span></span>
        </h1>

        <div className="c-row">
          <p className="c-pitch">
            Open the app. <span className="hl">Type a number.</span> Tap who's in. Done.
            Built for flatmates, travel crews & friends who can't be bothered to do mental math at 1am.
            <br /><br />
            <span className="scribble">→ no more spreadsheets ever again ✓</span>
          </p>

          <form onSubmit={submit} className="c-signup" id="signup">
            <div className="lab">※ GET IN EARLY</div>
            <div className="form">
              <input
                type="email" placeholder="you@notgreatatmath.com"
                value={email} onChange={(e) => setEmail(e.target.value)}
                disabled={done}
              />
              <button type="submit" className="go">{done ? "✓" : "GO →"}</button>
            </div>
            <div className="ct">
              <span><b>{fmtNum(signups)}</b> already in</span>
              <span>POS. #{fmtNum(signups + 1)}</span>
            </div>
          </form>
        </div>
      </div>

      {stickersOn && (
        <>
          <DragSticker className="c-stk k1" baseTransform="rotate(8deg)">FAST AS HELL</DragSticker>
          <DragSticker className="c-stk k2" baseTransform="rotate(-12deg)">GEN-Z<br/>APPROVED</DragSticker>
          <DragSticker className="c-stk k3" baseTransform="rotate(-4deg)">// shipping soon</DragSticker>
          <DragSticker className="c-stk k4" baseTransform="translateY(-50%) rotate(-8deg)">EAT · PAY · DASH</DragSticker>
          <DragSticker className="c-stk k5" baseTransform="rotate(-6deg)">try it →</DragSticker>
        </>
      )}

      <svg className="c-arrow" width="180" height="60" viewBox="0 0 180 60" aria-hidden="true">
        <path d="M5 40 Q 50 5, 100 30 T 175 25" stroke="#FF3D00" strokeWidth="5" fill="none" strokeLinecap="round" />
        <path d="M155 12 L 175 25 L 158 40" stroke="#FF3D00" strokeWidth="5" fill="none" strokeLinecap="round" strokeLinejoin="round" />
      </svg>
    </section>
  );
}

function CWhat(){
  return (
    <section className="c-what" id="what">
      <div className="c-section-head rv">
        <span className="c-num">№ 01</span>
        <h2>OK BUT WHAT IS IT?</h2>
        <span className="c-tag">↓↓ KEEP READING ↓↓</span>
      </div>

      <div className="c-what-grid">
        <div className="receipt r1 rv rv-l">
          <div className="r-top">★★★★★ DA RESTAURANT</div>
          <div className="r-line"><span>PIZZA (4)</span><span>£42.00</span></div>
          <div className="r-line"><span>WINE (2)</span><span>£28.00</span></div>
          <div className="r-line"><span>TIRAMISU</span><span>£8.50</span></div>
          <div className="r-line"><span>SERVICE 12.5%</span><span>£9.81</span></div>
          <div className="r-line r-tot"><span>TOTAL</span><span>£88.31</span></div>
          <div className="r-stamp">✗ THE OLD WAY ✗</div>
          <div className="r-bottom">▓▓▓▓▓ TIME: 47 SEC ▓▓▓▓▓</div>
        </div>

        <div className="c-pull rv">
          <div className="c-pull-mark">"</div>
          <div className="c-pull-q">
            we're not building <s>another finance app</s>.
            <br />we're <span className="hl">killing the spreadsheet</span>.
          </div>
          <div className="c-pull-cite">— THE SPLITFAST CREW</div>
        </div>

        <div className="receipt r2 rv rv-r">
          <div className="r-top">⚡⚡ SPLITFAST APP ⚡⚡</div>
          <div className="r-line"><span>OPEN APP</span><span>0.4s</span></div>
          <div className="r-line"><span>TYPE 88.31</span><span>0.9s</span></div>
          <div className="r-line"><span>TAP 4 PEOPLE</span><span>0.4s</span></div>
          <div className="r-line r-tot"><span>DONE.</span><span>1.8s</span></div>
          <div className="r-stamp green">✓ THE NEW WAY ✓</div>
          <div className="r-bottom">★ KEEP UR LIFE GOING ★</div>
        </div>
      </div>

      <p className="c-payoff-line rv">
        SPLITWISE'S JOB · <span className="dot">●</span> · REVOLUT'S PRECISION · <span className="dot">●</span> · LINEAR'S SPEED
      </p>
    </section>
  );
}

function CHow(){
  const steps = [
    { n:"1", color:"#FF3D00", title:"BANG IT IN", body:"Tap (+). Type the number. Or just photograph the receipt and we'll do the squinting. No description. No category. No 'currency conversion settings' menu of doom.", time:"0.8s" },
    { n:"2", color:"#1F4DFF", title:"PICK UR PPL", body:"Yr group is already there from last time. Tap the people who were in. Equal split by default. Long-press anyone if Mo had the lobster.", time:"1.2s" },
    { n:"3", color:"#00C853", title:"BYE 👋", body:"Everyone in the group sees it instantly. Balances net automatically. One tap to settle when you're ready (or not, idc).", time:"0.4s" },
  ];
  return (
    <section className="c-how" id="how">
      <div className="c-section-head light rv">
        <span className="c-num">№ 02</span>
        <h2>HOW THE HELL IT WORKS</h2>
        <span className="c-tag">↓↓ 3 STEPS ↓↓</span>
      </div>
      <div className="c-step-grid rv-group">
        {steps.map((s, i) => (
          <article key={i} className="c-step rv" style={{ background: s.color, '--d': i }}>
            <div className="c-step-top">
              <span className="c-step-num">{s.n}</span>
              <span className="c-step-time">⏱ {s.time}</span>
            </div>
            <h3>{s.title}</h3>
            <p>{s.body}</p>
            <div className="c-step-tape"></div>
          </article>
        ))}
      </div>
      <div className="c-phone-spot rv">
        <AnimatedPhone />
        <div className="c-phone-arrow">
          <span>← LIKE THIS, ROUGHLY</span>
        </div>
      </div>
    </section>
  );
}

function CWhy(){
  return (
    <section className="c-why" id="why">
      <div className="c-section-head rv">
        <span className="c-num">№ 03</span>
        <h2>WHY R WE EVEN DOING THIS</h2>
        <span className="c-tag">★ A RANT ★</span>
      </div>

      <div className="c-rant rv-group">
        <p className="line rv" style={{'--d':0}}><span className="hl-y">money between friends</span> shouldn't feel like work.</p>
        <p className="line rv" style={{'--d':1}}>it should feel like passing the phone across the table.</p>
        <p className="line rv" style={{'--d':2}}>but somehow, in <s>2026</s>, it still feels like:</p>
        <ul className="c-rant-list rv" style={{'--d':3}}>
          <li>opening 4 different apps</li>
          <li>arguing about who paid for what</li>
          <li>"i'll send u a venmo later" (he won't)</li>
          <li>a spreadsheet at the end of every trip</li>
          <li>weird tension @ brunch</li>
        </ul>
        <p className="line big rv" style={{'--d':4}}>SO WE'RE FIXING IT.<br/><span className="hl-r">RUDELY.</span></p>
        <p className="line small rv" style={{'--d':5}}>— the splitfast crew, bengaluru, 2026</p>
      </div>
    </section>
  );
}

function CStats({ signups }){
  const ref = useRef(null);
  const [vis, setVis] = useState(false);
  useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver(es => { if (es[0].isIntersecting){ setVis(true); io.disconnect(); }}, { threshold: 0.2 });
    io.observe(ref.current); return () => io.disconnect();
  }, []);
  const a = useCountUp(vis ? 180 : 0, 1400);
  const b = useCountUp(vis ? signups : 0, 1600);
  const c = useCountUp(vis ? 1247 : 0, 1500);
  const d = useCountUp(vis ? 23 : 0, 1100);
  return (
    <section className="c-stats" ref={ref} id="stats">
      <div className="c-section-head light rv">
        <span className="c-num">№ 04</span>
        <h2>NUMBERS GO UP</h2>
        <span className="c-tag">★ LIVE ★</span>
      </div>
      <div className="c-stats-grid rv-group">
        <div className="c-stat rv" style={{ background:"#FFE600", color:"#0A0A0A", '--d':0 }}>
          <div className="c-stat-v">{(a/100).toFixed(1)}<span>s</span></div>
          <div className="c-stat-k">avg time-to-split</div>
          <div className="c-stat-tag">↓ FASTER THAN U</div>
        </div>
        <div className="c-stat rv" style={{ background:"#FF3D00", color:"#fff", '--d':1 }}>
          <div className="c-stat-v">{fmtNum(b)}</div>
          <div className="c-stat-k">on the waitlist</div>
          <div className="c-stat-tag">↑ +83/DAY</div>
        </div>
        <div className="c-stat rv" style={{ background:"#1F4DFF", color:"#fff", '--d':2 }}>
          <div className="c-stat-v">{fmtNum(c)}</div>
          <div className="c-stat-k">bills split (beta)</div>
          <div className="c-stat-tag">★ £88,420 RECONCILED</div>
        </div>
        <div className="c-stat rv" style={{ background:"#00C853", color:"#0A0A0A", '--d':3 }}>
          <div className="c-stat-v">{d}</div>
          <div className="c-stat-k">currencies @ launch</div>
          <div className="c-stat-tag">→ INC. EUR, USD, GBP</div>
        </div>
        <div className="c-stat rv" style={{ background:"#0A0A0A", color:"#fff", '--d':4 }}>
          <div className="c-stat-v">£0</div>
          <div className="c-stat-k">monthly fee</div>
          <div className="c-stat-tag">★ 4EVA ★</div>
        </div>
        <div className="c-stat rv" style={{ background:"#FF6FB5", color:"#0A0A0A", '--d':5 }}>
          <div className="c-stat-v">100%</div>
          <div className="c-stat-k">end-2-end encrypted</div>
          <div className="c-stat-tag">YR DATA = YOURS</div>
        </div>
      </div>
    </section>
  );
}

function CMarquee(){
  const items = ["NO MATH AT DINNER", "★", "NO MORE SPREADSHEETS", "★", "NO MORE \"I'LL VENMO U LATER\"", "★", "NO MORE SQUINTING AT RECEIPTS", "★", "NO MORE WEIRD BRUNCH ENERGY", "★"];
  return (
    <div className="c-marq">
      <div className="c-marq-track">
        {Array(3).fill(0).map((_, i) => (
          <div className="c-marq-row" key={i}>
            {items.map((it, j) => <span key={j}>{it}</span>)}
          </div>
        ))}
      </div>
    </div>
  );
}

function CFoot({ signups, onSubmit, konamiActive }){
  const [email, setEmail] = useState("");
  const [done, setDone] = useState(false);
  const submit = async (e) => {
    e.preventDefault();
    if (!email) return;
    sound.coin();
    const result = await submitToWaitlist(email, konamiActive);
    onSubmit(email, result);
    setEmail(""); setDone(true); setTimeout(() => setDone(false), 2000);
  };
  return (
    <footer className="c-foot">
      <div className="c-foot-row rv">
        <div>
          <h3>LAST CALL.</h3>
          <p>{fmtNum(signups)} ppl already in. one email when we launch — that's the whole thing.</p>
          <form onSubmit={submit} className="c-foot-form">
            <input type="email" placeholder="you@notgreatatmath.com" value={email} onChange={(e)=>setEmail(e.target.value)} />
            <button type="submit">{done ? "✓" : "JOIN →"}</button>
          </form>
        </div>
        <div className="c-foot-links">
          <div>
            <h5>★ PRODUCT</h5>
            <a href="#how">features</a>
            <a href="#why">manifesto</a>
            <a href="#what">faq</a>
            <a href="#">changelog</a>
          </div>
          <div>
            <h5>★ COMPANY</h5>
            <a href="#">about</a>
            <a href="#">press</a>
            <a href="#">careers</a>
            <a href="mailto:leveragelifeofficial@gmail.com">contact</a>
          </div>
          <div>
            <h5>★ LEGAL</h5>
            <a href="/privacy">privacy</a>
            <a href="/privacy">terms</a>
            <a href="#">security</a>
            <a href="#">status</a>
          </div>
        </div>
      </div>
      <div className="c-foot-mega rv">
        <span>SPLIT</span><span className="x">FAST</span><span className="bang">!!</span>
      </div>
      <div className="c-foot-legal">
        <span>&copy; 2026 SPLITFAST &middot; MADE IN BENGALURU</span>
        <span>v0.0.1 / build 23a87f4</span>
        <span>&uarr;&uarr;&darr;&darr;&larr;&rarr;&larr;&rarr;BA</span>
      </div>
    </footer>
  );
}

function CToast({ data, onClose }){
  useEffect(() => {
    const id = setTimeout(onClose, 5000);
    return () => clearTimeout(id);
  }, [onClose]);
  return (
    <div className="c-toast" onClick={onClose}>
      <div className="c-toast-card" onClick={(e) => e.stopPropagation()}>
        <div className="c-toast-icon">{data.boosted ? "⚡" : "✓"}</div>
        <div className="c-toast-body">
          <div className="c-toast-title">
            {data.boosted ? "CHEAT CODE ACTIVATED" : "YOU'RE ON THE LIST"}
          </div>
          <div className="c-toast-pos">
            POSITION <span>#{fmtNum(data.position)}</span>
          </div>
          {data.boosted && (
            <div className="c-toast-boost">you jumped ahead. respect.</div>
          )}
          <div className="c-toast-sub">we'll email you when it's go time.</div>
        </div>
        <button className="c-toast-close" onClick={onClose}>✕</button>
      </div>
    </div>
  );
}

function CKonami({ onClose }){
  return (
    <div className="c-konami" onClick={onClose}>
      <div className="c-konami-card" onClick={(e) => e.stopPropagation()}>
        <div className="c-k-tag">★ SECRET UNLOCKED ★</div>
        <h2>U FOUND THE EASTER EGG</h2>
        <p>respect. we're slipping you to the front of the waitlist. sign up now &amp; skip the queue.</p>
        <button onClick={onClose}>OK COOL</button>
      </div>
    </div>
  );
}

function App(){
  const [signups, setSignups] = useState(12847);
  const [muted, setMuted] = useState(false);
  const [konami, setKonami] = useState(false);

  useEffect(() => { sound.setMuted(muted); }, [muted]);
  useEffect(() => {
    const id = setInterval(() => setSignups(s => s + (Math.random() < 0.6 ? 1 : 0)), 4200);
    return () => clearInterval(id);
  }, []);

  useEffect(() => {
    const v = VIBES[RANDOM_VIBE] || VIBES.yellow;
    const r = document.documentElement.style;
    r.setProperty("--c-bg", v.bg);
    r.setProperty("--c-ink", v.ink);
    r.setProperty("--c-red", v.red);
    r.setProperty("--c-blue", v.blue);
    r.setProperty("--c-green", v.green);
  }, []);

  useEffect(() => {
    if (typeof Lenis === 'undefined') return;
    const lenis = new Lenis({
      duration: 1.4,
      easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
      touchMultiplier: 2,
    });
    const marqTrack = document.querySelector('.c-marq-track');
    let marqAnim = null;
    function raf(time) {
      lenis.raf(time);
      if (marqTrack && !marqAnim) {
        const a = marqTrack.getAnimations();
        if (a.length) marqAnim = a[0];
      }
      if (marqAnim) {
        const v = Math.abs(lenis.velocity);
        marqAnim.playbackRate += (1 + Math.min(v * 0.15, 4) - marqAnim.playbackRate) * 0.1;
      }
      requestAnimationFrame(raf);
    }
    requestAnimationFrame(raf);
    return () => lenis.destroy();
  }, []);

  useEffect(() => {
    const els = document.querySelectorAll('.rv');
    if (!els.length) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          e.target.classList.add('shown');
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.15, rootMargin: '0px 0px -60px 0px' });
    els.forEach(el => io.observe(el));
    return () => io.disconnect();
  }, []);

  const [toast, setToast] = useState(null);

  useKonami(() => { setKonami(true); sound.coin(); });
  const onSubmit = (email, result) => {
    setSignups(s => s + 1);
    if (result && result.position) {
      setToast({ position: result.position, boosted: result.boosted });
    }
  };

  return (
    <>
      <LaserPointer />
      <CTopBar />
      <CHero signups={signups} onSubmit={onSubmit} stickersOn={true} konamiActive={konami} />
      <CMarquee />
      <CWhat />
      <CHow />
      <CWhy />
      <CStats signups={signups} />
      <CFoot signups={signups} onSubmit={onSubmit} konamiActive={konami} />
      {konami && <CKonami onClose={() => setKonami(false)} />}
      {toast && <CToast data={toast} onClose={() => setToast(null)} />}
      <button className="c-mute" onClick={() => setMuted(m => !m)} title="toggle sound">
        {muted ? "🔇" : "🔊"}
      </button>
    </>
  );
}

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