// Garner Landing Page — main app component
const { useState, useEffect, useRef } = React;

const TWEAKS = {
  headline: "Your money, finally on your team.",
  subhead: "Garner is the budget app that shows you what's safe to spend right now — and turns staying on top of your money into something you actually enjoy. Hit your goals with a smarter system.",
  ctaText: "Get early access",
  showSurplusToast: true,
  tagline: "BUDGETING THAT FIGHTS FOR YOU"
};

function App() {
  const tweaks = TWEAKS;
  const [submitted, setSubmitted] = useState(false);
  const [position, setPosition] = useState(null);
  const [email, setEmail] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const [submitError, setSubmitError] = useState(null);

  async function submit(e) {
    e.preventDefault();
    if (!email.includes("@") || submitting) return;
    setSubmitting(true);
    setSubmitError(null);

    const url = (window.GARNER_CONFIG && window.GARNER_CONFIG.waitlistUrl) || "";

    if (!url) {
      // Local-dev fallback so the page is testable before the edge function URL is wired in.
      const base = 1247;
      const hash = email.split("").reduce((a, c) => a + c.charCodeAt(0), 0);
      setPosition(base + hash % 137);
      setSubmitted(true);
      setSubmitting(false);
      return;
    }

    try {
      const res = await fetch(url, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          email: email.trim().toLowerCase(),
          source: "landing",
          referrer: typeof document !== "undefined" ? document.referrer || null : null,
        }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok || typeof data.position !== "number") {
        throw new Error(data.error || `HTTP ${res.status}`);
      }
      setPosition(data.position);
      setSubmitted(true);
    } catch (err) {
      console.error("waitlist submit failed", err);
      setSubmitError("Something went wrong — try again in a moment.");
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="page">
      <Nav />
      <Hero
        tweaks={tweaks}
        email={email}
        setEmail={setEmail}
        submit={submit}
        submitted={submitted}
        position={position}
        submitting={submitting}
        submitError={submitError} />

      <SectionProblem />
      <SectionTour />
      <SectionPartner />
      <SectionSystems />
      <SectionAIChat />
      <SectionFlow />
      <SectionFounder />
      <SectionFAQ />
      <SectionFooterCTA email={email} setEmail={setEmail} submit={submit} submitted={submitted} position={position} submitting={submitting} submitError={submitError} />
      <Footer />
    </div>);

}

// ====== NAV ======
function Nav() {
  return (
    <nav className="nav">
      <div className="nav-inner">
        <div className="nav-brand">
          <span className="nav-logo">GARNER</span>
        </div>
        <div className="nav-links">
          <a href="#tour">The app</a>
          <a href="#ai">Garner AI</a>
          <a href="#partner">For couples</a>
          <a href="#faq">FAQ</a>
          <a href="#waitlist" className="nav-cta">Join waitlist</a>
        </div>
      </div>
    </nav>);

}

// ====== HERO ======
function Hero({ tweaks, email, setEmail, submit, submitted, position, submitting, submitError }) {
  return (
    <section className="hero">
      <div className="hero-bg">
        <div className="hero-grid"></div>
        <div className="hero-glow hero-glow-1"></div>
        <div className="hero-glow hero-glow-2"></div>
      </div>
      <div className="hero-inner">
        <div className="hero-text">
          <div className="hero-tagline">
            <img src="assets/lightning.png" alt="" />
            <span>{tweaks.tagline}</span>
          </div>
          <h1 className="hero-headline">{tweaks.headline}</h1>
          <p className="hero-sub">{tweaks.subhead}</p>

          {!submitted ?
          <>
            <form className="hero-form" onSubmit={submit}>
              <input
              type="email"
              placeholder="you@example.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              disabled={submitting}
              required />

              <button type="submit" disabled={submitting}>
                {submitting ? "Joining…" : tweaks.ctaText}
                <span className="cta-arrow">→</span>
              </button>
            </form>
            {submitError && <div className="form-error">{submitError}</div>}
          </> :

          <SuccessCard position={position} />
          }

          <div className="hero-meta">
            <div className="hero-meta-item">
              <img src="assets/sparkle.png" alt="" />
              <span>Beta launching soon</span>
            </div>
            <div className="hero-meta-item">
              <img src="assets/shield.png" alt="" />
              <span>Bank-grade encryption</span>
            </div>
            <div className="hero-meta-item">
              <img src="assets/coins.png" alt="" />
              <span>Free during beta</span>
            </div>
          </div>
        </div>

        <div className="hero-visual">
          <HeroPhoneShowcase showSurplus={tweaks.showSurplusToast} />
        </div>
      </div>
    </section>);

}

