/* Loops — Homepage v2 sections A: Seasons, Mechanics, Brain, Built kind, Who sees what */

const V2_SEASONS = [
  { title: "Career and work", body: "The promotion you're working towards, the difficult conversation you've been avoiding, the work that builds your future." },
  { title: "Money", body: "The goal you set, the habits that get you there, the honest conversations with yourself about spending." },
  { title: "Exercise and physical health", body: "The fitness goal, the daily movement, the recovery you need to honour." },
  { title: "Mood and mental health", body: "The patterns you can see across days, the support on the hard ones, the tools that work for your brain." },
  { title: "Relationships", body: "The conversations worth having, the patterns worth changing, the work of being present." },
  { title: "Exams and learning", body: "The qualification you're working towards, the daily revision, the long arc of getting good at something." },
  { title: "Parenting", body: "Especially when you and your child are both wired differently. The work of showing up as the parent you want to be." },
  { title: "The big questions", body: "Meaning, purpose, the things that come up at 2am." },
];

const V2SeasonCard = ({ s, i }) =>
<article className="season-card card-hover flex w-[280px] sm:w-[320px] shrink-0 flex-col gap-4 rounded-card border border-line bg-white p-6 sm:p-7">
    <SeasonGlyph variant={i} />
    <h3 className="text-[18px] font-semibold tracking-tight2 text-ink leading-snug">{s.title}</h3>
    <p className="text-[15px] leading-[1.6] text-ink-2 text-pretty">{s.body}</p>
  </article>;

