/* global React, Icon, LogoMark, DashboardHero, HeroIllustration, DeviceShowcase, Reveal, ParticleField, TiltCard, CountUp, LiveTicker, AllocatorWidget, KPIStrip, IncomeStreamsChart, PipelineWidget, ScenarioPlanner, TaxLadder */

function Hero({ go }) {
  return (
    <section className="hero">
      <div className="hero-mesh" aria-hidden="true"><div className="hero-mesh-3"/></div>
      <ParticleField/>
      <div className="container-wide hero-inner">
        <div className="hero-copy">
          <span className="tag fade-up">
            <Icon.spark/> For founders, commission earners & independent professionals
          </span>
          <h1 className="h-display fade-up delay-1" style={{marginTop:20}}>
            Most budgets assume a paycheck.{" "}
            <span style={{color:"var(--green-600)"}}>ReservWise assumes you don't.</span>
          </h1>
          <p className="lead fade-up delay-2" style={{marginTop:24}}>
            The budgeting system built for variable income. Treat every deposit as an event,
            auto-fund tax reserves, forecast runway, and know your next move before cash gets tight.
          </p>
          <div className="hero-ctas fade-up delay-3">
            <a className="btn btn-primary btn-lg" href={window.APP_URL + "/register"}>
              Start Building Reserves <Icon.arrow/>
            </a>
            <button className="btn btn-secondary btn-lg" onClick={() => go("product")}>
              See the System
            </button>
          </div>
          <div className="hero-trust fade-up delay-4">
            <div className="trust-item">
              <span className="trust-num"><CountUp to={3.4} decimals={1} suffix="×"/></span>
              <span className="trust-label">avg reserve growth in 90 days</span>
            </div>
            <div className="trust-divider"></div>
            <div className="trust-item">
              <span className="trust-num"><CountUp to={14} suffix="-day"/></span>
              <span className="trust-label">free trial · no card required</span>
            </div>
          </div>
        </div>
        <div className="hero-dash fade-up delay-3">
          <HeroIllustration/>
          <div className="hero-glow"></div>
        </div>
      </div>
    </section>
  );
}

