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

/* ========================== ICONS / WORDMARK ========================== */
const LiwayMark = ({ size = 36, color = "currentColor" }) => (
  <svg width={size} height={size} viewBox="0 0 1024 1024" fill="none" aria-hidden="true">
    <g stroke={color} fill="none" strokeMiterlimit="10">
      <circle cx="361" cy="292.43" r="69.76" strokeWidth="55"/>
      <circle cx="361" cy="731.57" r="69.76" strokeWidth="55"/>
      <circle cx="663" cy="731.57" r="69.76" strokeWidth="55"/>
    </g>
    <rect x="345.23" y="388.85" width="31.54" height="232.43" fill={color}/>
    <rect x="432.7" y="715.6" width="105.97" height="31.54" fill={color}/>
  </svg>
);

const Wordmark = ({ height = 28, color = "currentColor" }) => (
  <svg height={height} viewBox="0 0 447.04 196.48" fill={color} aria-label="liway">
    <path d="M0,0h21.11v124.61c0,4.96,2.64,7.43,7.93,7.43h7.32v20.5h-9.42c-7.7,0-14.04-1.98-19.04-5.94-5.27-4.03-7.9-10.8-7.9-20.32V0Z"/>
    <path d="M55.87,0h21.11v21.75h-21.11V0ZM55.87,43.94h21.11v108.6h-21.11V43.94Z"/>
    <path d="M168.01,76.46h-.41l-21.99,76.09h-18.65l-33.64-108.6h22.4l20.16,76.18h.41l23.92-76.18h15.3l23.92,76.18h.41l20.06-76.18h22.4l-33.54,108.6h-18.75l-21.99-76.09Z"/>
    <path d="M316.59,142.92h-.41c-1.96,3.69-5,6.41-9.12,8.16-4.05,1.81-9.66,2.72-16.81,2.72-11.75-.14-20.8-3.35-27.14-9.62-6.69-6.14-10.03-13.98-10.03-23.54s2.9-16.7,8.71-22.7c5.81-6.14,14.32-9.27,25.53-9.42h29.27v-11.46c.14-9.6-7.06-14.26-21.58-13.98-5.27,0-9.42.56-12.46,1.68-3.18,1.33-5.68,3.58-7.5,6.73l-16.62-13.09c8.03-10.82,19.88-16.09,35.54-15.81,13.23-.14,23.79,2.44,31.69,7.74,7.9,5.44,11.91,14.79,12.05,28.04v74.18h-21.11v-9.62ZM316.59,106.5h-25.38c-12.32.28-18.41,4.64-18.27,13.09,0,3.7,1.59,6.84,4.77,9.42,3.04,2.86,8.09,4.29,15.12,4.29,8.86.14,15.12-.94,18.78-3.25,3.31-2.3,4.97-7.54,4.97-15.71v-7.85Z"/>
    <path d="M352.06,43.94h22.38l24.91,76.08h.41l24.81-76.08h22.48l-45.26,131.09c-2.9,8.16-6.92,13.81-12.05,16.95-5.2,3-11.07,4.5-17.62,4.5h-6.99v-20.5h6.18c2.77,0,5.33-.77,7.69-2.31,2.36-1.61,4.02-3.98,4.96-7.13l5.77-18.24-37.67-104.38Z"/>
  </svg>
);

