// Full-width photo hero: consultation image (overlay-ready), top-cropped, scrimmed
// into brand navy so it blends with the header above and curves into the next
// section below. Image failures fall back to a brand gradient, never a broken frame.
const { useState: useStateHero, useRef: useRefHero } = React;
const useEffectHero = React.useLayoutEffect;

function SmartImage({ src, alt, className = '', style = {}, imgClassName = '', referrerPolicy = 'no-referrer', objectFit = 'cover', objectPosition = '50% 50%', loading = 'lazy' }) {
  const [failed, setFailed] = useStateHero(false);
  return (
    <div className={className} style={{ position: 'relative', overflow: 'hidden', ...style }}>
      {failed ? (
        <div aria-label={alt} role="img" style={{ position: 'absolute', inset: 0, background: 'linear-gradient(155deg, #EAF1FA 0%, #4A6FA4 60%, #1A3066 100%)' }}>
          <div aria-hidden="true" style={{ position: 'absolute', top: '14%', left: '12%', width: '46%', height: '46%', borderRadius: '46% 54% 57% 43% / 52% 41% 59% 48%', background: 'rgba(255,255,255,0.18)', filter: 'blur(10px)' }} />
        </div>
      ) : (
        <img
          src={src}
          alt={alt}
          loading={loading}
          referrerPolicy={referrerPolicy}
          onError={() => setFailed(true)}
          className={imgClassName}
          style={{ width: '100%', height: '100%', objectFit, objectPosition, display: 'block' }}
        />
      )}
    </div>
  );
}