function ProblemSection() {
  const items = [
    { stat: <><CountUp to={73} suffix="%"/></>, label: "of small business owners report income that swings 30%+ month over month" },
    { stat: "$1 in $5", label: "of revenue gets misallocated when budgets assume steady paychecks" },
    { stat: "0", label: "budgeting apps were built for owner draws, tax buckets, and runway in one place" },
  ];
  return (
    <section className="bg-soft">
      <div className="container">
        <div className="section-head">
          <span className="eyebrow"><span className="dot"></span>The problem</span>
          <h2 className="h-section" style={{marginTop:14}}>
            Most budgeting apps assume a paycheck.
            <br/>
            <span className="text-muted">You don't get one.</span>
          </h2>
          <p className="lead" style={{marginTop:18}}>
            Irregular income. Surprise expenses. Quarterly tax pressure. Owner draws.
            Feast and famine. The tools you've tried weren't designed for any of it.
          </p>
        </div>
        <Reveal as="div" stagger className="problem-grid">
          {items.map((it,i) => (
            <TiltCard key={i} className="problem-card">
              <div className="problem-stat">{it.stat}</div>
              <div className="problem-label">{it.label}</div>
            </TiltCard>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

function BreakoutSection() {
  return (
    <section className="bg-charcoal breakout">
      <div className="container breakout-inner">
        <div>
          <span className="eyebrow" style={{color:"var(--green-400)"}}>
            <span className="dot" style={{background:"var(--green-400)", boxShadow:"0 0 0 4px rgba(76,175,99,.18)"}}></span>
            The breakout
          </span>
          <h2 className="h-section" style={{marginTop:14, color:"#fff"}}>
            Break out of paycheck-based budgeting.
          </h2>
          <p style={{marginTop:18, fontSize:18, lineHeight:1.6, color:"#b8bdd1", maxWidth:520}}>
            ReservWise rebuilds the operating system for your money around the
            shape of entrepreneur income — not a salary you don't get.
          </p>
          <div className="breakout-bullets">
            <div className="breakout-bullet">
              <span className="bullet-tick"><Icon.check/></span>
              Reserves first, spending second.
            </div>
            <div className="breakout-bullet">
              <span className="bullet-tick"><Icon.check/></span>
              Forecasts that bend with revenue, not against it.
            </div>
            <div className="breakout-bullet">
              <span className="bullet-tick"><Icon.check/></span>
              Owner draws planned, not improvised.
            </div>
            <div className="breakout-bullet">
              <span className="bullet-tick"><Icon.check/></span>
              Tax pressure absorbed before it lands.
            </div>
          </div>
        </div>
        <div className="breakout-visual">
          <BreakoutBox/>
        </div>
      </div>
    </section>
  );
}

/* The animated arrow-breaking-out-of-the-box concept visual */
function BreakoutBox() {
  return (
    <svg viewBox="0 0 360 360" className="breakout-svg">
      <defs>
        <linearGradient id="boxStroke" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="#5b6294"/>
          <stop offset="100%" stopColor="#2c3358"/>
        </linearGradient>
        <linearGradient id="arrowGrad" x1="0" y1="1" x2="0" y2="0">
          <stop offset="0%" stopColor="#2e9143"/>
          <stop offset="100%" stopColor="#a5d6a7"/>
        </linearGradient>
        <radialGradient id="glowCore" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#4caf63" stopOpacity="0.6"/>
          <stop offset="60%" stopColor="#4caf63" stopOpacity="0.1"/>
          <stop offset="100%" stopColor="#4caf63" stopOpacity="0"/>
        </radialGradient>
      </defs>
      {/* Glow core behind everything */}
      <circle cx="180" cy="60" r="80" fill="url(#glowCore)" className="bo-glow"/>
      {/* Pulsating reverberation rings */}
      <circle className="bo-ring r1" cx="180" cy="200" r="80" stroke="#4caf63" strokeWidth="1.4" fill="none" opacity="0.35"/>
      <circle className="bo-ring r2" cx="180" cy="200" r="80" stroke="#4caf63" strokeWidth="1.4" fill="none" opacity="0.35"/>
      <circle className="bo-ring r3" cx="180" cy="200" r="80" stroke="#4caf63" strokeWidth="1.4" fill="none" opacity="0.35"/>
      <circle className="bo-ring r4" cx="180" cy="200" r="80" stroke="#4caf63" strokeWidth="1.4" fill="none" opacity="0.35"/>
      {/* Concentric depth rings */}
      <circle cx="180" cy="200" r="150" stroke="rgba(255,255,255,0.07)" strokeWidth="1" fill="none"/>
      <circle cx="180" cy="200" r="110" stroke="rgba(255,255,255,0.10)" strokeWidth="1" fill="none"/>
      <circle cx="180" cy="200" r="70" stroke="rgba(255,255,255,0.13)" strokeWidth="1" fill="none"/>

      {/* The box (container) */}
      <g className="box-frame">
        <path d="M90 160 L180 120 L270 160 L270 280 L180 320 L90 280 Z"
              stroke="url(#boxStroke)" strokeWidth="3" fill="rgba(255,255,255,0.02)"
              strokeLinejoin="round"/>
        {/* Reserve fill line — the stable foundation */}
        <path d="M90 160 L180 200 L270 160" stroke="rgba(76,175,99,0.5)" strokeWidth="2" fill="none"/>
        <path d="M180 200 L180 320" stroke="rgba(76,175,99,0.3)" strokeWidth="2" fill="none" strokeDasharray="4 4"/>
        {/* Reserve fill area */}
        <path d="M90 160 L180 200 L270 160 L270 280 L180 320 L90 280 Z" fill="url(#arrowGrad)" opacity="0.10"/>
      </g>

      {/* The arrow breaking out */}
      <g className="break-arrow">
        <path d="M180 200 L180 60 M150 90 L180 60 L210 90"
              stroke="url(#arrowGrad)" strokeWidth="6" strokeLinecap="round" strokeLinejoin="round" fill="none"/>
        {/* Burst fragments */}
        <path d="M120 130 L100 110" stroke="var(--green-400)" strokeWidth="2" strokeLinecap="round" opacity="0.7"/>
        <path d="M240 130 L260 110" stroke="var(--green-400)" strokeWidth="2" strokeLinecap="round" opacity="0.7"/>
        <circle cx="100" cy="100" r="3" fill="var(--green-400)" opacity="0.7"/>
        <circle cx="260" cy="100" r="3" fill="var(--green-400)" opacity="0.7"/>
        <circle cx="180" cy="40" r="4" fill="var(--green-400)"/>
      </g>

      {/* Labels */}
      <text x="180" y="345" textAnchor="middle" fontSize="11" fill="rgba(255,255,255,0.4)"
            fontFamily="var(--font-display)" letterSpacing="0.16em">RIGID PAYCHECK BUDGETING</text>
      <text x="180" y="22" textAnchor="middle" fontSize="11" fill="var(--green-400)"
            fontFamily="var(--font-display)" letterSpacing="0.16em" fontWeight="600">DISCIPLINED GROWTH</text>
    </svg>
  );
}

function SystemSection() {
  const pillars = [
    { icon: Icon.reserve, name: "Variable Income Tracker", desc: "Log each deposit as an event with source, project, and confidence level — confirmed, likely, or speculative." },
    { icon: Icon.forecast, name: "Smart Budget Engine", desc: "Percentage-based budgets across 6 priority tiers. Income arrives → envelopes auto-fill in priority order." },
    { icon: Icon.draw, name: "Cashflow Forecasting", desc: "30/60/90-day projections. Best, expected, and worst case scenarios. Runway calculated to the day." },
    { icon: Icon.tax, name: "Tax Reserve Auto-Fill", desc: "Set 25–30%. Every income event reserves your share. Quarterly estimates, 1099 tracking, deduction log." },
    { icon: Icon.ai, name: "AI Financial Coach", desc: "Weekly summaries, spending pattern analysis, and specific moves before pressure hits the month." },
    { icon: Icon.growth, name: "Invoicing & Plaid Sync", desc: "Send Stripe-powered invoices. Connect bank accounts. Paid invoices auto-log as income events." },
  ];
  return (
    <section>
      <div className="container">
        <div className="section-head center">
          <span className="eyebrow"><span className="dot"></span>The system</span>
          <h2 className="h-section" style={{marginTop:14}}>Six pieces. One operating system for your money.</h2>
          <p className="lead" style={{marginTop:18, marginInline:"auto"}}>
            Each part holds the others. Together they replace the spreadsheet,
            the side-app, and the gut feeling you've been running the business on.
          </p>
        </div>
        <Reveal as="div" stagger className="pillar-grid">
          {pillars.map((p,i) => (
            <TiltCard key={i} className="pillar-card">
              <div className="pillar-icon"><p.icon/></div>
              <div className="pillar-name">{p.name}</div>
              <div className="pillar-desc">{p.desc}</div>
              <div className="pillar-num">0{i+1}</div>
            </TiltCard>
          ))}
        </Reveal>
      </div>
    </section>
  );
}

function DashboardPreviewSection() {
  return (
    <section className="bg-soft dashboard-preview-section">
      <div className="container">
        <div className="section-head center">
          <span className="eyebrow"><span className="dot"></span>Dashboard</span>
          <h2 className="h-section" style={{marginTop:14}}>The whole picture, in one calm view.</h2>
          <p className="lead" style={{marginTop:18, marginInline:"auto"}}>
            Reserve health, runway, owner draw, tax pressure, and the next move
            — all where you can act on them, not just stare at them.
          </p>
        </div>
      </div>
      <div className="container-wide" style={{marginTop:48}}>
        <DashboardHero/>
      </div>
    </section>
  );
}

function InteractiveWidgetsSection() {
  return (
    <section className="widgets-section">
      <div className="container">
        <div className="section-head center">
          <span className="eyebrow"><span className="dot"></span>Interactive · try it</span>
          <h2 className="h-section" style={{marginTop:14}}>
            Numbers that <span className="text-green">respond</span>, not just report.
          </h2>
          <p className="lead" style={{marginTop:18, marginInline:"auto"}}>
            Drag a slider, switch a scenario, hover a bar. This is what running
            ReservWise feels like — every panel a live instrument, not a static report.
          </p>
        </div>

        <Reveal as="div" className="widgets-grid-full" style={{marginTop:48}}>
          <KPIStrip/>
        </Reveal>

        <Reveal as="div" className="widgets-grid">
          <AllocatorWidget/>
          <div style={{display:"flex", flexDirection:"column", gap:24}}>
            <LiveTicker base={23400} jitter={120} label="Reserves · live"/>
            <TaxLadder/>
          </div>
        </Reveal>

        <Reveal as="div" className="widgets-grid-full">
          <IncomeStreamsChart/>
        </Reveal>

        <Reveal as="div" className="widgets-grid">
          <PipelineWidget/>
          <ScenarioPlanner/>
        </Reveal>
      </div>
    </section>
  );
}

function AISection() {
  return (
    <section className="ai-section">
      <div className="container ai-section-inner">
        <div>
          <span className="eyebrow"><span className="dot"></span>AI guidance</span>
          <h2 className="h-section" style={{marginTop:14}}>
            The quiet intelligence layer.
            <br/>Not a chatbot. A coach.
          </h2>
          <p className="lead" style={{marginTop:18}}>
            ReservWise watches the pattern, flags the pressure, and helps you make
            the next disciplined move — long before the month gets tight.
          </p>
          <div className="ai-features">
            <div className="ai-feature">
              <span className="ai-feat-dot"></span>
              <div>
                <div className="ai-feat-h">Pattern recognition</div>
                <div className="ai-feat-d">Learns the rhythm of your invoices, expenses, and seasonal swings.</div>
              </div>
            </div>
            <div className="ai-feature">
              <span className="ai-feat-dot"></span>
              <div>
                <div className="ai-feat-h">Pressure forecasting</div>
                <div className="ai-feat-d">Flags the month where reserves dip below your floor — weeks ahead.</div>
              </div>
            </div>
            <div className="ai-feature">
              <span className="ai-feat-dot"></span>
              <div>
                <div className="ai-feat-h">Disciplined recommendations</div>
                <div className="ai-feat-d">Specific moves: pause this, defer that, set this much aside.</div>
              </div>
            </div>
          </div>
        </div>
        <div className="ai-mock">
          <div className="ai-thread">
            <div className="ai-msg system">
              <div className="ai-msg-head"><Icon.spark style={{color:"var(--green-500)"}}/> ReservWise</div>
              <div className="ai-msg-body">
                Two of your three largest invoices are landing late this cycle.
                Operating reserves dip below your 8-week floor on May 14.
              </div>
            </div>
            <div className="ai-msg system">
              <div className="ai-msg-head"><Icon.spark style={{color:"var(--green-500)"}}/> Recommended move</div>
              <div className="ai-msg-body">
                Pause Q2 marketing increase ($1,800), and defer the new contractor onboarding by 3 weeks. Owner draw stays intact.
              </div>
              <div className="ai-msg-actions">
                <button className="btn btn-primary btn-sm">Apply</button>
                <button className="btn btn-ghost btn-sm">Show reasoning</button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function PricingTeaser({ go }) {
  const tiers = [
    { name: "Free", price: "$0", pitch: "Track income & expenses. 1 bank account, 1 entity.", featured: false },
    { name: "Pro", price: "$12", pitch: "Smart budgets, AI insights, invoicing, 5 accounts.", featured: true },
    { name: "Business", price: "$29", pitch: "Multi-entity, unlimited everything, team & API access.", featured: false },
  ];
  return (
    <section className="bg-soft">
      <div className="container">
        <div className="section-head center">
          <span className="eyebrow"><span className="dot"></span>Pricing</span>
          <h2 className="h-section" style={{marginTop:14}}>Priced like a discipline. Not a database.</h2>
          <p className="lead" style={{marginTop:18, marginInline:"auto"}}>
            Three tiers. No usage games. Cancel any time.
          </p>
        </div>
        <Reveal as="div" stagger className="pricing-grid">
          {tiers.map((t,i) => (
            <TiltCard key={i} className={"pricing-card" + (t.featured ? " featured" : "")} maxTilt={4}>
              {t.featured && <div className="featured-badge">Most chosen</div>}
              <div className="pricing-name">{t.name}</div>
              <div className="pricing-price">
                <span className="pricing-amount">{t.price}</span>
                <span className="pricing-period">/mo</span>
              </div>
              <div className="pricing-pitch">{t.pitch}</div>
              <button
                className={"btn " + (t.featured ? "btn-primary" : "btn-secondary")}
                style={{width:"100%", marginTop:18}}
                onClick={() => go("pricing")}>
                See plan details
              </button>
            </TiltCard>
          ))}
        </Reveal>
        <div style={{textAlign:"center", marginTop:32}}>
          <button className="btn btn-ghost" onClick={() => go("pricing")}>
            Compare all features <Icon.arrow/>
          </button>
        </div>
      </div>
    </section>
  );
}

function FinalCTA({ go }) {
  return (
    <section className="final-cta">
      <div className="container final-cta-inner">
        <h2 className="h-display" style={{fontSize:"clamp(36px,4.5vw,60px)", color:"#ffffff"}}>
          Build stability from <br/>
          <span style={{color:"#7ed492"}}>unpredictable income.</span>
        </h2>
        <p className="lead" style={{color:"#b8bdd1", marginTop:18, marginInline:"auto"}}>
          Start your 14-day trial. No card required. See the system in action with your numbers.
        </p>
        <div className="hero-ctas" style={{justifyContent:"center", marginTop:28}}>
          <a className="btn btn-primary btn-lg" href={window.APP_URL + "/register"}>
            Start Building Reserves <Icon.arrow/>
          </a>
          <button className="btn btn-secondary btn-lg" onClick={() => go("product")}
                  style={{background:"transparent", color:"#fff", borderColor:"rgba(255,255,255,0.18)"}}>
            See How It Works
          </button>
        </div>
        <div style={{marginTop:22, fontSize:14, color:"#9ba1bb"}}>
          Already a customer?{" "}
          <a href={window.APP_URL + "/login"} style={{color:"#7ed492", fontWeight:600}}>Sign in to the app</a>
          {" · "}
          Need help?{" "}
          <a href={window.SUPPORT_URL} style={{color:"#7ed492", fontWeight:600}}>Visit the help center</a>
        </div>
      </div>
    </section>
  );
}

function HomePage({ go }) {
  return (
    <div className="page-fade-in">
      <Hero go={go}/>
      <ProblemSection/>
      <BreakoutSection/>
      <SystemSection/>
      <DashboardPreviewSection/>
      <DeviceShowcase/>
      <InteractiveWidgetsSection/>
      <AISection/>
      <PricingTeaser go={go}/>
      <FinalCTA go={go}/>
    </div>
  );
}

Object.assign(window, { HomePage, Hero, ProblemSection, BreakoutSection, SystemSection, DashboardPreviewSection, InteractiveWidgetsSection, AISection, PricingTeaser, FinalCTA, BreakoutBox });
