/* CareNav site — Connecting the dots animation (signature moment) + Patient Promise */

/* Signature animation — scattered dots representing fragments of care
   converge into a single connected path as the user scrolls into view. */
window.SiteConnectDots = function SiteConnectDots() {
  const isMobile = useIsMobile();
  const sectionRef = React.useRef(null);
  const ref = React.useRef(null);
  const pathRef = React.useRef(null);
  // Trigger when section enters view, replay each time it re-enters
  const [playKey, setPlayKey] = React.useState(0);
  const [inView, setInView] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    let isInView = false;
    const obs = new IntersectionObserver(([e]) => {
      if (e.isIntersecting && !isInView) {
        isInView = true;
        setInView(true);
        setPlayKey(k => k + 1);
      } else if (!e.isIntersecting && isInView) {
        isInView = false;
        setInView(false);
      }
    }, { threshold: 0.35 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  // Path = the CareNav logo's "Cn" monogram, in viewBox 0..100 × 0..100.
  // The C: starts at top-right, sweeps up-left, down to waist, back to bottom.
  // The n: rises from bottom of C, hump up, then drops vertically.
  const pathD = [
    'M 72 18',
    'C 60 11, 43 12, 32 24',
    'C 18 38, 17 60, 32 73',
    'C 44 85, 65 82, 74 68',
    'C 80 58, 80 45, 91 38',
    'C 104 30, 121 38, 121 58',
    'L 121 78',
  ].join(' ');

  // Sample 11 evenly-spaced points ALONG the actual rendered path so dots
  // sit exactly on the curve, not on guessed coordinates.
  const labels = [
    { label: 'Screening',      side: 'top'    },
    { label: 'Pathology',      side: 'top'    },
    { label: 'Diagnosis',      side: 'left'   },
    { label: 'Insurance',      side: 'left'   },
    { label: 'Specialists',    side: 'left'   },
    { label: 'Treatment plan', side: 'bottom' },
    { label: 'Chemotherapy',   side: 'bottom' },
    { label: 'Surgery',        side: 'right'  },
    { label: 'Pharmacy',       side: 'top'    },
    { label: 'Follow-up',      side: 'right'  },
    { label: 'Survivorship',   side: 'right'  },
  ];
  const [dots, setDots] = React.useState([]);
  const [pathLen, setPathLen] = React.useState(1000);
  React.useLayoutEffect(() => {
    const path = pathRef.current;
    if (!path) return;
    const len = path.getTotalLength();
    setPathLen(len);
    const sampled = labels.map((l, i) => {
      const t = i / (labels.length - 1);
      const pt = path.getPointAtLength(t * len);
      return { ...l, x: pt.x, y: pt.y, t };
    });
    setDots(sampled);
  }, []);

  // Time-based progress 0..1 driven by rAF after inView=true; resets on each replay
  const [p, setP] = React.useState(0);
  React.useEffect(() => {
    if (!inView) { setP(0); return; }
    setP(0);
    const DURATION = 5200;
    const start = performance.now() + 250;
    let raf;
    const tick = (t) => {
      const raw = Math.max(0, Math.min(1, (t - start) / DURATION));
      const eased = raw < 0.5 ? 2 * raw * raw : 1 - Math.pow(-2 * raw + 2, 2) / 2;
      setP(eased);
      if (raw < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [inView, playKey]);

  // Reserve a small head and tail of the timeline for hold/logo, line draws between
  const drawProgress = Math.max(0, Math.min(1, (p - 0.04) / 0.82));
  const allConnected = p > 0.96;
  // Color blends from coral → green over the last 20% of the draw.
  // We do this by drawing TWO paths: coral always at full draw, green fades in on top.
  const greenFade = Math.max(0, Math.min(1, (drawProgress - 0.82) / 0.18));

  return (
    <section id="how-it-works" ref={ref} style={{ background: 'var(--cn-cream-100)', padding: isMobile ? '64px 20px' : '140px 32px', position: 'relative' }}>
      <div style={{ maxWidth: 1280, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1.4fr', gap: isMobile ? 36 : 64, alignItems: 'center' }}>
          <div>
            <div style={{ fontFamily: 'var(--cn-font-mono)', fontSize: isMobile ? 10 : 11, letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--cn-coral-700)', fontWeight: 600 }}>How it works</div>
            <h2 style={{ fontFamily: 'var(--cn-font-display)', fontSize: isMobile ? 'clamp(34px, 9vw, 48px)' : 'clamp(44px, 5.5vw, 80px)', fontWeight: 400, letterSpacing: '-0.025em', color: 'var(--cn-forest-900)', margin: '14px 0 20px', lineHeight: 0.98, textWrap: 'balance' }}>
              We connect the <span style={{ fontStyle: 'italic', color: 'var(--cn-coral-700)' }}>dots</span>, so you don't have to.
            </h2>
            <p style={{ fontFamily: 'var(--cn-font-sans)', fontSize: isMobile ? 15 : 18, lineHeight: 1.6, color: 'var(--cn-ink-700)', textWrap: 'pretty' }}>
              A real human navigator — supported by smart software — stitches together every part of your journey. One plan. One record. One number to call.
            </p>
            <div style={{ marginTop: isMobile ? 24 : 32, display: 'grid', gap: 14 }}>
              {[
                ['One human', 'Your dedicated CareNav navigator — clinically trained.'],
                ['One plan', 'Appointments, referrals, follow-ups, all in one place.'],
                ['One record', 'Records, results, and notes, gathered for you.'],
              ].map(([t, d]) => (
                <div key={t} style={{ display: 'grid', gridTemplateColumns: '8px 1fr', gap: 16, alignItems: 'baseline' }}>
                  <div style={{ width: 8, height: 8, borderRadius: 4, background: 'var(--cn-coral-600)', marginTop: 6 }}/>
                  <div>
                    <div style={{ fontFamily: 'var(--cn-font-display)', fontSize: isMobile ? 18 : 20, fontWeight: 500, color: 'var(--cn-forest-900)' }}>{t}</div>
                    <div style={{ fontFamily: 'var(--cn-font-sans)', fontSize: 14, color: 'var(--cn-ink-700)', marginTop: 2 }}>{d}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
          {/* Diagram — viewBox sized to fit the Cn (130 wide × 100 tall + label margin) */}
          <div style={{ position: 'relative', aspectRatio: '4/3', background: 'white', borderRadius: 24, border: '1px solid var(--cn-ink-100)', overflow: 'hidden', boxShadow: '0 30px 80px rgba(11,63,50,0.08)' }}>
            {/* Inner positioning context so labels at the edge of the curve have horizontal breathing room on mobile */}
            <div style={{ position: 'absolute', top: isMobile ? '12%' : 0, bottom: isMobile ? '14%' : 0, left: isMobile ? 70 : 0, right: isMobile ? 76 : 0 }}>
            <svg viewBox="0 0 130 100" preserveAspectRatio="xMidYMid meet" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
              {/* Hidden measurement path — must be in the DOM so getTotalLength works */}
              <path ref={pathRef} d={pathD} fill="none" stroke="none"/>
              {/* Faint guide so users sense where the line is going */}
              <path d={pathD} fill="none" stroke="var(--cn-ink-200)" strokeWidth="0.6" strokeLinecap="round" strokeDasharray="0.4 1.2" opacity="0.55"/>
              {/* Coral pen line — draws first */}
              <path
                d={pathD}
                pathLength="1000"
                fill="none"
                stroke="var(--cn-coral-500)"
                strokeWidth="2.4"
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeDasharray="1000 1000"
                strokeDashoffset={1000 * (1 - drawProgress)}
                style={{ transition: 'stroke-dashoffset 80ms linear', opacity: 1 - greenFade * 0.95 }}
              />
              {/* Green overlay — fades in over the same path as the line nears completion */}
              <path
                d={pathD}
                pathLength="1000"
                fill="none"
                stroke="var(--cn-forest-700)"
                strokeWidth="2.4"
                strokeLinecap="round"
                strokeLinejoin="round"
                strokeDasharray="1000 1000"
                strokeDashoffset={1000 * (1 - drawProgress)}
                style={{ transition: 'stroke-dashoffset 80ms linear, opacity 600ms ease-out', opacity: greenFade }}
              />
            </svg>
            {/* Dots — sampled along the actual rendered path so they sit exactly on the line */}
            {dots.map((d, i) => {
              const dotAt = d.t;
              // The pen "passes through" the dot when drawProgress reaches dotAt.
              const reached = drawProgress >= dotAt - 0.001;
              // SVG viewBox is 130×100, rendered with xMidYMid meet inside a 4:3 box.
              // Box ratio 4:3 = 1.333; svg ratio 130:100 = 1.3 → svg fits width-wise (almost),
              // actually 1.3 < 1.333 so it fits height-wise. Compute padding precisely.
              // For a div of width W, height H = 0.75W. SVG drawn at scale s = min(W/130, H/100).
              // s = min(W/130, 0.75W/100) = min(W/130, W/133.33) = W/133.33 (height-bound).
              // Drawn width = 130 * W/133.33 = 0.975W; horizontal pad = 0.0125W on each side.
              // Drawn height = 100 * W/133.33 = 0.75W = H; vertical pad = 0.
              const xPct = 1.25 + (d.x / 130) * 97.5;
              const yPct = (d.y / 100) * 100;
              const offset = 14;
              const labelStyle = ({
                top:    { bottom: offset, left: '50%', transform: 'translateX(-50%)' },
                bottom: { top: offset,    left: '50%', transform: 'translateX(-50%)' },
                left:   { right: offset,  top: '50%',  transform: 'translateY(-50%)' },
                right:  { left: offset,   top: '50%',  transform: 'translateY(-50%)' },
              })[d.side];
              const lineColor = greenFade > 0.5 ? 'var(--cn-forest-700)' : 'var(--cn-coral-500)';
              return (
                <div key={i} style={{
                  position: 'absolute',
                  left: `${xPct}%`, top: `${yPct}%`,
                  transform: 'translate(-50%, -50%)',
                }}>
                  <div style={{
                    width: 14, height: 14, borderRadius: 7,
                    background: reached ? lineColor : 'white',
                    border: reached ? '3px solid white' : '2px solid var(--cn-ink-300)',
                    boxShadow: reached ? `0 0 0 5px ${greenFade > 0.5 ? 'rgba(31,108,90,0.18)' : 'rgba(200,97,71,0.18)'}` : '0 1px 3px rgba(0,0,0,0.08)',
                    transition: 'background 280ms ease-out, box-shadow 320ms ease-out, border-color 240ms',
                  }}/>
                  <div style={{
                    position: 'absolute',
                    ...labelStyle,
                    fontFamily: 'var(--cn-font-mono)', fontSize: 9, letterSpacing: '0.08em', textTransform: 'uppercase',
                    color: reached ? 'var(--cn-forest-800)' : 'var(--cn-ink-400)',
                    fontWeight: 600, whiteSpace: 'nowrap', transition: 'color 240ms',
                  }}>{d.label}</div>
                </div>
              );
            })}
            </div>
            {/* Footer text — appears in green across the bottom of the card once connected */}
            <div style={{
              position: 'absolute', left: 0, right: 0, bottom: 22,
              textAlign: 'center',
              opacity: allConnected ? 1 : 0,
              transform: allConnected ? 'translateY(0)' : 'translateY(8px)',
              transition: 'opacity 700ms ease-out 200ms, transform 700ms ease-out 200ms',
              pointerEvents: 'none',
            }}>
              <span style={{ fontFamily: 'var(--cn-font-display)', fontSize: isMobile ? 18 : 22, fontStyle: 'italic', color: 'var(--cn-forest-700)', letterSpacing: '-0.01em' }}>
                connected by CareNav
              </span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

window.SitePromise = function SitePromise() {
  const isMobile = useIsMobile();
  const [ref, inView] = useInView({ threshold: 0.4, once: true });
  const lines = ['Every step.', 'Every decision.', 'The knowns and the unknowns.'];
  return (
    <section ref={ref} style={{ background: 'var(--cn-forest-900)', color: 'var(--cn-cream-100)', padding: isMobile ? '80px 20px' : '160px 32px', position: 'relative', overflow: 'hidden' }}>
      <div style={{ position: 'absolute', left: -120, top: -80, opacity: 0.05 }}><CNLogoMark size={isMobile ? 320 : 620} color="var(--cn-cream-100)"/></div>
      <div style={{ position: 'absolute', right: -160, bottom: -160, opacity: 0.04 }}><CNLogoMark size={isMobile ? 380 : 760} color="var(--cn-coral-300)"/></div>
      <div style={{ position: 'relative', maxWidth: 1180, margin: '0 auto' }}>
        <div style={{ fontFamily: 'var(--cn-font-mono)', fontSize: isMobile ? 12 : 18, letterSpacing: '0.24em', textTransform: 'uppercase', color: 'var(--cn-coral-300)', fontWeight: 700 }}>Our Patient Promise</div>
        <div style={{ width: 56, height: 1, background: 'var(--cn-coral-400)', marginTop: isMobile ? 20 : 32 }}/>
        <div style={{ marginTop: isMobile ? 32 : 56, fontFamily: 'var(--cn-font-display)', fontWeight: 400, letterSpacing: '-0.025em', lineHeight: 1.05, fontSize: isMobile ? 'clamp(36px, 11vw, 56px)' : 'clamp(48px, 8vw, 112px)' }}>
          {lines.map((l, i) => (
            <div key={i} style={{
              opacity: inView ? 1 : 0,
              transform: inView ? 'translateY(0)' : 'translateY(20px)',
              transition: `all 900ms cubic-bezier(0.2, 0.8, 0.2, 1) ${i * 350}ms`,
              fontStyle: i === 2 ? 'italic' : 'normal',
              color: i === 2 ? 'var(--cn-coral-300)' : 'var(--cn-cream-100)',
            }}>{l}</div>
          ))}
        </div>
        <div style={{
          marginTop: isMobile ? 36 : 64, paddingTop: isMobile ? 28 : 56, borderTop: '1px solid rgba(243,234,218,0.18)',
          fontFamily: 'var(--cn-font-display)', fontSize: isMobile ? 'clamp(28px, 7.5vw, 40px)' : 'clamp(40px, 5vw, 72px)', fontWeight: 400, color: 'var(--cn-cream-100)',
          lineHeight: 1.15, letterSpacing: '-0.02em', maxWidth: 1100, textWrap: 'balance',
          opacity: inView ? 1 : 0, transition: 'opacity 1000ms 1500ms',
        }}>
          We'll be here — to <span style={{ fontStyle: 'italic', color: 'var(--cn-coral-300)' }}>guide</span>, to <span style={{ fontStyle: 'italic', color: 'var(--cn-coral-300)' }}>connect</span>, to <span style={{ fontStyle: 'italic', color: 'var(--cn-coral-300)' }}>care</span>.
        </div>
      </div>
    </section>
  );
};
