// Main app — sections + scroll animations

const { useState, useEffect, useRef } = React;

// Scroll-reveal helper
function useReveal() {
  useEffect(() => {
    const els = document.querySelectorAll('.reveal');
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add('in');
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.18, rootMargin: '0px 0px -80px 0px' }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
}

function useScrollState() {
  const [scrolled, setScrolled] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 30);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return scrolled;
}

// Track section progress (0→1) for parallax / pathway fill
// Section progress applied via CSS var on DOM directly (no React state — avoids re-render storm)
function useSectionProgressDOM(ref, targetSelector = '.pathway-steps') {
  useEffect(() => {
    if (!ref.current) return;
    let raf = 0;
    let last = -1;
    const target = ref.current.querySelector(targetSelector);
    const stepEls = target ? Array.from(target.querySelectorAll('.pathway-step')) : [];
    const total = stepEls.length;
    const compute = () => {
      raf = 0;
      if (!ref.current || !target) return;
      const r = ref.current.getBoundingClientRect();
      const vh = window.innerHeight;
      const start = vh * 0.85;
      const end = vh * 0.2;
      const totalDist = r.height + start - end;
      const passed = start - r.top;
      const prog = Math.round(Math.max(0, Math.min(1, passed / totalDist)) * 100);
      if (prog !== last) {
        last = prog;
        target.style.setProperty('--progress', prog + '%');
        // Mark complete / current
        const current = Math.min(total - 1, Math.floor((prog / 100) * total));
        stepEls.forEach((el, i) => {
          el.classList.toggle('complete', i < current);
          el.classList.toggle('current', i === current);
        });
      }
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(compute); };
    const t = setTimeout(compute, 200);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => { window.removeEventListener('scroll', onScroll); if (raf) cancelAnimationFrame(raf); clearTimeout(t); };
  }, [ref, targetSelector]);
}

// ─────────────────────────  Store buttons (shared, aligned CTAs)  ───────────────────────── //
const StoreButtons = ({ dark = false }) => {
  const stores = window.CONTENT.stores;
  return (
  <div className="store-btns">
    <a href={stores.appStoreUrl} className="app-store-btn" aria-label="Download on the App Store">
      <Icon.apple className="apple" width={26} height={26} aria-hidden="true" />
      <div>
        <div className="label-small">Download on the</div>
        <div className="label-big">App Store</div>
      </div>
    </a>
    <a
      href={stores.googlePlayUrl}
      className={`app-store-btn ${dark ? 'store-btn-dark' : 'store-btn-outline'}`}
      aria-label="Get it on Google Play">
      <Icon.playStore className="apple" width={26} height={26} aria-hidden="true" />
      <div>
        <div className="label-small">Get it on</div>
        <div className="label-big">Google Play</div>
      </div>
    </a>
  </div>);
};

// ─────────────────────────  Nav  ───────────────────────── //
const Nav = () => {
  const scrolled = useScrollState();
  const [open, setOpen] = useState(false);

  useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  return (
    <nav className={`nav ${scrolled ? 'scrolled' : ''}`}>
      <a href="#top" className="nav-brand" onClick={() => setOpen(false)}>
        <InjuredWordmark height={20} />
      </a>
      <div className="nav-links">
        <a href="#orthoagent" onClick={(e) => { e.preventDefault(); document.querySelector('#orthoagent')?.scrollIntoView({ behavior: 'smooth', block: 'start' }); history.pushState(null, '', '#orthoagent'); }}>OrthoAgent</a>
        <a href="#pathway" onClick={(e) => { e.preventDefault(); document.querySelector('#pathway')?.scrollIntoView({ behavior: 'smooth', block: 'start' }); history.pushState(null, '', '#pathway'); }}>Recovery</a>
        <a href="#pricing" onClick={(e) => { e.preventDefault(); document.querySelector('#pricing')?.scrollIntoView({ behavior: 'smooth', block: 'start' }); history.pushState(null, '', '#pricing'); }}>Pricing</a>
        <a href="#download" className="nav-cta" onClick={(e) => { e.preventDefault(); document.querySelector('#download')?.scrollIntoView({ behavior: 'smooth', block: 'start' }); history.pushState(null, '', '#download'); }}>Download</a>
      </div>
      <button
        className="nav-toggle"
        aria-label={open ? 'Close menu' : 'Open menu'}
        aria-expanded={open}
        onClick={() => setOpen((v) => !v)}>
        {open ? <Icon.close width={22} height={22} /> : <Icon.menu width={22} height={22} />}
      </button>
      <div className={`nav-mobile ${open ? 'open' : ''}`} onClick={() => setOpen(false)}>
        <a href="#orthoagent" onClick={(e) => { e.preventDefault(); setOpen(false); document.querySelector('#orthoagent')?.scrollIntoView({ behavior: 'smooth', block: 'start' }); history.pushState(null, '', '#orthoagent'); }}>OrthoAgent</a>
        <a href="#pathway" onClick={(e) => { e.preventDefault(); setOpen(false); document.querySelector('#pathway')?.scrollIntoView({ behavior: 'smooth', block: 'start' }); history.pushState(null, '', '#pathway'); }}>Recovery</a>
        <a href="#pricing" onClick={(e) => { e.preventDefault(); setOpen(false); document.querySelector('#pricing')?.scrollIntoView({ behavior: 'smooth', block: 'start' }); history.pushState(null, '', '#pricing'); }}>Pricing</a>
        <a href="#download" className="nav-cta" onClick={(e) => { e.preventDefault(); setOpen(false); document.querySelector('#download')?.scrollIntoView({ behavior: 'smooth', block: 'start' }); history.pushState(null, '', '#download'); }}>Download the app</a>
      </div>
    </nav>);

};

