// hero-doctor.jsx — the "by physicians" signing scene.
//
// A rigged cartoon doctor (white coat, scrubs, stethoscope) walks onto the
// hero stage, stops center, looks at the viewer and waves, then walks up to
// the "by physicians" scrawl and writes it out — the scrawl's clip-path
// reveal + pen-light + lift-off flare are held until his pen touches down
// (via the `doc-write` class on the hero section).
//
// Pure CSS/SVG rig: every limb is a group with a viewBox-unit transform
// origin; poses are classes on the actor. Transform/opacity only.
// Desktop + prefers-reduced-motion: no-preference only — otherwise the
// component removes itself and the scrawl auto-draws on its original timing.

const DOC_SPEED = 0.34; // px per ms — brisk cartoon walk

const DOC_CSS = `
  .doc-actor { will-change: transform; }
  .doc-actor svg { overflow: visible; display: block; }

  /* limbs return smoothly whenever a pose class drops */
  .doc-arm-l, .doc-arm-r, .doc-leg-l, .doc-leg-r, .doc-head, .doc-torso-lean {
    transition: transform .35s cubic-bezier(.34,1.56,.64,1);
  }
  .doc-pen { opacity: 0; transition: opacity .2s ease; }
  .doc-shadow { transform-origin: 60px 143px; }

  /* —— walk cycle —— */
  .doc-walking .doc-leg-l { animation: docLegL .5s linear infinite; }
  .doc-walking .doc-leg-r { animation: docLegR .5s linear infinite; }
  .doc-walking .doc-arm-l { animation: docArmL .5s linear infinite; }
  .doc-walking .doc-arm-r { animation: docArmR .5s linear infinite; }
  .doc-walking .doc-bob   { animation: docBob .25s ease-in-out infinite alternate; }
  .doc-walking .doc-shadow { animation: docShadow .25s ease-in-out infinite alternate; }
  @keyframes docLegL { 0% { transform: rotate(18deg); } 50% { transform: rotate(-18deg); } 100% { transform: rotate(18deg); } }
  @keyframes docLegR { 0% { transform: rotate(-18deg); } 50% { transform: rotate(18deg); } 100% { transform: rotate(-18deg); } }
  @keyframes docArmL { 0% { transform: rotate(-14deg); } 50% { transform: rotate(14deg); } 100% { transform: rotate(-14deg); } }
  @keyframes docArmR { 0% { transform: rotate(14deg); } 50% { transform: rotate(-14deg); } 100% { transform: rotate(14deg); } }
  @keyframes docBob { from { transform: translateY(0); } to { transform: translateY(-2.6px); } }
  @keyframes docShadow { from { transform: scaleX(1); opacity: .35; } to { transform: scaleX(.92); opacity: .28; } }

  /* —— wave: arm swings high, two friendly wiggles; brows lift —— */
  .doc-waving .doc-arm-r { animation: docWave 1.55s cubic-bezier(.34,1.3,.5,1) forwards; }
  .doc-waving .doc-head { transform: rotate(-4deg); }
  .doc-waving .doc-brows { transform: translateY(-1.6px); }
  .doc-waving .doc-bob { animation: docBob 1.1s ease-in-out infinite alternate; }
  @keyframes docWave {
    0%   { transform: rotate(0); }
    30%  { transform: rotate(-152deg); }
    45%  { transform: rotate(-128deg); }
    60%  { transform: rotate(-156deg); }
    75%  { transform: rotate(-128deg); }
    100% { transform: rotate(-146deg); }
  }

  /* —— writing: lean in, pen up at chest-forward, quick scribble —— */
  .doc-writing .doc-torso-lean { transform: rotate(4deg); }
  .doc-writing .doc-head { transform: rotate(-5deg); }
  .doc-writing .doc-arm-r { animation: docScribble .22s ease-in-out infinite alternate; }
  .doc-writing .doc-arm-l { transform: rotate(-8deg); }
  .doc-writing .doc-pen { opacity: 1; }
  @keyframes docScribble {
    from { transform: rotate(-88deg); }
    to   { transform: rotate(-101deg); }
  }

  /* —— ta-da: little hop, both arms up —— */
  .doc-tada .doc-bob { animation: docHop .75s cubic-bezier(.34,1.56,.64,1); }
  .doc-tada .doc-arm-r { transform: rotate(-150deg); }
  .doc-tada .doc-arm-l { transform: rotate(150deg); }
  .doc-tada .doc-brows { transform: translateY(-1.6px); }
  @keyframes docHop {
    0% { transform: translateY(0); }
    40% { transform: translateY(-9px); }
    70% { transform: translateY(0); }
    85% { transform: translateY(-3px); }
    100% { transform: translateY(0); }
  }

  /* front/back views: he turns his back to the audience while writing */
  .doc-view-back { display: none; }
  .doc-writing .doc-view-back { display: block; }
  .doc-writing .doc-view-front { display: none; }

  /* idle blink, always on */
  .doc-eyes { animation: docBlink 4.2s linear infinite; transform-origin: 60px 26px; }
  @keyframes docBlink {
    0%, 91.5%, 95.5%, 100% { transform: scaleY(1); }
    93.5% { transform: scaleY(0.12); }
  }
`;