function SuccessCard({ position }) {
  return (
    <div className="success-card">
      <div className="success-banner">
        <img src="assets/treasure-chest.png" alt="" />
        <div>
          <div className="success-title">YOU'RE IN THE QUEUE</div>
          <div className="success-sub">Check your inbox for confirmation</div>
        </div>
      </div>
      <div className="position-card">
        <div className="position-label">YOUR POSITION</div>
        <div className="position-num">#{position}</div>
        <div className="position-bar">
          <div className="position-bar-fill" style={{ width: `${Math.min(95, position / 1500 * 100)}%` }}>
            <div className="bar-shine"></div>
          </div>
        </div>
        <div className="position-sub">Move up by sharing your invite link</div>
      </div>
    </div>);

}

function HeroPhoneShowcase({ showSurplus }) {
  // Hero shows HQ screen as the lead, with floating surplus toast and a peek of Tanks behind
  return (
    <div className="hero-phones">
      <div className="hero-phone-back">
        <PhoneFrame label="TANKS" glow="cyan">
          <ScreenTanks active={true} />
        </PhoneFrame>
      </div>
      <div className="hero-phone-front">
        <PhoneFrame label="HQ · are we okay?" glow="gold">
          <ScreenHQ active={true} />
        </PhoneFrame>
      </div>
      {showSurplus &&
      <div className="hero-toast">
          <img src="assets/coins.png" alt="" />
          <div>
            <div className="hero-toast-title">+ $148 SURPLUS</div>
            <div className="hero-toast-sub">Groceries came in under → routed to Vacation</div>
          </div>
        </div>
      }
    </div>);

}

// ====== PROBLEM ======
function SectionProblem() {
  const points = [
  {
    icon: "scroll.png",
    title: "They look backward.",
    body: "Every budget app shows what you already spent. That's like driving by looking in the rearview mirror. You need to see what's coming — which bills hit before payday, what's safe to spend right now, what happens to the timeline if you spend $200 today."
  },
  {
    icon: "lightning.png",
    title: "They ignore timing.",
    body: "Money has a schedule. Paychecks land on the 15th and 30th. Mortgage hits the 1st. Insurance hits quarterly. Static snapshots can't model the tension between when money arrives, when it's owed, and how it flows through time."
  },
  {
    icon: "shield.png",
    title: "They make you do the work.",
    body: "Categorize. Reconcile. Remember. Most apps push the mental load onto you, then guilt you when you stop opening them. Garner does the remembering, so you can focus on the choices, and the wins!"
  }];

  return (
    <section className="problem" id="problem">
      <div className="section-inner">
        <div className="section-eyebrow">THE PROBLEM</div>
        <h2 className="section-h2">Budget apps are built for accounting. <span className="text-gold">Not for real life, or real people.</span></h2>
        <div className="problem-grid">
          {points.map((p, i) =>
          <div className="problem-card" key={i}>
              <img src={`assets/${p.icon}`} alt="" className="problem-icon" />
              <h3>{p.title}</h3>
              <p>{p.body}</p>
            </div>
          )}
        </div>
      </div>
    </section>);

}