// ─────────────────────────  Hero  ───────────────────────── //
const Hero = () => {
  // Tilted phone stack — parallax done via direct DOM (no re-render storm)
  const phonesRef = useRef(null);
  useEffect(() => {
    let raf = 0;
    const apply = () => {
      raf = 0;
      const y = Math.min(window.scrollY * 0.12, 80);
      const el = phonesRef.current;
      if (!el) return;
      const left = el.querySelector('.hero-phone-left');
      const right = el.querySelector('.hero-phone-right');
      const front = el.querySelector('.hero-phone-front');
      if (left) left.style.transform = `translate(-58%, calc(-50% + ${-20 + y * 0.4}px)) rotate(-10deg) scale(0.78)`;
      if (right) right.style.transform = `translate(58%, calc(-50% + ${20 + y * 0.6}px)) rotate(10deg) scale(0.78)`;
      if (front) front.style.transform = `translate(-50%, calc(-50% + ${-y * 0.2}px))`;
    };
    const onScroll = () => { if (!raf) raf = requestAnimationFrame(apply); };
    apply();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => { window.removeEventListener('scroll', onScroll); if (raf) cancelAnimationFrame(raf); };
  }, []);

  const hero = window.CONTENT.hero;
  return (
    <section className="hero" id="top">
      <div className="hero-grid">
        <div>
          <div className="hero-eyebrow reveal">
            <span className="dot" />
            {hero.eyebrow}
          </div>
          <h1 className="reveal reveal-delay-1">
            {hero.title1}<br />
            {hero.title2}<br />
            <span className="accent">{hero.titleAccent}</span>
          </h1>
          <p className="hero-sub reveal reveal-delay-2">
            {hero.subhead}
          </p>
          <div className="hero-ctas reveal reveal-delay-3">
            <StoreButtons />
          </div>
          <a href="#orthoagent" className="hero-howlink reveal reveal-delay-3">
            {hero.howLink}
          </a>
          <div className="hero-stats reveal reveal-delay-3">
            {hero.stats.map((s, i) =>
              <div className="hero-stat" key={i}>
                <div className="num">{s.num}{s.small && <span className="small">{s.small}</span>}</div>
                <div className="label">{s.label}</div>
              </div>
            )}
          </div>
          <p className="hero-disclaimer reveal reveal-delay-3">
            {hero.disclaimer}
          </p>
        </div>
        <div className="hero-video-embed">
          <div className="hero-phone-video-wrap">
            <iframe
              src="https://player.vimeo.com/video/1204669245?h=619448e53a&badge=0&autopause=0&player_id=0&app_id=58479&autoplay=1&muted=1&loop=1&background=1"
              allow="autoplay; fullscreen; picture-in-picture; clipboard-write; encrypted-media"
              style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }}
              title="INJURED App"
            />
          </div>
        </div>
      </div>
    </section>);

};

// ─────────────────────────  Trust strip  ───────────────────────── //
const Stars = () =>
  <span className="stars" aria-hidden="true">
    {[0, 1, 2, 3, 4].map((i) => <Icon.star key={i} width={16} height={16} />)}
  </span>;