function HeroDoctorSvg() {
  return (
    <svg viewBox="0 0 120 150" width="100%" height="100%" aria-hidden="true">
      {/* ground shadow */}
      <ellipse className="doc-shadow" cx="60" cy="143" rx="24" ry="3.6" fill="#04120C" opacity="0.35" />

      <g className="doc-bob">
        {/* ============ FRONT VIEW (walk, wave, ta-da) ============ */}
        <g className="doc-view-front">
        {/* legs (behind coat hem) */}
        <g className="doc-leg-l" style={{ transformOrigin: '54px 104px' }}>
          <path d="M54 104 L54 132" stroke="#33424D" strokeWidth="8" strokeLinecap="round" fill="none" />
          <path d="M48.5 134.5 Q54 132.5 59 134.5 L59 139 Q53.5 141 47.5 139 Z" fill="#22303A" />
        </g>
        <g className="doc-leg-r" style={{ transformOrigin: '66px 104px' }}>
          <path d="M66 104 L66 132" stroke="#3B4C58" strokeWidth="8" strokeLinecap="round" fill="none" />
          <path d="M60.5 134.5 Q66 132.5 71 134.5 L71 139 Q65.5 141 59.5 139 Z" fill="#2A3944" />
        </g>

        <g className="doc-torso-lean" style={{ transformOrigin: '60px 106px' }}>
          {/* left arm (viewer's left) */}
          <g className="doc-arm-l" style={{ transformOrigin: '47px 52px' }}>
            <path d="M47 52 L43 79" stroke="#FBFDFC" strokeWidth="7" strokeLinecap="round" fill="none" />
            <path d="M47 52 L43 79" stroke="#E3EAE5" strokeWidth="7" strokeLinecap="round" fill="none" opacity="0.25" />
            <circle cx="42.4" cy="84" r="3.5" fill="#F0BD8F" />
          </g>

          {/* white coat */}
          <path d="M60 45 L46.5 49 Q42.5 50.2 42 55.5 L40.5 103.5 Q40.4 107.5 44.5 107.5 L75.5 107.5 Q79.6 107.5 79.5 103.5 L78 55.5 Q77.5 50.2 73.5 49 Z"
            fill="#FBFDFC" stroke="#DCE5DF" strokeWidth="1.2" />
          {/* scrubs under the coat */}
          <path d="M52.5 47.5 L67.5 47.5 L66 78 L54 78 Z" fill="#2C8C64" />
          <path d="M56 47.5 L60 54 L64 47.5 Z" fill="#20714F" />
          {/* coat opening + hem details */}
          <path d="M52.5 47.5 L51 107.5 M67.5 47.5 L69 107.5" stroke="#E3EAE5" strokeWidth="1.2" fill="none" />
          <path d="M45 90 L51 90 M69 90 L75 90" stroke="#E3EAE5" strokeWidth="1.2" />
          {/* lapels */}
          <path d="M52.5 47.5 L57 47.5 L52 60 Z M67.5 47.5 L63 47.5 L68 60 Z" fill="#F2F6F3" stroke="#DCE5DF" strokeWidth="0.8" />
          {/* id badge */}
          <rect x="66.5" y="61" width="8" height="6" rx="1" fill="#EAF4EE" stroke="#CBDCD2" strokeWidth="0.8" />
          <rect x="66.5" y="61" width="8" height="2.1" rx="1" fill="#2C8C64" />

          {/* stethoscope */}
          <path d="M53.5 48.5 C53.5 60 66.5 60 66.5 48.5" fill="none" stroke="#3B4A52" strokeWidth="2.6" strokeLinecap="round" />
          <path d="M53.8 54.5 C50.5 61 50 65 51 69.5" fill="none" stroke="#3B4A52" strokeWidth="2.2" strokeLinecap="round" />
          <circle cx="51.2" cy="72.5" r="3.9" fill="#90A4AE" stroke="#3B4A52" strokeWidth="1.4" />
          <circle cx="51.2" cy="72.5" r="1.5" fill="#3B4A52" />
          <circle cx="53.5" cy="48.5" r="1.7" fill="#3B4A52" />
          <circle cx="66.5" cy="48.5" r="1.7" fill="#3B4A52" />

          {/* right arm (waves in front view) */}
          <g className="doc-arm-r" style={{ transformOrigin: '73px 52px' }}>
            <path d="M73 52 L77 79" stroke="#FBFDFC" strokeWidth="7" strokeLinecap="round" fill="none" />
            <circle cx="77.6" cy="84" r="3.5" fill="#F0BD8F" />
          </g>

          {/* head */}
          <g className="doc-head" style={{ transformOrigin: '60px 42px' }}>
            <rect x="56.5" y="38" width="7" height="8" rx="2.4" fill="#E5AE7F" />
            <circle cx="43.5" cy="27" r="3" fill="#F0BD8F" />
            <circle cx="76.5" cy="27" r="3" fill="#F0BD8F" />
            <circle cx="60" cy="26" r="16.5" fill="#F0BD8F" />
            {/* hair */}
            <path d="M43.5 25 Q44.5 8.5 60 8.5 Q75.5 8.5 76.5 25 Q68 15.5 59 16.5 Q50 17.5 43.5 25 Z" fill="#33261F" />
            {/* brows */}
            <g className="doc-brows" style={{ transition: 'transform .3s ease' }}>
              <path d="M50 20.8 Q53.5 19 56.5 20.6" stroke="#33261F" strokeWidth="1.5" strokeLinecap="round" fill="none" />
              <path d="M63.5 20.6 Q66.5 19 70 20.8" stroke="#33261F" strokeWidth="1.5" strokeLinecap="round" fill="none" />
            </g>
            {/* eyes */}
            <g className="doc-eyes">
              <circle cx="54" cy="26" r="2" fill="#2B2B2B" />
              <circle cx="66" cy="26" r="2" fill="#2B2B2B" />
              <circle cx="54.7" cy="25.3" r="0.6" fill="#fff" />
              <circle cx="66.7" cy="25.3" r="0.6" fill="#fff" />
            </g>
            {/* cheeks + smile */}
            <circle cx="49" cy="30.5" r="2.1" fill="#E89B72" opacity="0.45" />
            <circle cx="71" cy="30.5" r="2.1" fill="#E89B72" opacity="0.45" />
            <path d="M54 32 Q60 36.8 66 32" stroke="#B26A4A" strokeWidth="1.7" strokeLinecap="round" fill="none" />
          </g>
        </g>
        </g>

        {/* ============ BACK VIEW (writing — back to the audience,
             pen in his LEFT hand, which sits viewer-right) ============ */}
        <g className="doc-view-back">
        <g className="doc-leg-l" style={{ transformOrigin: '54px 104px' }}>
          <path d="M54 104 L54 132" stroke="#33424D" strokeWidth="8" strokeLinecap="round" fill="none" />
          <path d="M48.5 134.5 Q54 132.5 59 134.5 L59 139 Q53.5 141 47.5 139 Z" fill="#22303A" />
        </g>
        <g className="doc-leg-r" style={{ transformOrigin: '66px 104px' }}>
          <path d="M66 104 L66 132" stroke="#3B4C58" strokeWidth="8" strokeLinecap="round" fill="none" />
          <path d="M60.5 134.5 Q66 132.5 71 134.5 L71 139 Q65.5 141 59.5 139 Z" fill="#2A3944" />
        </g>

        <g className="doc-torso-lean" style={{ transformOrigin: '60px 106px' }}>
          {/* his right arm hangs (viewer-left) */}
          <g className="doc-arm-l" style={{ transformOrigin: '47px 52px' }}>
            <path d="M47 52 L43 79" stroke="#FBFDFC" strokeWidth="7" strokeLinecap="round" fill="none" />
            <circle cx="42.4" cy="84" r="3.5" fill="#F0BD8F" />
          </g>

          {/* coat, from behind: plain back, center seam, shoulder yoke, vent */}
          <path d="M60 45 L46.5 49 Q42.5 50.2 42 55.5 L40.5 103.5 Q40.4 107.5 44.5 107.5 L75.5 107.5 Q79.6 107.5 79.5 103.5 L78 55.5 Q77.5 50.2 73.5 49 Z"
            fill="#FBFDFC" stroke="#DCE5DF" strokeWidth="1.2" />
          <path d="M46 57 Q60 61 74 57" stroke="#E3EAE5" strokeWidth="1.2" fill="none" />
          <path d="M60 61 L60 96" stroke="#E3EAE5" strokeWidth="1.2" />
          <path d="M60 96 L57.5 107.5 M60 96 L62.5 107.5" stroke="#E3EAE5" strokeWidth="1.2" fill="none" />
          {/* collar band */}
          <path d="M52.5 47.5 Q60 51.5 67.5 47.5 L66.8 51.5 Q60 55 53.2 51.5 Z" fill="#F2F6F3" stroke="#DCE5DF" strokeWidth="0.8" />
          {/* stethoscope tube peeking over both shoulders */}
          <path d="M53 48.5 q-2.5 3.5 -1.5 7" fill="none" stroke="#3B4A52" strokeWidth="2.2" strokeLinecap="round" />
          <path d="M67 48.5 q2.5 3.5 1.5 7" fill="none" stroke="#3B4A52" strokeWidth="2.2" strokeLinecap="round" />

          {/* his LEFT arm (viewer-right) raised, writing — scribble rig */}
          <g className="doc-arm-r" style={{ transformOrigin: '73px 52px' }}>
            <path d="M73 52 L77 79" stroke="#FBFDFC" strokeWidth="7" strokeLinecap="round" fill="none" />
            <circle cx="77.6" cy="84" r="3.5" fill="#F0BD8F" />
            <g className="doc-pen">
              <rect x="76.6" y="85.5" width="2" height="9.5" rx="1" fill="#26343B" />
              <path d="M76.6 95 L78.6 95 L77.6 98 Z" fill="#5FD39A" />
            </g>
          </g>

          {/* head from behind: full hair, ears, neck */}
          <g className="doc-head" style={{ transformOrigin: '60px 42px' }}>
            <rect x="56.5" y="38" width="7" height="8" rx="2.4" fill="#E5AE7F" />
            <circle cx="43.5" cy="27" r="3" fill="#F0BD8F" />
            <circle cx="76.5" cy="27" r="3" fill="#F0BD8F" />
            <circle cx="60" cy="26" r="16.5" fill="#F0BD8F" />
            <path d="M43.5 28 Q43.5 8.5 60 8.5 Q76.5 8.5 76.5 28 Q76.5 40.5 60 41.5 Q43.5 40.5 43.5 28 Z" fill="#33261F" />
            {/* hair whorl */}
            <path d="M62 17 q4.5 1.5 3 6 q-1.5 3.5 -5 2.5" fill="none" stroke="#221913" strokeWidth="1.1" strokeLinecap="round" />
          </g>
        </g>
        </g>
      </g>
    </svg>
  );
}