// ====== FLOW (Money follows rules) ======
function SectionFlow() {
  const [active, setActive] = useState(0);
  useEffect(() => {
    const intv = setInterval(() => setActive((p) => (p + 1) % 5), 1100);
    return () => clearInterval(intv);
  }, []);

  const nodes = [
  { id: "income", label: "INCOME", sub: "arrives", color: "#00E676", icon: "money-bag.png" },
  { id: "bills", label: "BILLS", sub: "take first", color: "#FF5252", icon: "envelope-beige.png" },
  { id: "you", label: "YOU", sub: "spend next", color: "#BB86FC", icon: "flying-money.png" },
  { id: "surplus", label: "SURPLUS", sub: "what's left", color: "#FFD700", icon: "chest.png" },
  { id: "goals", label: "GOALS", sub: "forward", color: "#22D3EE", icon: "trophy.png" }];


  return (
    <section className="flow" id="flow">
      <div className="section-inner">
        <div className="section-eyebrow">HOW cash ACTUALLY flows</div>
        <h2 className="section-h2">Your money follows rules, <span className="text-purple">like a game.</span></h2>
        <p className="section-lede">It flows in a pattern, every cycle, every paycheck. Most apps show you a static snapshot. Garner shows you the cycle — and helps you end every turn with something left to push you forward.

        </p>

        <div className="flow-diagram">
          <div className="flow-glow" style={{ background: `radial-gradient(circle at 50% 50%, ${nodes[active].color}33, transparent 65%)` }}></div>
          <div className="flow-nodes">
            {nodes.map((n, i) => {
              const isActive = active === i;
              return (
                <div key={n.id} className={`flow-node ${isActive ? "flow-node-active" : ""}`}>
                  <div
                    className="flow-icon-box"
                    style={{
                      borderColor: isActive ? n.color : "var(--card-border)",
                      background: isActive ? `${n.color}22` : "var(--bg)",
                      boxShadow: isActive ? `0 0 28px ${n.color}aa, inset 0 0 14px ${n.color}55` : "none"
                    }}>
                    <img src={`assets/${n.icon}`} alt="" style={{ width: "63.9986px", objectFit: "contain" }} />
                  </div>
                  <div className="flow-label" style={{ color: isActive ? n.color : "var(--text-soft)", textShadow: isActive ? `0 0 10px ${n.color}` : "none" }}>{n.label}</div>
                  <div className="flow-sub">{n.sub}</div>
                  {i < nodes.length - 1 && <div className="flow-arrow" aria-hidden>→</div>}
                </div>);

            })}
          </div>
        </div>

        <p className="flow-coda">
          Garner helps you <span className="text-gold">see the game</span> — and <span className="text-gold">beat the system</span>.<br />Every cycle, every dollar, accounted for and aimed forward.
        </p>
      </div>
    </section>);

}

// ====== TOUR ======
function SectionTour() {
  const [activeIdx, setActiveIdx] = useState(0);
  const stops = [
  {
    key: "hq", label: "HQ", icon: "⚔️",
    title: "“Is it safe to spend?”",
    sub: "Answered at a glance.",
    body: "Never guess if the amount in your account will cover what you want to buy. One glance at Garner's \"Safe to Spend\" calculation tells you what you have on hand for variable/envelope spending, minus what bills are expected to hit before your next pay day. No mental math, no financial angst.",
    screen: ScreenHQ, glow: "gold"
  },
  {
    key: "tanks", label: "Tanks", icon: "🎒",
    title: "Envelopes that show current status.",
    sub: "Spending tracked with ease.",
    body: "Each spending envelope is like a tank. Watch it drain in real time as you swipe your card. FULL → ON TRACK → WATCH IT → LOW. You'll never have to ask “can I afford this?” again — the answer is staring at you.",
    screen: ScreenTanks, glow: "cyan"
  },
  {
    key: "goals", label: "Goals", icon: "🏆",
    title: "Surplus drops like loot.",
    sub: "The reward for being careful.",
    body: "When an envelope finishes the month under budget, Garner detects it and asks where to send it. One tap routes leftover money to the Vacation goal, the Emergency Fund, the dental work. Frugality, finally with a payoff you can see.",
    screen: ScreenGoals, glow: "gold"
  }];


  return (
    <section className="tour" id="tour">
      <div className="section-inner">
        <div className="section-eyebrow">THE APP</div>
        <h2 className="section-h2">Three screens. <span className="text-cyan">easy answers</span> for all your $$.</h2>
        <p className="section-lede">Garner reduces money to a few honest visuals. Open the app. Read the picture. Move on with your day.</p>

        <div className="tour-tabs">
          {stops.map((s, i) =>
          <button
            key={s.key}
            className={`tour-tab ${activeIdx === i ? "tour-tab-active" : ""}`}
            onClick={() => setActiveIdx(i)}>

              <span className="tour-tab-icon">{s.icon}</span>
              <span>{s.label}</span>
            </button>
          )}
        </div>

        <div className="tour-stage">
          {stops.map((s, i) => {
            const Screen = s.screen;
            return (
              <div className={`tour-frame ${activeIdx === i ? "tour-frame-active" : ""}`} key={s.key}>
                <div className="tour-copy">
                  <div className="tour-step">{String(i + 1).padStart(2, "0")} / 0{stops.length}</div>
                  <h3 className="tour-title">{s.title}</h3>
                  <div className="tour-sub" style={{ color: "rgb(34, 211, 238)" }}>{s.sub}</div>
                  <p className="tour-body">{s.body}</p>
                </div>
                <div className="tour-phone-wrap">
                  <PhoneFrame label={s.label} glow={s.glow}>
                    <Screen active={activeIdx === i} />
                  </PhoneFrame>
                </div>
              </div>);

          })}
        </div>
      </div>
    </section>);

}