// ─────────────────────────  Hero Video  ───────────────────────── //
const SectionHeroVideo = () =>
  <section className="section-hero-video">
    <div className="hero-video-shell reveal">
      <div className="hero-video-wrap">
        <iframe
          src="https://player.vimeo.com/video/1204669245?h=619448e53a&badge=0&autopause=0&player_id=0&app_id=58479"
          allow="autoplay; fullscreen; picture-in-picture; clipboard-write; encrypted-media"
          style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }}
          title="INJURED — See how it works"
        />
      </div>
    </div>
  </section>;

const SectionTrust = () => {
  const trust = window.CONTENT.trust;
  return (
  <section className="section-trust" aria-label="Ratings and partners">
    <div className="trust-shell">
      <div className="trust-proof">
        <div className="trust-rating">
          <Stars />
          <div className="trust-rating-text">
            <strong>{trust.rating}</strong> on the App Store
            <span>{trust.ratingSub}</span>
          </div>
        </div>
        <div className="trust-div" />
        <div className="trust-rating">
          <div className="trust-rating-text">
            <strong>{trust.athletes}</strong> athletes recovering
            <span>{trust.athletesSub}</span>
          </div>
        </div>
      </div>
      <div className="trust-logos">
        <span className="trust-logos-label">{trust.partnersLabel}</span>
        <div className="trust-logos-row">
          {(trust.partnerLogos || []).map((src, i) =>
            <image-slot
              key={i}
              id={`partner-p${i + 1}`}
              shape="rounded"
              radius="8"
              fit="contain"
              placeholder="Logo"
              {...(src ? { src } : {})}
              style={{ width: '120px', height: '44px', opacity: 0.9 }}>
            </image-slot>
          )}
        </div>
      </div>
    </div>
  </section>);
};

// ─────────────────────────  OrthoAgent  ───────────────────────── //
const SectionOrthoAgent = () => {
  return (
    <section id="orthoagent" className="section-padded section-orthoagent">
      <div className="feature-grid">
        <div>
          <div className="eyebrow reveal">OrthoAgent · AI Assistant</div>
          <h2 className="section-title reveal reveal-delay-1">
            An ortho specialist<br />in your pocket.
          </h2>
          <p className="section-sub reveal reveal-delay-2">
            Ask anything — surgical prep, what to expect after PT, why your knee clicks. OrthoAgent reads your MRI, knows your plan, and sources every answer from your care team.
          </p>
          <div className="feature-bullets">
            <Bullet
              title="Plain-English MRI breakdowns"
              body="Drop in your imaging — see your injury explained without the jargon."
              icon={<Icon.bolt width={14} height={14} />} />
            
            <Bullet
              title="Voice, photo, or text input"
              body="Whisper a question mid-PT. Snap a photo of your brace. We've got you."
              icon={<Icon.mic width={14} height={14} />} />
            
            <Bullet
              title="Verified, never hallucinated"
              body="Every answer cites your surgeon, your PT, or peer-reviewed clinical literature."
              icon={<Icon.shield width={14} height={14} />} />
            
          </div>
          <div className="security-row reveal">
            <Icon.lock width={15} height={15} aria-hidden="true" />
            <span><strong>HIPAA-compliant.</strong> End-to-end encrypted. Your health data is never sold.</span>
          </div>
        </div>
        <div style={{ display: "flex", justifyContent: "center", alignItems: "center" }} className="reveal reveal-delay-2">
          <div style={{ transform: "scale(1)" }}>
            <ScreenOrthoAgent />
          </div>
        </div>
      </div>
    </section>);

};

const Bullet = ({ title, body, icon }) =>
<div className="feature-bullet reveal">
    <div className="check">{icon}</div>
    <div>
      <h4>{title}</h4>
      <p>{body}</p>
    </div>
  </div>;