function HeroDoctor() {
  const holderRef = React.useRef(null);
  const [scene, setScene] = React.useState(null);
  const [pose, setPose] = React.useState('idle');
  const [move, setMove] = React.useState({ x: 0, dur: 0 });
  const [gone, setGone] = React.useState(false);

  React.useEffect(() => {
    const holder = holderRef.current;
    if (!holder) return;
    const section = holder.closest('section');
    const okMotion = window.matchMedia &&
      window.matchMedia('(prefers-reduced-motion: no-preference)').matches;
    if (!section) { setGone(true); return; }
    // Same choreography at every width; reduced-motion gets the auto-draw.
    if (!okMotion) { setGone(true); return; }
    const scrawl = section.querySelector('.hero-script-glow');
    if (!scrawl) { setGone(true); return; }

    // Hold the scrawl's auto-draw NOW — before its 1.35s default timing —
    // so it can't fire while we wait for the artwork image to load.
    section.classList.add('doc-mode');

    const timers = [];
    const at = (t, fn) => timers.push(setTimeout(fn, t));
    let began = false;

    const bail = () => {
      section.classList.remove('doc-mode', 'doc-write');
      setGone(true);
    };

    const begin = () => {
      if (began) return;
      began = true;

      const sRect = section.getBoundingClientRect();
      const gRect = scrawl.getBoundingClientRect();
      if (!gRect.width || !gRect.height) { bail(); return; }

    // Scale the actor to the artwork. He stands LOWER than the headline so
    // his raised pen hand — not his head — meets the scrawl. With the writing
    // arm at ~-94°, the pen tip sits at ≈ (0.97w, 0.29h) of the actor box, so
    // we align that point with the scrawl's left edge / vertical center.
    const h = Math.max(104, Math.min(138, gRect.height * 1.85));
    const w = h * (120 / 150);
    const gLeft = gRect.left - sRect.left;
    const gCenterY = (gRect.top - sRect.top) + gRect.height / 2;
    const top = gCenterY - h * 0.29;
    const xEnter = sRect.width + 70;              // walks IN from the right
    const xWrite = gLeft - w * 0.97;              // pen tip on the first stroke
    const xWave = Math.min((gRect.right - sRect.left) + 24, sRect.width - w - 16); // waves just right of "physicians,"
      const slide = gRect.width * 0.95;           // pen tracks the reveal edge
      const xExit = -w - 90;                      // exits stage left

      setScene({ w, h, top });
      setMove({ x: xEnter, dur: 0 });

      const d1 = Math.round(Math.abs(xWave - xEnter) / DOC_SPEED);
    const d2 = Math.round(Math.abs(xWrite - xWave) / DOC_SPEED);
    const d3 = Math.round(Math.abs((xWrite + slide) - xExit) / DOC_SPEED);

    let t = 120;
    at(t, () => { setPose('walking'); setMove({ x: xWave, dur: d1 }); });
    t += d1;
    at(t, () => setPose('waving'));            // stop, face the viewer, wave
    t += 1650;
    at(t, () => { setPose('walking'); setMove({ x: xWrite, dur: d2 }); });
    t += d2;
    at(t, () => {                              // pen down — scrawl draws now
      setPose('writing');
      // Drive the reveal imperatively with WAAPI — a CSS animation attached
      // via ancestor-class swap can fail to start its clock; animate() always
      // runs and takes precedence in composite order.
      const drawEase = 'cubic-bezier(.45,.05,.35,1)';
      const reveal = scrawl.querySelector('.hero-script-reveal');
      const pen = scrawl.querySelector('.hero-script-pen');
      const flare = scrawl.querySelector('.hero-script-flare');
      if (reveal && reveal.animate) {
        reveal.animate(
          [{ clipPath: 'inset(0 100% 0 0)' }, { clipPath: 'inset(0 0 0 0)' }],
          { duration: 1700, easing: drawEase, fill: 'forwards' });
      }
      if (pen && pen.animate) {
        pen.animate([
          { left: '0%', opacity: 0 },
          { opacity: 1, offset: 0.06 },
          { opacity: 1, offset: 0.88 },
          { left: '100%', opacity: 0 }
        ], { duration: 1700, easing: drawEase, fill: 'forwards' });
      }
      if (flare && flare.animate) {
        flare.animate([
          { opacity: 0, transform: 'scale(0.3)' },
          { opacity: 0.95, transform: 'scale(1.25)', offset: 0.35 },
          { opacity: 0, transform: 'scale(1.65)' }
        ], { duration: 750, delay: 1570, easing: 'cubic-bezier(.2,.7,.3,1)', fill: 'both' });
      }
      setMove({ x: xWrite + slide, dur: 1700 });
    });
    t += 1700 + 420;                           // draw + flare beat
    at(t, () => setPose('tada'));
    t += 950;
    at(t, () => { setPose('walking'); setMove({ x: xExit, dur: d3 }); });
    t += d3 + 100;
    at(t, () => setGone(true));
    };

    // The scrawl artwork is an <img>; its width is 0 until the PNG loads.
    // Start only once it has real geometry (with a safety timeout).
    const img = scrawl.querySelector('img');
    if (img && !img.complete) {
      img.addEventListener('load', begin, { once: true });
      img.addEventListener('error', bail, { once: true });
      timers.push(setTimeout(() => { if (!began) begin(); }, 3500));
    } else {
      begin();
    }

    return () => {
      timers.forEach(clearTimeout);
      if (!began) section.classList.remove('doc-mode', 'doc-write');
    };
  }, []);

  return (
    <div ref={holderRef} aria-hidden="true"
    style={{ position: 'absolute', inset: 0, zIndex: 5, pointerEvents: 'none' }}>
      <style>{DOC_CSS}</style>
      {scene && !gone &&
      <div className={'doc-actor doc-' + pose} style={{
        position: 'absolute', top: scene.top, left: 0,
        width: scene.w, height: scene.h,
        transform: 'translateX(' + move.x + 'px)',
        transition: move.dur ? 'transform ' + move.dur + 'ms linear' : 'none'
      }}>
        <HeroDoctorSvg />
      </div>}
    </div>
  );
}

Object.assign(window, { HeroDoctor });