// ====== PARTNER ======
function SectionPartner() {
  return (
    <section className="partner" id="partner">
      <div className="section-inner partner-inner">
        <div className="partner-text">
          <div className="section-eyebrow">FOR BOTH OF YOU</div>
          <h2 className="section-h2">No more <span className="text-red">“bad-guy conversation.”</span></h2>
          <p className="section-lede">One partner usually carries the financial picture in their head. The other gets surprised (or does the surprising!). Garner ends that.

          </p>
          <p className="partner-body">
            When the question comes up — “Can we take a trip?” “Should we replace the dishwasher?” — you both look at the same screen. The Vacation goal is at 42%. Surplus is $659/month. The math is on the wall, not in someone's head.
          </p>
          <div className="partner-quote">
            <img src="assets/sparkle.png" alt="" />
            <div>
              <div className="partner-quote-text">“The app is the shared language for money. The bad-guy conversation just… stops happening.”</div>
              <div className="partner-quote-attr">— Built for households like ours</div>
            </div>
          </div>
        </div>
        <div className="partner-visual">
          <div className="partner-couple">
            <div className="partner-bubble partner-bubble-left">
              <div className="partner-bubble-name">Joseph</div>
              <div>“Can we afford a beach trip in June?”</div>
            </div>
            <div className="partner-phone">
              <PhoneFrame label="On both phones" glow="purple">
                <ScreenGoals active={true} />
              </PhoneFrame>
            </div>
            <div className="partner-bubble partner-bubble-right">
              <div className="partner-bubble-name">Perla</div>
              <div>“Looks like August. I'm in.”</div>
            </div>
          </div>
        </div>
      </div>
    </section>);

}

// ====== SYSTEMS ======
function SectionSystems() {
  return (
    <section className="systems" id="systems">
      <div className="section-inner">
        <div className="section-eyebrow">THREE SYSTEMS possible</div>
        <h2 className="section-h2">Personal, rentals, Business. <span className="text-purple">One tap to switch lenses.</span></h2>
        <p className="section-lede">Combining your household, your rental property, and your side business in one chart creates a false picture. Garner keeps them clean and lets you switch with a single tap. Each has it's own goals, budgets and income, but Garner knows them all in context with each other.</p>
        <SystemSwitcher active={true} />
      </div>
    </section>);

}

// ====== AI CHAT ======
function SectionAIChat() {
  return (
    <section className="aichat" id="ai">
      <div className="section-inner aichat-inner">
        <div className="aichat-visual">
          <PhoneFrame label="Ask Garner" glow="purple">
            <ScreenChat active={true} />
          </PhoneFrame>
        </div>
        <div className="aichat-text">
          <div className="section-eyebrow">ALWAYS-ON AI COACH</div>
          <h2 className="section-h2">Talk to Garner like a <span className="text-gold" style={{ color: "rgb(34, 211, 238)" }}>friend who knows the books.</span></h2>
          <p className="section-lede">
            Garner is more than a dashboard. Ask any question about your money in plain English and get an answer rooted in your actual numbers — not generic advice from the internet.
          </p>
          <ul className="aichat-list">
            <li style={{ color: "rgb(34, 211, 238)" }}><span style={{ color: "rgb(34, 211, 238)" }}>→</span> “Can we afford a $3,000 vacation in June?”</li>
            <li style={{ color: "rgb(34, 211, 238)" }}><span style={{ color: "rgb(34, 211, 238)" }}>→</span> “Which bills are funded for next paycheck?”</li>
            <li style={{ color: "rgb(34, 211, 238)" }}><span style={{ color: "rgb(34, 211, 238)" }}>→</span> “How much would $50/mo less on takeout move my goals?”</li>
            <li style={{ color: "rgb(34, 211, 238)" }}><span style={{ color: "rgb(34, 211, 238)" }}>→</span> “What changed in our spending last week?”</li>
          </ul>
        </div>
      </div>
    </section>);

}