// ─────────────────────────  Pathway  ───────────────────────── //
const SectionPathway = () => {
  const sectionRef = useRef(null);
  useSectionProgressDOM(sectionRef);

  const steps = [
  { label: "Report your injury", time: "Day 1", body: "Tell us what hurts. OrthoAgent walks you through intake — pain level, mobility, mechanism." },
  { label: "MRI & diagnosis", time: "Week 1", body: "Get your scans broken down in plain English with a personalized timeline." },
  { label: "Match with a surgeon", time: "Week 1–2", body: "Auto-matched with certified specialists in your network. You stay in control." },
  { label: "Procedure & PT", time: "Month 1–6", body: "Recovery roadmap updates in real time. Every milestone, every appointment, in one place." },
  { label: "Cleared to return", time: "Comeback", body: "Closing recap. Shareable card. Archive your injury, get back to what you love." }];


  return (
    <section id="pathway" ref={sectionRef} className="section-padded section-pathway">
      <div className="pathway-shell">
        <div className="pathway-header">
          <div className="eyebrow reveal">The INJURED Pathway</div>
          <h2 className="section-title reveal reveal-delay-1">
            One app.<br />
            From day one to comeback.
          </h2>
          <p className="section-sub reveal reveal-delay-2">
            No more being handed off between specialists, paper records, and waiting rooms. The INJURED pathway gives you a single, living plan from intake to clearance.
          </p>
        </div>
        <div className="pathway-flow">
          <div className="pathway-steps reveal">
            {steps.map((s, i) =>
            <div
              key={i}
              className="pathway-step"
              data-step={i}>
              
                <div className="node">
                  <Icon.check width={14} height={14} />
                </div>
                <h4>
                  {s.label}
                  <span className="time-pill">{s.time}</span>
                </h4>
                <p>{s.body}</p>
              </div>
            )}
          </div>
          <div className="pathway-phones reveal reveal-delay-2">
            <div className="pathway-phone-back">
              <ScreenHome />
            </div>
            <div className="pathway-phone-front">
              <ScreenRoadmap />
            </div>
          </div>
        </div>
      </div>
    </section>);

};

// ─────────────────────────  Testimonials  ───────────────────────── //
const SectionTestimonials = () =>
  <section className="section-padded section-testimonials">
    <div className="testimonials-shell">
      <div className="pricing-header">
        <div className="eyebrow reveal">Comeback stories</div>
        <h2 className="section-title reveal reveal-delay-1">
          Recoveries that<br />stayed on track.
        </h2>
      </div>
      <div className="testimonials-grid testimonials-video-grid">
        {[
          { id: '1189847721', h: '71906d4f67', name: 'Noah Kjar', role: 'Weber State WR' },
          { id: '1063340166', h: '7469536bc2', name: 'Britain Covey', role: 'NFL Wide Receiver' },
          { id: '912692853',  h: '821e61697d', name: 'London Packer', role: 'Athlete' },
          { id: '1092233091', h: '4c88cbf033', name: 'Aiden Parish', role: 'Freeride MTB Pro' }
        ].map((v, i) =>
          <figure className="testimonial-card testimonial-video-card reveal" key={i}>
            <div className="testimonial-video-wrap">
              <iframe
                src={`https://player.vimeo.com/video/${v.id}?h=${v.h}&badge=0&autopause=0&player_id=0&app_id=58479`}
                allow="autoplay; fullscreen; picture-in-picture; clipboard-write; encrypted-media"
                style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }}
                title={v.name}
              />
            </div>
            <figcaption>
              <div className="testimonial-name">{v.name}</div>
              <div className="testimonial-role">{v.role}</div>
            </figcaption>
          </figure>
        )}
      </div>
    </div>
  </section>;
// ─────────────────────────  Pricing  ───────────────────────── //
const SectionPricing = () => {
  const [billing, setBilling] = useState('monthly');
  return (
    <section id="pricing" className="section-padded section-pricing">
      <div className="pricing-shell">
        <div className="pricing-header">
          <div className="eyebrow reveal">Membership</div>
          <h2 className="section-title reveal reveal-delay-1">
            One plan to get back<br />in the game.
          </h2>
          <p className="section-sub reveal reveal-delay-2">
            Start free. Upgrade when you're ready to access full care.
          </p>
          <div className="billing-toggle reveal reveal-delay-2" role="group" aria-label="Billing period">
            <button
              className={billing === 'monthly' ? 'active' : ''}
              aria-pressed={billing === 'monthly'}
              onClick={() => setBilling('monthly')}>
              Monthly
            </button>
            <button
              className={billing === 'onetime' ? 'active' : ''}
              aria-pressed={billing === 'onetime'}
              onClick={() => setBilling('onetime')}>
              One-time <span className="save-pill">best value</span>
            </button>
          </div>
        </div>
        <div className="pricing-grid">
          <PriceCard
            tier="Essentials"
            blurb="Get back into reading your body."
            price="Free"
            bill="Forever"
            features={[
            "Injury location & pain logging",
            "Limited OrthoAgent access (5/wk)",
            "Educational injury library",
            "Recovery roadmap (read-only)"]
            }
            cta="Get Started" />
          
          <PriceCard
            tier="INJURED Pro+"
            blurb="Everything you need to recover."
            price={billing === 'monthly' ? '$2.99' : '$99.99'}
            per={billing === 'monthly' ? '/mo' : ' once'}
            bill={billing === 'monthly' ? 'Billed monthly · cancel anytime' : 'One-time payment · lifetime access'}
            popular
            features={[
            "Unlimited OrthoAgent",
            "Personalized support from Surgeons & PTs",
            "Immediate access to expert Surgeons",
            "Discounted PT sessions",
            "Full educational video library",
            "Discount on bio-health products"]
            }
            cta="Start Recovery" />
          
          <PriceCard
            tier="Teams & Clinics"
            blurb="For trainers, PTs, and athletic programs."
            price="Custom"
            bill="Volume pricing"
            features={[
            "Athlete dashboards & cohorts",
            "Direct messaging with team",
            "Clinical case workflow",
            "Single sign-on & HIPAA"]
            }
            cta="Talk to Sales" />
          
        </div>
      </div>
    </section>);

};