const V2SeasonTicker = () => {
  const trackRef = React.useRef(null);
  const secondSetRef = React.useRef(null);
  const offset = React.useRef(0);
  const speed = React.useRef(1);
  const target = React.useRef(1);
  const dragging = React.useRef(false);
  const dragStartX = React.useRef(0);
  const dragStartOffset = React.useRef(0);
  const moved = React.useRef(false);
  const [reduced, setReduced] = React.useState(false);
  const [grabbing, setGrabbing] = React.useState(false);

  React.useEffect(() => {
    const mq = window.matchMedia("(prefers-reduced-motion: reduce)");
    const update = () => setReduced(mq.matches);
    update();
    mq.addEventListener("change", update);
    return () => mq.removeEventListener("change", update);
  }, []);

  const wrapValue = (v) => {
    const w = secondSetRef.current ? secondSetRef.current.offsetLeft : 0;
    if (w <= 0) return v;
    return (v % w + w) % w;
  };

  React.useEffect(() => {
    if (reduced) return;
    let raf, last = null;
    const PX_PER_SEC = 34;
    const loop = (t) => {
      if (last == null) last = t;
      const dt = Math.min(0.05, (t - last) / 1000);
      last = t;
      if (!dragging.current) {
        speed.current += (target.current - speed.current) * Math.min(1, dt * 2.4);
        offset.current = wrapValue(offset.current + PX_PER_SEC * speed.current * dt);
      }
      if (trackRef.current) trackRef.current.style.transform = `translate3d(${-offset.current}px,0,0)`;
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, [reduced]);

  const slow = () => { if (!dragging.current) target.current = 0; };
  const resume = () => { if (!dragging.current) target.current = 1; };

  const onPointerDown = (e) => {
    dragging.current = true;
    moved.current = false;
    dragStartX.current = e.clientX;
    dragStartOffset.current = offset.current;
    speed.current = 0;
    target.current = 0;
    setGrabbing(true);
    e.currentTarget.setPointerCapture?.(e.pointerId);
  };
  const onPointerMove = (e) => {
    if (!dragging.current) return;
    const dx = e.clientX - dragStartX.current;
    if (Math.abs(dx) > 3) moved.current = true;
    offset.current = wrapValue(dragStartOffset.current - dx);
  };
  const endDrag = (e) => {
    if (!dragging.current) return;
    dragging.current = false;
    setGrabbing(false);
    const stillHovering = e.currentTarget.matches(":hover");
    target.current = stillHovering ? 0 : 1;
  };

  if (reduced) {
    return (
      <Container>
        <div className="mt-12 lg:mt-16 grid gap-4 sm:gap-5 sm:grid-cols-2 lg:grid-cols-4">
          {V2_SEASONS.map((s, i) => <V2SeasonCard key={s.title} s={s} i={i} />)}
        </div>
      </Container>);
  }

  return (
    <div
      className={`relative mt-12 lg:mt-16 overflow-hidden select-none ${grabbing ? "cursor-grabbing" : "cursor-grab"}`}
      style={{ touchAction: "pan-y" }}
      onMouseEnter={slow}
      onMouseLeave={resume}
      onFocusCapture={slow}
      onBlurCapture={resume}
      onPointerDown={onPointerDown}
      onPointerMove={onPointerMove}
      onPointerUp={endDrag}
      onPointerCancel={endDrag}
      onClickCapture={(e) => { if (moved.current) { e.preventDefault(); e.stopPropagation(); } }}>
      <div aria-hidden="true" className="pointer-events-none absolute inset-y-0 left-0 z-10 w-12 sm:w-24 bg-gradient-to-r from-base to-transparent"></div>
      <div aria-hidden="true" className="pointer-events-none absolute inset-y-0 right-0 z-10 w-12 sm:w-24 bg-gradient-to-l from-base to-transparent"></div>
      <div ref={trackRef} className="flex w-max gap-4 sm:gap-5 px-2 will-change-transform">
        {V2_SEASONS.map((s, i) => <V2SeasonCard key={"a" + i} s={s} i={i} />)}
        {V2_SEASONS.map((s, i) =>
        <div key={"b" + i} ref={i === 0 ? secondSetRef : null} className="flex">
            <V2SeasonCard s={s} i={i} />
          </div>
        )}
      </div>
    </div>);
};

const TravelSectionV2 = () =>
<Section id="how" className="bg-base">
    <Container>
      <SectionHeading
        kicker="How it works"
        title="The mechanics are the same, whatever the goal."
        body="A goal is what you're working towards. A season is how long it takes. Loops are the small, doable actions that get you there, one day at a time." />
      <p className="mt-5 max-w-prose text-[17px] sm:text-[18px] leading-[1.65] text-ink-2 text-pretty">
        When your goals change, your Loops change too. The app stays the same. The actions, the rewards and the coaching adapt around you.
      </p>
    </Container>
    <V2SeasonTicker />
    <Container>
      <p className="mt-14 lg:mt-16 max-w-prose text-[18px] text-ink-2">
        Most apps help with one part. <span className="font-semibold text-ink gloss-sweep" data-text="Loops is built around all five.">Loops is built around all five.</span>
      </p>
      <ol className="mt-8 grid gap-4 sm:gap-5 sm:grid-cols-2">
        {V2_MECHANICS.map((m) => <V2MechanicCard key={m.n} m={m} />)}
      </ol>
    </Container>
  </Section>;

/* ---------------- Mechanics ---------------- */

const V2_MECHANICS = [
  { n: "01", title: "Set a goal that matters", body: "Write it in your own words. Give it a season. Name exactly what done looks like. A goal with a finish line is something your brain can actually see." },
  { n: "02", title: "Do small, doable Loops", body: "A Loop is an action small enough to start, so procrastination never gets a foothold. 30 press-ups a day. 3 runs a week. 2 hours of study. Reading to your daughter every night. Daily, weekly, hours per week, or one-offs. The commitment is the count. When you do it is your business." },
  { n: "03", title: "Be seen by your Buddy", body: "Pick someone who matters. Your partner, your best mate, your mum. They see your progress as you complete Loops, and they can react with a tap. It's body doubling, built in: they don't nag, they don't manage you, they just get to watch you do the thing. That changes everything." },
  { n: "04", title: "Feel the win", body: "Completing week streaks triggers rewards you choose for yourself. The gig tickets. The tattoo. The guilt-free Saturday. Your brain gets to feel the progress, not just the gap." },
  { n: "05", title: "Talk to Dora", gloss: true, cta: { label: "Learn More About Dora", href: "/ai-coach/" }, body: "Dora is an AI coach who gets ADHD. Ask her anything about how your brain works, or let her suggest Loop ideas to move your goal along. She already knows your goal, your Loops and your history, so there's no explaining yourself from the start. And she's there at 11pm, which is when you actually need her." },
];

const V2MechanicCard = ({ m }) =>
<li className="relative">
    <div className="card-hover relative h-full rounded-card border border-line bg-white p-6 sm:p-7">
      <span className="block text-[40px] font-semibold tracking-tight3 text-brand-deep tnum leading-none">{m.n}</span>
      <h3 className="mt-5 text-[18px] font-semibold tracking-tight2 text-ink leading-snug">{m.gloss ? <span className="gloss-sweep" data-text={m.title}>{m.title}</span> : m.title}</h3>
      <p className="mt-2 text-[15px] leading-[1.6] text-ink-2 text-pretty">{m.body}</p>
      {m.cta ? <div className="mt-5"><Button variant="secondary" size="sm" href={m.cta.href}>{m.cta.label}</Button></div> : null}
    </div>
  </li>;

const MechanicsSectionV2 = () =>
<Section id="mechanics" className="bg-soft">
    <Container>
      <SectionHeading
        kicker="How it works"
        title="The mechanics don't change."
        body="Whoever you are and whatever you're working towards, the way people actually make progress is the same." />
      <div className="mt-6 flex flex-wrap gap-2.5">
        {["Set a goal", "Do small Loops", "Be seen", "Feel the win", "Talk to Dora"].map((c) =>
        <span key={c} className="inline-flex items-center rounded-pill bg-brand-soft px-4 py-2 text-[14px] font-semibold text-brand-deep">{c}</span>
        )}
      </div>
      <p className="mt-6 max-w-prose text-[18px] text-ink-2">
        Most apps help with one part. <span className="font-semibold text-ink gloss-sweep" data-text="Loops is built around all five.">Loops is built around all five.</span>
      </p>
      <ol className="mt-12 lg:mt-16 grid gap-4 sm:gap-5 sm:grid-cols-2">
        {V2_MECHANICS.map((m) => <V2MechanicCard key={m.n} m={m} />)}
      </ol>
    </Container>
  </Section>;

/* ---------------- Brain ---------------- */

const BrainSectionV2 = () =>
<Section id="brain" className="bg-base">
    <Container>
      <SectionHeading
        kicker="For ADHD"
        title="Built for the brain that has the hardest time."
        body="ADHD makes it harder to get started, harder to stay consistent, and harder to keep going when things get hard. Procrastination, lost focus, the gap between wanting to do a thing and actually starting it. Any system that genuinely works for ADHD has to be built to a higher standard." />
      <p className="mt-6 max-w-prose text-[18px] leading-[1.55] text-ink-2">
        That same care makes Loops work. <span className="font-bold text-ink gloss-sweep" data-text="For everyone.">For everyone.</span>
      </p>
      <div className="mt-10 rounded-card border border-line bg-white p-6 sm:p-8">
        <div className="mb-4"><Kicker>Loops is used by</Kicker></div>
        <ul className="grid gap-x-6 gap-y-3 sm:grid-cols-2">
          {[
          "Parents helping their child revise for exams",
          "Career changers building towards the next thing",
          "Runners training for their first marathon",
          "Founders fundraising a Series A",
          "Recently bereaved people finding structure again",
          "Students preparing for finals"].
          map((p) =>
          <li key={p} className="flex items-start gap-3 text-[15px] leading-[1.5]">
              <span aria-hidden="true" className="mt-[7px] h-2 w-2 shrink-0 rounded-full bg-brand-deep"></span>
              <span style={{ color: "rgb(97, 86, 120)" }}>{p}</span>
            </li>
          )}
        </ul>
        <p className="mt-6 text-[15px] leading-[1.6] text-ink-2">
          For anyone trying to get good at something hard. The same app. The same coach. Different seasons, different goals, different Loops.
        </p>
      </div>
      <p className="mt-8 max-w-prose text-[17px] sm:text-[18px] leading-[1.6] text-ink-2">
        If it works on the bad days, it works on the good ones. <span className="font-bold text-ink gloss-sweep" data-text="That's the design.">That's the design.</span>
      </p>
    </Container>
  </Section>;

/* ---------------- Built kind ---------------- */

const V2_KIND = [
  { t: "Quiet by default", b: "At most three notifications a day. A morning round-up, an afternoon check-in only if nothing's happening, and a kind word in the evening. When you're on track, we stay silent." },
  { t: "Rest days", b: "Four a month, no questions asked. Your streaks survive." },
  { t: "Away mode", b: "Holidays, illness, life. Everything pauses. Nothing is lost. No guilt when you come back." },
  { t: "No \u201Cstreak broken\u201D", b: "No \u201Cwe miss you\u201D. A missed day is information, not failure." },
];

const BuiltKindV2 = () =>
<Section id="built-kind" className="bg-soft">
    <Container>
      <SectionHeading
        kicker="Built kind"
        title="Most habit apps quietly run on shame. Loops doesn't." />
      <div className="mt-12 grid gap-4 sm:gap-5 sm:grid-cols-2">
        {V2_KIND.map((k) =>
        <article key={k.t} className="rounded-card border border-line bg-white p-6 sm:p-7 shadow-soft">
            <h3 className="text-[18px] font-semibold tracking-tight2 text-ink leading-snug">{k.t}</h3>
            <p className="mt-3 text-[15px] leading-[1.65] text-ink-2 text-pretty">{k.b}</p>
          </article>
        )}
      </div>
    </Container>
  </Section>;

/* ---------------- Who sees what ---------------- */

const WhoSeesWhatV2 = () =>
<Section id="privacy" className="bg-base">
    <Container>
      <div className="max-w-prose">
        <Kicker>Who sees what</Kicker>
        <h2 className="mt-5 text-balance text-ink font-semibold tracking-tight2 text-[28px] sm:text-[34px] lg:text-[40px] leading-[1.12]">
          Your work, not your diary.
        </h2>
        <div className="mt-6 space-y-5 text-[17px] sm:text-[18px] leading-[1.7] text-ink-2 text-pretty">
          <p>Your Buddy sees the work, never the diary. The Loops you've closed and the streaks you've built. That's it.</p>
        </div>
        <div className="mt-6 rounded-card border border-line bg-white p-6 sm:p-7 shadow-soft">
          <p className="text-[17px] sm:text-[18px] leading-[1.7] text-ink-2 text-pretty">Your conversations with Dora are always private. Nothing is sold. There are no advertisers.</p>
        </div>
      </div>
    </Container>
  </Section>;

Object.assign(window, { TravelSectionV2, MechanicsSectionV2, BrainSectionV2, BuiltKindV2, WhoSeesWhatV2 });