// ====== FOUNDER ======
function SectionFounder() {
  return (
    <section className="founder" id="founder">
      <div className="section-inner founder-inner">
        <div className="founder-aside">
          <div className="founder-avatar">
            <img src="assets/garner-guy.png" alt="" />
          </div>
          <div className="founder-tag">FROM THE FOUNDER</div>
        </div>
        <div className="founder-body">
          <h2 className="section-h2 founder-h2">Built by a household, for households.</h2>
          <p>I'm Joseph. My wife and I have a rental property, two businesses, two kids, and six insurance policies between us. We both have ADHD. Every budgeting app we tried punished us for not being accountants.
We always felt, what I call "cash flow blindness".
          </p>
          <p>So I built the app we actually wanted. The one that does the remembering. The one that shows both of us the same picture. The one that turns staying on top of money into something I open in the morning instead of a chore I avoid.

          </p>
          <p>
            <b>Garner is the result.</b> If your money has timing, if your household has more than one person, if you've ever opened a budget app and immediately closed it, hell, if you've ever worried about $, or needed more of it, this is for you.
          </p>
          <div className="founder-sign">— Joseph, founder</div>
        </div>
      </div>
    </section>);

}

// ====== FAQ ======
function SectionFAQ() {
  const [open, setOpen] = useState(0);
  const faqs = [
  { q: "When does the beta open?", a: "We're rolling out access in waves over the coming weeks. Sign up and we'll email you when your spot opens — first signups, first invites." },
  { q: "Is my bank data safe?", a: "Garner connects through Plaid (the same provider used by Venmo, Robinhood, and most modern finance apps). Your bank credentials never touch our servers, and balances are read-only." },
  { q: "Will it cost money?", a: "Beta is free. We'll have transparent pricing at launch with a generous free tier — we want this to be the default budget app for households, not a paywalled tool." },
  { q: "Does it work for couples / shared accounts?", a: "Yes — Garner is designed from the ground up for two-person households. Both partners see the same picture in real time, so the “can we afford this?” conversation happens with shared data, not someone's memory." },
  { q: "What if I'm self-employed or have irregular income?", a: "Garner uses historical averages for variable streams (gigs, commissions, side businesses) and known amounts for fixed ones (W-2 paychecks, dividends). It's built for messy, real-world income — not just salary." },
  { q: "Can I track rental properties, gig-work, or a small business separately?", a: "Yes. Garner has three independent systems — Personal, Rentals, and Business — that never bleed into each other. Switch lenses in one tap." }];

  return (
    <section className="faq" id="faq">
      <div className="section-inner faq-inner">
        <div className="section-eyebrow">QUESTIONS</div>
        <h2 className="section-h2">Stuff people ask <span className="text-cyan">before they sign up.</span></h2>
        <div className="faq-list">
          {faqs.map((f, i) =>
          <div className={`faq-item ${open === i ? "faq-item-open" : ""}`} key={i} onClick={() => setOpen(open === i ? -1 : i)}>
              <div className="faq-q">
                <span>{f.q}</span>
                <span className="faq-toggle">{open === i ? "−" : "+"}</span>
              </div>
              {open === i && <div className="faq-a">{f.a}</div>}
            </div>
          )}
        </div>
      </div>
    </section>);

}

// ====== FOOTER CTA ======
function SectionFooterCTA({ email, setEmail, submit, submitted, position, submitting, submitError }) {
  return (
    <section className="footer-cta" id="waitlist">
      <div className="section-inner footer-cta-inner">
        <img src="assets/treasure-chest.png" alt="" className="footer-cta-icon" />
        <h2 className="footer-cta-h2">Get your money on your team.</h2>
        <p className="footer-cta-sub">Join the beta waitlist. Be first in when the doors open.</p>
        {!submitted ?
        <>
          <form className="hero-form footer-cta-form" onSubmit={submit}>
            <input
            type="email"
            placeholder="you@example.com"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            disabled={submitting}
            required />

            <button type="submit" disabled={submitting}>
              {submitting ? "Joining…" : "Join the waitlist"} <span className="cta-arrow">→</span>
            </button>
          </form>
          {submitError && <div className="form-error">{submitError}</div>}
        </> :

        <SuccessCard position={position} />
        }
        <div className="footer-cta-meta">No spam. One email when your beta spot is ready.</div>
      </div>
    </section>);

}

// ====== FOOTER ======
function Footer() {
  return (
    <footer className="footer">
      <div className="footer-inner">
        <div className="footer-brand">
          <span className="nav-logo">GARNER</span>
          <span className="footer-tag">Budgeting that fights for you.</span>
        </div>
        <div className="footer-meta">
          <span>© 2026 Garner</span>
          <a href="#">Privacy</a>
          <a href="#">Terms</a>
          <a href="#">Contact</a>
        </div>
      </div>
    </footer>);

}

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