const Arrow = ({ size = 14 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M5 12h14M13 5l7 7-7 7"/>
  </svg>
);

/* ========================== NAV ========================== */
const Nav = () => (
  <header className="nav">
    <div className="container nav-inner">
      <a href="/" className="nav-logo is-visible nav-lockup" aria-label="liway home">
        <LiwayMark size={28} />
        <Wordmark height={20} color="currentColor" />
      </a>
      <nav className="nav-links">
        <a href="/">Home</a>
        <a href="https://my.liway.app" className="nav-cta">My liway <Arrow size={12}/></a>
      </nav>
    </div>
  </header>
);

/* ========================== INTERACTIVE LEEWAY METER ========================== */
const LEEWAY_THRESHOLD_TIGHT = 500;

const verdictFor = (available) => {
  if (available < 0) return { level: "risk", label: "RISK: you'll run short", color: "var(--risk-fg)" };
  if (available <= LEEWAY_THRESHOLD_TIGHT) return { level: "tight", label: "TIGHT: close but covered", color: "var(--tight-fg)" };
  return { level: "safe", label: "SAFE through payday", color: "var(--safe-fg)" };
};

const InteractiveLeeway = ({ initialBalance = 1464, initialBills = 280 }) => {
  const [balance, setBalance] = useState(initialBalance);
  const [bills, setBills] = useState(initialBills);

  const available = useMemo(() => balance - bills, [balance, bills]);
  const verdict = useMemo(() => verdictFor(available), [available]);

  // Position marker as a function of available / balance — clamp 0–100
  const fillPct = balance > 0 ? Math.max(0, Math.min(100, (available / balance) * 100)) : 0;
  const billPct = balance > 0 ? Math.max(0, Math.min(100, (bills / balance) * 100)) : 0;

  return (
    <div className="hlw-interactive">
      <div className={`leeway-card hlw-card hlw-card-${verdict.level}`} role="figure" aria-label="Interactive leeway projection">
        <div className="leeway-head">
          <span className="leeway-label">YOUR LEEWAY</span>
          <span className={`leeway-status ${verdict.level}`}>● {verdict.label}</span>
        </div>
        <div className="leeway-track">
          <div className={`leeway-fill hlw-fill-${verdict.level}`} style={{width: `${fillPct}%`}}/>
          <div className="leeway-bill" style={{left: `${billPct}%`}}>
            <span className="leeway-bill-tick"/>
            <span className="leeway-bill-label">${bills.toLocaleString()}</span>
          </div>
          <div className="leeway-marker" style={{left: `${fillPct}%`}}>
            <div className="leeway-marker-bubble">${available.toLocaleString()}</div>
            <div className="leeway-marker-today">headroom</div>
          </div>
        </div>
        <div className="leeway-foot">
          <span><strong>Apr 22</strong> · last paycheck</span>
          <span><strong>Apr 30</strong> · payday</span>
        </div>
      </div>

      <div className="hlw-controls">
        <label className="hlw-slider">
          <span className="hlw-slider-label">Bank balance</span>
          <span className="hlw-slider-value">${balance.toLocaleString()}</span>
          <input type="range" min="0" max="5000" step="50" value={balance} onChange={(e) => setBalance(Number(e.target.value))}/>
        </label>
        <label className="hlw-slider">
          <span className="hlw-slider-label">Bills coming up</span>
          <span className="hlw-slider-value">${bills.toLocaleString()}</span>
          <input type="range" min="0" max="3000" step="20" value={bills} onChange={(e) => setBills(Number(e.target.value))}/>
        </label>
      </div>
    </div>
  );
};

/* ========================== HERO ========================== */
const HlwHero = () => (
  <section className="section hlw-hero" id="main">
    <div className="container">
      <header className="section-head">
        <p className="eyebrow">How liway works</p>
        <h1 className="display hlw-display">
          The math behind your{" "}
          <em className="serif-newsreader">headroom.</em>
        </h1>
        <p className="lede">
          A worked example, end to end. The formula, the verdicts, and the receipt. No spreadsheets, no jargon.
        </p>
      </header>
      <InteractiveLeeway />
      <p className="hlw-hint">
        Drag the sliders. The number you see is the same one your real account would show.
      </p>
    </div>
  </section>
);

/* ========================== TERMS YOU'LL SEE ========================== */
const TERM_CARDS = [
  {
    word: "liway",
    role: "the app",
    body: "Pronounced like “leeway.” That's deliberate. The word inspired the name."
  },
  {
    word: "Leeway",
    role: "the number we compute",
    body: "Your dollar amount of safe-to-spend room before payday. The headline number on every screen of the app."
  },
  {
    word: "headroom",
    role: "the everyday word for it",
    body: "“How much room do I have?” is what most people actually ask. We use both words on purpose. Pick whichever feels natural."
  }
];

const TermCards = () => (
  <section className="section hlw-terms">
    <div className="container">
      <header className="section-head">
        <p className="eyebrow">A few words you'll see</p>
        <h2 className="section-title">Three words. <em className="serif-newsreader">One simple idea.</em></h2>
        <p className="section-intro">
          You'll hear us use these words around here. They're close cousins, not jargon. Here's what each one means.
        </p>
      </header>
      <div className="terms-grid">
        {TERM_CARDS.map((t) => (
          <article className="term-card" key={t.word}>
            <h3 className="term-word">{t.word}</h3>
            <p className="term-role">{t.role}</p>
            <p className="term-explain">{t.body}</p>
          </article>
        ))}
      </div>
    </div>
  </section>
);

/* ========================== HOW WE FIGURE IT OUT ========================== */
const HowWeFigure = () => (
  <section className="section hlw-figure">
    <div className="container">
      <header className="section-head">
        <p className="eyebrow">How we figure it out</p>
        <h2 className="section-title">Your real headroom is what's left after what's coming.</h2>
        <p className="section-intro">
          We take what's actually in your account and subtract what's already promised: bills, autopays, the things you can't easily change. The number that's left is yours to spend, without surprises.
        </p>
      </header>
      <div className="figure-pills">
        <div className="figure-pill figure-pill-balance">
          <span className="figure-pill-label">In your account</span>
          <span className="figure-pill-amount">$1,464</span>
          <span className="figure-pill-caption">Live from your bank</span>
        </div>
        <span className="figure-op">minus</span>
        <div className="figure-pill figure-pill-bills">
          <span className="figure-pill-label">Already promised</span>
          <span className="figure-pill-amount">$280</span>
          <span className="figure-pill-caption">CC autopay coming up</span>
        </div>
        <span className="figure-op">equals</span>
        <div className="figure-pill figure-pill-leeway">
          <span className="figure-pill-label">Yours to spend</span>
          <span className="figure-pill-amount">$1,184</span>
          <span className="figure-pill-caption">Real headroom, no surprises</span>
        </div>
      </div>
    </div>
  </section>
);

/* ========================== THREE STATES ========================== */
const VerdictMini = ({ level, label, headline, story }) => (
  <div className={`verdict-card verdict-${level}`}>
    <span className={`verdict-pill ${level}`}>● {label}</span>
    <h3 className="verdict-headline">{headline}</h3>
    <p className="verdict-story">{story}</p>
  </div>
);

const Verdicts = () => (
  <section className="section hlw-verdicts">
    <div className="container">
      <header className="section-head">
        <p className="eyebrow">Three states</p>
        <h2 className="section-title">You'll see one of three answers.</h2>
        <p className="section-intro">
          liway doesn't grade you or score you. It just tells you where your cycle stands. So you can decide what to do, not feel judged.
        </p>
      </header>
      <div className="verdicts-grid">
        <VerdictMini
          level="safe"
          label="SAFE"
          headline="Plenty of headroom."
          story="The cycle ends well above zero. Spend with confidence. Check back tomorrow."
        />
        <VerdictMini
          level="tight"
          label="TIGHT"
          headline="Close, but covered."
          story="Bills are paid; the buffer is thin. Big discretionary purchases can wait until payday."
        />
        <VerdictMini
          level="risk"
          label="RISK"
          headline="Action needed."
          story="You won't make it without a move. liway shows the day balance hits zero, so you can act before the bank does."
        />
      </div>
    </div>
  </section>
);

/* ========================== WHY THIS MATTERS ========================== */
const WhyMatters = () => (
  <section className="section hlw-why">
    <div className="container hlw-why-inner">
      <p className="eyebrow">Why this matters</p>
      <h2 className="section-title">Most apps show you the balance. <em className="serif-newsreader">liway shows what's actually safe to spend.</em></h2>
      <div className="contrast-grid">
        <div className="contrast-col contrast-them">
          <h3>What you usually see</h3>
          <p className="contrast-big">$1,464</p>
          <p className="contrast-caption">"You have $1,464 in checking."</p>
          <p className="contrast-body">
            True, but it doesn't tell you whether dinner tonight is fine, because it doesn't account for what's already on its way out.
          </p>
        </div>
        <div className="contrast-col contrast-us">
          <h3>What liway shows you</h3>
          <p className="contrast-big">$1,184</p>
          <p className="contrast-caption">"That's your real headroom."</p>
          <p className="contrast-body">
            The $280 autopay is already set aside, so you can spend the full $1,184 without overdrafting. The math is the receipt.
          </p>
        </div>
      </div>
    </div>
  </section>
);

/* ========================== FINAL CTA ========================== */
const FinalCTA = () => (
  <section className="cta-block hlw-cta">
    <div className="cta-bg" aria-hidden="true">
      <svg viewBox="0 0 1024 1024" className="cta-bg-mark" fill="none" stroke="currentColor" strokeWidth="55">
        <circle cx="361" cy="292.43" r="69.76"/>
        <circle cx="361" cy="731.57" r="69.76"/>
        <circle cx="663" cy="731.57" r="69.76"/>
      </svg>
    </div>
    <div className="container cta-inner">
      <p className="eyebrow eyebrow-on-dark">Free to start · No credit card</p>
      <h2 className="cta-title">
        Stop guessing.
        <br/>
        <em className="serif-newsreader">Know your headroom.</em>
      </h2>
      <p className="cta-sub">Connect a bank in two minutes, or try with sample data first. Your real number, every time you open the app.</p>
      <div className="cta-actions">
        <a href="/beta/" className="store-badge store-badge-lg" aria-label="Join the beta — App Store coming soon">
          <img src="../assets/appstore-badge.png" alt="Download on the App Store"/>
        </a>
        <a href="/beta/" className="store-badge store-badge-lg" aria-label="Join the beta — Google Play coming soon">
          <img src="../assets/googleplay-badge.png" alt="Get it on Google Play"/>
        </a>
      </div>
      <p className="cta-meta">Or open <a href="https://my.liway.app" className="cta-link">liway on the web →</a></p>
    </div>
  </section>
);

/* ========================== FOOTER ========================== */
const Footer = () => (
  <footer className="footer">
    <div className="container">
      <div className="footer-grid">
        <div className="footer-brand">
          <div className="footer-lockup">
            <LiwayMark size={28} color="var(--slate-950)"/>
            <Wordmark height={22} color="var(--slate-950)"/>
          </div>
          <p>Cashflow leeway, paycheck to paycheck.</p>
        </div>
        <div>
          <h4>Product</h4>
          <ul>
            <li><a href="/#how">How it works</a></li>
            <li><a href="/#why">Why liway</a></li>
            <li><a href="https://my.liway.app">Web app</a></li>
            <li><a href="/beta/">Beta program</a></li>
          </ul>
        </div>
        <div>
          <h4>Connect</h4>
          <ul>
            <li><a href="mailto:hello@liway.app">Contact</a></li>
          </ul>
        </div>
        <div>
          <h4>Legal</h4>
          <ul>
            <li><a href="/privacy.html">Privacy</a></li>
            <li><a href="/terms.html">Terms</a></li>
          </ul>
        </div>
      </div>
      <div className="footer-bottom">
        <span>© 2026 liway, LLC</span>
        <span className="footer-tag">Made for the days between paydays.</span>
      </div>
    </div>
  </footer>
);

/* ========================== SCROLL PROGRESS BAR ========================== */
// Mirror of the ScrollProgress component on the homepage. Same .scroll-progress
// styles in design/site/styles.css (which this page imports), so no CSS changes.
const ScrollProgress = () => {
  const ref = useRef(null);
  useEffect(() => {
    const update = () => {
      const doc = document.documentElement;
      const max = doc.scrollHeight - doc.clientHeight;
      const pct = max > 0 ? (doc.scrollTop / max) * 100 : 0;
      if (ref.current) ref.current.style.width = pct + "%";
    };
    update();
    window.addEventListener("scroll", update, { passive: true });
    window.addEventListener("resize", update);
    return () => {
      window.removeEventListener("scroll", update);
      window.removeEventListener("resize", update);
    };
  }, []);
  return <div className="scroll-progress" aria-hidden="true"><div ref={ref}/></div>;
};

/* ========================== APP ========================== */
const App = () => (
  <>
    <ScrollProgress />
    <Nav />
    <HlwHero />
    <TermCards />
    <HowWeFigure />
    <Verdicts />
    <WhyMatters />
    <FinalCTA />
    <Footer />
  </>
);

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