const PriceCard = ({ tier, blurb, price, per, bill, badge, features, cta, popular }) =>
<div className={`price-card ${popular ? 'popular' : ''} reveal`}>
    {popular && <div className="price-tag-pop">Most Popular</div>}
    <div className="tier-name">{tier}</div>
    <div className="tier-blurb">{blurb}</div>
    <div className="tier-price">
      {price}{per && <span className="per">{per}</span>}
    </div>
    <div className="tier-bill">
      {bill}
      {badge && <span className="badge">{badge} one-time</span>}
    </div>
    <ul className="tier-features">
      {features.map((f, i) =>
    <li key={i}>
          <Icon.checkCircle />
          <span>{f}</span>
        </li>
    )}
    </ul>
    <a href={cta === 'Talk to Sales' ? 'mailto:help@injuredapp.com' : '#download'} className="price-cta">{cta}</a>
  </div>;


// ─────────────────────────  CTA + Footer  ───────────────────────── //
const TextMeLink = () => {
  const [val, setVal] = useState('');
  const [sent, setSent] = useState(false);
  const submit = (e) => {
    e.preventDefault();
    if (!val.trim()) return;
    setSent(true);
  };
  return (
    <form className="textme" onSubmit={submit} aria-label="Send me a download link">
      {sent ?
        <div className="textme-done">
          <Icon.checkCircle width={18} height={18} aria-hidden="true" />
          Link on its way — check your messages.
        </div> :
        <>
          <div className="textme-field">
            <Icon.message width={16} height={16} aria-hidden="true" />
            <input
              type="text"
              inputMode="email"
              value={val}
              onChange={(e) => setVal(e.target.value)}
              placeholder="Email or phone number"
              aria-label="Email or phone number" />
          </div>
          <button type="submit" className="textme-btn">Text me the link</button>
        </>}
    </form>);
};

const SectionCTA = () =>
<section id="download" className="section-cta">
    <div className="cta-phone reveal">
      <ScreenCongrats />
    </div>
    <h2 className="reveal">
      {window.CONTENT.cta.title} <span className="accent">{window.CONTENT.cta.titleAccent}</span>
    </h2>
    <p className="reveal reveal-delay-1">
      {window.CONTENT.cta.subhead}
    </p>
    <div className="cta-stores reveal reveal-delay-2">
      <StoreButtons dark />
    </div>
    <div className="cta-or reveal reveal-delay-2">or have a link sent to your phone</div>
    <div className="reveal reveal-delay-2">
      <TextMeLink />
    </div>
  </section>;


const Footer = () =>
<footer>
    <div className="row">
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <InjuredWordmark height={14} />
        <span>© 2026 INJURED, Inc.</span>
      </div>
      <div className="footer-links">
        <a href="#">Privacy</a>
        <a href="#">Terms</a>
        <a href="#">HIPAA</a>
        <a href="#">Medical Disclaimer</a>
        <a href="#">Security</a>
        <a href="#">Contact</a>
      </div>
    </div>
  </footer>;


// ─────────────────────────  Root  ───────────────────────── //
function App() {
  useReveal();
  return (
    <>
      <Nav />
      <Hero />
      <SectionHeroVideo />
      <SectionTrust />
      <SectionOrthoAgent />
      <SectionPathway />
      <SectionTestimonials />
      <SectionPricing />
      <SectionCTA />
      <Footer />
    </>);

}

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

// Re-render when content.js loads overrides from Supabase. Components read
// window.CONTENT at render time, so a plain re-render picks up the new values.
if (typeof window.onContentUpdate === 'function') {
  window.onContentUpdate(() => __root.render(<App />));
}