function Hero() {
  const staticRender = useStaticRender();
  const reduced = usePrefersReducedMotion();
  const paraRef = useRefHero(null);
  // Gentle parallax: the photo drifts slower than the page (max ~56px), scaled
  // slightly so no edge is ever exposed. Skipped for reduced motion.
  useEffectHero(() => {
    if (reduced || staticRender) return undefined;
    let ticking = false;
    const on = () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        const el = paraRef.current;
        if (el) {
          const y = Math.min(56, window.pageYOffset * 0.14);
          el.style.transform = `translate3d(0, ${y.toFixed(2)}px, 0) scale(1.08)`;
        }
        ticking = false;
      });
    };
    on();
    window.addEventListener('scroll', on, { passive: true });
    return () => window.removeEventListener('scroll', on);
  }, [reduced, staticRender]);
  const words = [
    { t: 'Together,' }, { t: "let's" }, { t: 'create' },
    { t: 'Your', i: true }, { t: 'Will,' },
    { t: 'Your', i: true }, { t: 'Way' },
  ];
  const entr = (delay, name = 'riseIn', dur = 600) =>
    staticRender ? {} : { animation: `${name} ${dur}ms ${EASE} ${delay}ms both` };
  const mag = useMagnetic(3);

  return (
    <section
      id="top"
      data-dark="true"
      className="relative flex items-center overflow-hidden"
      style={{ minHeight: 'clamp(520px, 74vh, 700px)', background: '#1A3066' }}
    >
      {/* Photo, top-cropped (objectPosition favours the lower part of the frame).
          Wrapped for the scroll parallax. */}
      <div ref={paraRef} className="absolute inset-0" style={{ willChange: 'transform' }}>
        <SmartImage
          src="images/hero-consultation.jpg"
          alt="A friendly Will writing consultation at home"
          loading="eager"
          objectPosition="center 72%"
          className="absolute inset-0"
          style={{ position: 'absolute', inset: 0 }}
        />
      </div>
      <div className="hero-scrim" aria-hidden="true"></div>
      <div className="hero-top-blend" aria-hidden="true"></div>
      <Grain opacity={0.05} />

      {/* Content */}
      <div className="relative mx-auto w-full max-w-[1280px] px-5 sm:px-7" style={{ paddingTop: 'clamp(118px,15vh,150px)', paddingBottom: 'clamp(96px,13vh,132px)' }}>
        <div className="max-w-[680px]">
          <h1 className="font-display font-normal text-white" style={{ fontSize: 'clamp(38px,5.2vw,72px)', lineHeight: 1.06, letterSpacing: '-0.015em', textShadow: '0 2px 24px rgba(15,26,60,0.35)' }}>
            {words.map((w, i) => (
              // paddingBottom + negative margin: room for y/g descenders inside the
              // overflow-hidden reveal wrapper without adding line height.
              <span key={i} style={{ display: 'inline-block', overflow: 'hidden', verticalAlign: 'top', paddingBottom: '0.14em', marginBottom: '-0.14em' }}>
                <span
                  className="hero-anim"
                  style={{
                    display: 'inline-block',
                    fontStyle: w.i ? 'italic' : 'normal',
                    color: w.i ? '#FFCC57' : '#FFFFFF',
                    ...entr(150 + i * 90),
                  }}
                >
                  {w.t}
                </span>
                {i < words.length - 1 ? '\u00A0' : ''}
              </span>
            ))}
          </h1>

          {/* Signature flourish: a single pen stroke, drawn in after the headline */}
          <svg
            className={'hero-sig' + (staticRender ? '' : ' hero-sig-anim')}
            viewBox="0 0 280 28"
            fill="none"
            aria-hidden="true"
            style={{ display: 'block', width: 'clamp(170px, 22vw, 270px)', height: 'auto', marginTop: 'clamp(10px, 1.4vw, 18px)', marginLeft: 4 }}
          >
            <path
              d="M6 20 C 64 8, 150 6, 204 12 C 232 15, 252 19, 274 14"
              pathLength="1"
              stroke="#FFCC57"
              strokeWidth="4.5"
              strokeLinecap="round"
            />
          </svg>

          <p className="hero-anim mt-5 font-sans" style={{ fontSize: 18, lineHeight: 1.65, maxWidth: '50ch', color: 'rgba(255,255,255,0.92)', textShadow: '0 1px 12px rgba(15,26,60,0.3)', ...entr(400) }}>
            Specialists in Will writing and estate planning near Weston-super-Mare, North Somerset. We help families across Somerset, Bristol and beyond protect their loved ones, in person or online, with friendly, plain-English advice.
          </p>

          <div className="hero-anim mt-8 flex flex-col gap-3 sm:flex-row sm:items-center" style={entr(600)}>
            <a
              ref={mag.ref}
              onMouseMove={mag.onMouseMove}
              onMouseLeave={mag.onMouseLeave}
              href={BOOKING_URL}
              target="_blank"
              rel="noopener noreferrer"
              className="cta-sheen inline-flex items-center justify-center rounded-full bg-gold px-7 py-4 font-sans font-semibold text-[17px] text-navy hover:bg-gold-deep"
              style={{ boxShadow: '0 14px 30px -12px rgba(240,184,60,0.7)', transition: 'transform 250ms ' + EASE + ', background-color 250ms ' + EASE }}
            >
              Book an appointment
            </a>
            <a
              href={PHONE_TEL}
              className="inline-flex items-center justify-center gap-2 rounded-full px-7 py-4 font-sans font-semibold text-[17px] text-white"
              style={{ boxShadow: 'inset 0 0 0 1.5px rgba(255,255,255,0.65)', transition: 'background-color 250ms ' + EASE }}
              onMouseEnter={(e) => (e.currentTarget.style.background = 'rgba(255,255,255,0.1)')}
              onMouseLeave={(e) => (e.currentTarget.style.background = 'transparent')}
            >
              <Icon name="phone" size={18} strokeWidth={2} className="ico-ring" />
              Call {PHONE_DISPLAY}
            </a>
          </div>

          <p className="hero-anim mt-5 flex items-center gap-2 font-sans font-medium text-[14px]" style={{ color: 'rgba(255,255,255,0.85)', ...entr(720) }}>
            <span className="inline-flex h-5 w-5 items-center justify-center rounded-full" style={{ background: '#FFCC57', color: '#1A3066' }}>
              <Icon name="check" size={13} strokeWidth={3} />
            </span>
            Free initial chat. No obligation. Home visits or online.
          </p>
        </div>
      </div>

      {/* Organic curve blending the photo into the next section */}
      <div aria-hidden="true" style={{ position: 'absolute', bottom: -1, left: 0, right: 0, lineHeight: 0 }}>
        <svg viewBox="0 0 1440 90" preserveAspectRatio="none" style={{ display: 'block', width: '100%', height: 'clamp(36px,5vw,64px)' }}>
          <path d="M0,46 C260,92 520,2 760,28 C980,52 1230,86 1440,42 L1440,90 L0,90 Z" fill="#FDFBF6" />
        </svg>
      </div>
    </section>
  );
}

Object.assign(window, { Hero, SmartImage });
