// A day in the life — clean reveal of 11 numbered annotations
//   ≥768px: glucose curve is fully drawn on entry; the 11 numbered notes
//           reveal one-by-one as the user scrolls (left → right).
//   <768px: no scroll-jacking — small static curve thumbnail above a
//           stacked, numbered list of the 11 moments.

function DayInTheLife() {
  const scrollerRef = React.useRef(null);
  const [rDisplay, setRDisplay] = React.useState(0);
  const targetRef = React.useRef(0);
  const rafRef = React.useRef(0);

  // Mobile breakpoint (<768px): use the stacked numbered list instead of
  // the scroll-driven horizontal reveal.
  const [isMobile, setIsMobile] = React.useState(
    () => typeof window !== 'undefined' && window.matchMedia('(max-width: 767px)').matches
  );
  React.useEffect(() => {
    const mq = window.matchMedia('(max-width: 767px)');
    const on = () => setIsMobile(mq.matches);
    on();
    mq.addEventListener ? mq.addEventListener('change', on) : mq.addListener(on);
    return () => { mq.removeEventListener ? mq.removeEventListener('change', on) : mq.removeListener(on); };
  }, []);

  // --- scroll target (0..1) follows the scroller's position in viewport ---
  React.useEffect(() => {
    if (isMobile) return; // mobile is static; no scroll listener
    const el = scrollerRef.current;
    if (!el) return;
    const readTarget = () => {
      const rect = el.getBoundingClientRect();
      const vh = window.innerHeight;
      const scrollable = el.offsetHeight - vh;
      const passed = Math.max(0, -rect.top);
      targetRef.current = scrollable > 0 ? Math.max(0, Math.min(1, passed / scrollable)) : 0;
    };
    readTarget();
    const tick = () => {
      setRDisplay(targetRef.current);
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    window.addEventListener('scroll', readTarget, { passive: true });
    window.addEventListener('resize', readTarget);
    return () => {
      cancelAnimationFrame(rafRef.current);
      window.removeEventListener('scroll', readTarget);
      window.removeEventListener('resize', readTarget);
    };
  }, [isMobile]);

  // ---- helpers ----------------------------------------------------------
  const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
  const phase = (r, a, b) => clamp((r - a) / (b - a), 0, 1);
  const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);

  // ---- SVG dimensions (matches assets/illustrations/hem-day-in-the-life-numbered.svg) ----
  const SVG_W = 1697;
  const SVG_H = 658;

  // The curve path lifted from the cleaned SVG. Rendered as the always-on
  // base layer so the line is fully visible on entry without exposing any
  // of the icons/labels/bubbles that the strip-reveals will bring in.
  const CURVE_D = "M7.5481 321.148C58.0503 312.835 73.1136 296.847 91.0503 290.397C108.987 283.947 124.908 272.357 141.05 269.233C153.871 266.752 166.831 268.195 181.05 267.366C190.4 266.82 200.293 266.589 211.05 266.616C231.78 266.668 255.715 267.679 285.134 269.246C301.775 270.133 340.05 258.82 340.05 258.82L404.548 263.335C404.548 263.335 433.048 258.335 453.548 258.335C474.048 258.335 499.05 272.233 511.548 280.835C541.548 290.497 536.351 277.677 553.548 269.246C559.711 266.225 563.426 258.875 567.275 251.338C570.953 244.136 574.753 236.763 580.927 232.835C586.321 229.403 593.528 228.6 604.048 232.835C609.63 235.082 613.799 237.03 617.05 238.765C627.125 244.141 628.402 247.476 635.672 251.338C639.766 253.512 645.759 255.853 656.29 258.82C690.309 268.404 673.385 277.798 709.313 284.002C717.926 285.49 727.298 287.407 737.05 288.779C745.284 289.937 753.789 290.705 762.335 290.497C777.542 290.127 788.768 264.544 799.031 257.852C806.181 253.19 817.681 248.29 829.05 243.892C840.574 239.435 851.962 235.493 858.548 232.835C865.606 229.987 873.255 228.721 881.05 227.917C889.057 227.092 897.218 226.754 905.05 225.691C917.052 224.063 933.05 215.338 937.002 211.335C939.55 206.838 945.55 194.134 947.465 189.835C947.465 189.835 949.55 184.338 954.849 164.338C954.849 164.338 963.59 140.832 965.05 135.835C966.511 130.838 969.78 113.665 971.108 108.751C972.436 103.838 979.558 79.836 980.524 75.8369C981.489 71.8379 990.163 37.1211 992.05 28.8377C993.402 22.9059 1000.57 17.2692 1004.55 14.8379C1008.53 12.4066 1017.71 5.99547 1021.55 4.8102C1025.39 3.62498 1031.46 3.05632 1034.05 5.33779L1052.05 23.3378L1070.05 98.3378L1076.05 133.835C1076.05 133.835 1077.66 138.227 1083.05 151.338C1087.46 162.073 1095.05 172.838 1095.05 172.838L1103.55 187.838C1103.55 187.838 1113.69 208.945 1117.55 205.338C1120.82 202.286 1125.57 187.428 1130.55 184.338C1130.55 184.338 1139.05 173.111 1143.55 172.838C1148.05 172.565 1151.63 175.178 1166.05 181.587C1173.33 184.823 1181.15 189.737 1189.05 194.134C1196.83 197.462 1204.69 164.258 1212.21 169.338C1218.86 173.825 1223.23 181.533 1229.05 186.335C1234.03 190.452 1242.54 200.448 1249.99 209.338C1255.48 215.892 1261.47 224.475 1267.74 232.691C1275.39 242.708 1283.43 251.667 1291.46 262.852C1301.71 277.143 1302.93 291.803 1312.21 305.338C1318.92 315.112 1321.14 328.3 1326.54 336.338C1338.72 354.45 1359.73 357.725 1359.73 357.725C1359.73 357.725 1368.2 360.963 1380.05 355.841C1386.92 352.873 1394.91 352.449 1403.05 349.035C1409.81 346.199 1416.67 333.37 1423.05 330.815C1434.87 326.087 1475.07 322.299 1480.05 321.148C1488.55 319.183 1487.9 284.379 1500.48 275.338C1512.31 266.833 1507.34 268.002 1516.55 268.002C1521.68 268.002 1535.15 306.709 1552.29 310.497C1562.85 312.83 1574.8 325.574 1587.05 328.348C1600.85 331.474 1615.04 324.639 1628.05 327.3C1654.2 332.65 1675.59 335.965 1679.55 332.835";

  // ---- 11 numbered annotation groups ------------------------------------
  // Each anchor x is the column where the icon/label/bubble for that moment
  // lives in the source SVG. Used to build clip-path strips so each group
  // reveals as one unit (no partial reveals across icon → bubble).
  const NOTES = [
    { n: 1,  title: 'Wake up',            body: 'Morning. Start the day with water.' },
    { n: 2,  title: 'Weigh-in',           body: "That's a great result. You're on track to 55kg in two months at this rate!" },
    { n: 3,  title: 'Breakfast',          body: 'Good to see another home-cooked breakfast. High in protein + low in carbs.' },
    { n: 4,  title: 'Activity low',       body: "Busy day? We're a bit low on steps this morning. How about a post-lunch walk?" },
    { n: 5,  title: 'Lunch',              body: 'Great meal choice!' },
    { n: 6,  title: 'Gym',                body: 'Great session. Your heart rate was above 165 for some time. Take time to wind down now.' },
    { n: 7,  title: 'Dinner',             body: "Chips caused a big spike. Get out for a 20 minute walk soon. Let's keep momentum." },
    { n: 8,  title: '20 min walk',        body: 'Good job. You helped move some glucose to your muscles.' },
    { n: 9,  title: 'Fell asleep',        body: '' },
    { n: 10, title: 'Nighttime glucose',  body: "See this drop? It's a sign that you're not eating enough protein. Learn more." },
    { n: 11, title: 'Woke up for a bit',  body: 'This regular 3am wake-up is probably due to raised cortisol. Try working out earlier and use these stress strategies…' },
  ];

  // Each note has been pre-extracted from the source SVG to its own file
  // (assets/illustrations/ditl-notes/note-NN.svg). Each is a complete SVG
  // with viewBox="0 0 1697 658", so they overlay onto the same coordinate
  // space as the curve. No clipping needed — each layer paints only its
  // own note's icon, label, dotted line and bubble, so adjacent notes can
  // never bleed into each other no matter how their bboxes overlap.
  const strips = NOTES.map((_, i) => i);

  const xPct = (px) => Math.max(0, Math.min(100, (px / SVG_W) * 100));

  // ---- Reveal timeline --------------------------------------------------
  // Curve is shown immediately (the cleaned SVG already has it baked in).
  // Spread the 11 reveals across raw [0.05 → 0.95], slight overlap so the
  // transitions feel continuous rather than ticky.
  const raw = rDisplay;
  // Equal spacing between every note. We divide the [REV_START, REV_END]
  // span into 12 equal gaps for 11 notes, so:
  //   - gap before note 1   = REV_STEP
  //   - gap between notes   = REV_STEP   (same)
  //   - gap after note 11   = REV_STEP   (same)
  // No note fires more quickly than another, no asymmetric lead-in or tail.
  const REV_START = 0.05, REV_END = 0.95;
  const REV_SPAN = REV_END - REV_START;
  const REV_STEP = REV_SPAN / 12;

  const groupProg = strips.map((_, i) => {
    const t = REV_START + (i + 1) * REV_STEP;
    return raw >= t ? 1 : 0;
  });

  return (
    <section id="day-in-the-life" style={{ background: '#fff' }}>
      <style>{`
        .ditl-scrubber { height: 810vh; position: relative; }
        @media (max-width: 767px) {
          .ditl-scrubber { height: auto; }
        }
        .ditl-sticky {
          position: sticky; top: 0; min-height: 100vh;
          display: flex; flex-direction: column; justify-content: center;
          overflow: hidden;
          padding: clamp(56px, 8vw, 96px) clamp(20px, 5vw, 64px);
        }
        @media (max-width: 767px) {
          .ditl-sticky { position: static; min-height: 0; }
        }
        .ditl-head {
          max-width: 1440px; margin: 0 auto; width: 100%;
          padding-bottom: clamp(24px, 3.5vw, 48px);
        }
        .ditl-stage {
          position: relative; width: 100%;
          max-width: 1440px; margin: 0 auto;
          aspect-ratio: 1697 / 658;
        }
        .ditl-svg-base {
          position: absolute; inset: 0; width: 100%; height: 100%;
          display: block;
        }
        .ditl-curve-svg {
          position: absolute; inset: 0; width: 100%; height: 100%;
          pointer-events: none; display: block;
        }
        .ditl-layer {
          position: absolute; inset: 0;
          will-change: opacity, transform;
          transform-origin: center center;
        }
        @keyframes ditl-pop {
          0%   { opacity: 0; transform: scale(0.82); }
          60%  { opacity: 1; transform: scale(1.04); }
          100% { opacity: 1; transform: scale(1); }
        }

        /* Mobile stacked list */
        .ditl-mobile {
          padding: clamp(56px, 10vw, 96px) clamp(20px, 5vw, 32px);
          max-width: 720px; margin: 0 auto;
        }
        .ditl-mobile-thumb {
          width: 100%; height: auto; display: block;
          margin: clamp(16px, 4vw, 24px) 0 clamp(28px, 6vw, 40px);
        }
        .ditl-list {
          display: flex; flex-direction: column;
          gap: clamp(18px, 4vw, 24px);
          margin: 0; padding: 0; list-style: none;
        }
        .ditl-item {
          display: grid;
          grid-template-columns: 36px 1fr;
          gap: 14px;
          align-items: start;
        }
        .ditl-num {
          width: 36px; height: 36px; border-radius: 999px;
          background: var(--teal, #1BBBBB); color: #fff;
          font-weight: 500; font-size: 15px;
          display: flex; align-items: center; justify-content: center;
          flex-shrink: 0;
          font-variant-numeric: tabular-nums;
        }
        .ditl-item-title {
          font-weight: 500; font-size: 17px; color: #000;
          margin: 6px 0 4px;
          line-height: 1.2;
        }
        .ditl-item-body {
          font-size: 15px; line-height: 1.45; color: #333;
          margin: 0;
        }
      `}</style>

      {isMobile ? (
        // ---------- MOBILE: stacked numbered list ----------
        <div className="ditl-mobile">
          <h2 className="t-h2" style={{ margin: 0, color: '#000' }}>
            The energy coach on your arm
          </h2>
          <p className="t-body" style={{ color: '#000', margin: 'clamp(12px, 3vw, 16px) 0 0' }}>
            Eivi tracks the metrics that drive your metabolism — glucose, movement, stress, and sleep — and shows how each hour of your day shapes the next.
          </p>
          <img
            className="ditl-mobile-thumb"
            src="assets/illustrations/hem-day-in-the-life-mobile-line.svg"
            alt="Glucose curve across a day, with eleven numbered moments"
          />
          <ol className="ditl-list">
            {NOTES.map((note) => (
              <li key={note.n} className="ditl-item">
                <span className="ditl-num" aria-hidden="true">{note.n}</span>
                <div>
                  <div className="ditl-item-title">{note.title}</div>
                  {note.body && <p className="ditl-item-body">{note.body}</p>}
                </div>
              </li>
            ))}
          </ol>
        </div>
      ) : (
        // ---------- TABLET / DESKTOP: scroll-driven 11-step reveal ----------
        <div ref={scrollerRef} className="ditl-scrubber">
          <div className="ditl-sticky">
            <div className="ditl-head">
              <h2 className="t-h2" style={{ margin: 0, color: '#000', maxWidth: 820 }}>
                The energy coach on your arm
              </h2>
              <p className="t-body" style={{ color: '#000', margin: 'clamp(16px, 2vw, 20px) 0 0', maxWidth: 720 }}>
                Eivi tracks the metrics that drive your metabolism — glucose, movement, stress, and sleep — and shows how each hour of your day shapes the next.
              </p>
            </div>

            <div className="ditl-stage">
              {/* Base layer: the glucose curve only — fully drawn on entry. */}
              <svg
                className="ditl-curve-svg"
                viewBox={`0 0 ${SVG_W} ${SVG_H}`}
                preserveAspectRatio="xMidYMid meet"
                aria-hidden="true"
              >
                <defs>
                  <linearGradient id="ditl-curve-grad" x1="673.938" y1="13.453" x2="673.938" y2="386.96" gradientUnits="userSpaceOnUse">
                    <stop offset="0.445" stopColor="#F55555" />
                    <stop offset="0.65"  stopColor="#1BBBBB" />
                    <stop offset="1"     stopColor="#188D8F" />
                  </linearGradient>
                </defs>
                <path
                  d={CURVE_D}
                  fill="none"
                  stroke="url(#ditl-curve-grad)"
                  strokeWidth="7.54757"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>

              {/* 11 note layers, each its own pre-extracted SVG. They share
                  the same viewBox as the curve so they overlay perfectly,
                  and there's no shared paint surface between them — adjacent
                  notes can never bleed into each other. */}
              {strips.map((_, i) => {
                const visible = groupProg[i] > 0;
                const isLast = i === strips.length - 1;
                const num = String(i + 1).padStart(2, '0');
                return (
                  <img
                    key={`g-${i}`}
                    src={`assets/illustrations/ditl-notes/note-${num}.svg`}
                    alt={isLast ? 'Day-in-the-life chart showing glucose across a day with eleven labeled events and insights' : ''}
                    aria-hidden={isLast ? undefined : 'true'}
                    className="ditl-layer ditl-svg-base"
                    style={{
                      visibility: visible ? 'visible' : 'hidden',
                      animation: visible ? 'ditl-pop 420ms cubic-bezier(0.34, 1.56, 0.64, 1) both' : 'none',
                    }}
                  />
                );
              })}
            </div>
          </div>
        </div>
      )}
    </section>
  );
}
window.DayInTheLife = DayInTheLife;
