// Hero — PIN + scroll-scrub: the hero pins to the viewport while the squeegee
// sweeps across the window driven by scroll position. When fully clean, the
// scroll releases naturally into the next section.

function Hero() {
  const scrubRef = React.useRef(null);
  const [progress, setProgress] = React.useState(0); // 0..1 squeegee sweep

  React.useEffect(() => {
    const onScroll = () => {
      const el = scrubRef.current;
      if (!el) return;
      const rect = el.getBoundingClientRect();
      const scrubHeight = el.offsetHeight - window.innerHeight; // how much scroll happens inside
      // scrolled = how far past the top of the scrubber we are
      const scrolled = -rect.top;
      const p = Math.max(0, Math.min(1, scrolled / Math.max(1, scrubHeight)));
      setProgress(p);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive:true });
    window.addEventListener('resize', onScroll);
    window.__setHeroProgress = (v) => setProgress(Math.max(0, Math.min(1, v)));
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, []);

  return (
    // OUTER — tall scroll scrubber. The user scrolls through this range,
    // and that scroll maps to squeegee progress. 180vh = 80vh of scroll room.
    <div id="top" ref={scrubRef} style={{ position:'relative', height:'180vh', background:'var(--ink)' }}>
      {/* INNER — sticky pinned hero, always fills viewport while scrubber is in frame */}
      <section style={{
        position:'sticky', top:0,
        height:'100vh',
        background:'var(--ink)', color:'#fff', overflow:'hidden',
      }}>
        {/* Subtle grid background */}
        <svg style={{ position:'absolute', inset:0, width:'100%', height:'100%', opacity:.05, pointerEvents:'none' }}>
          <defs>
            <pattern id="heroGrid" width="80" height="80" patternUnits="userSpaceOnUse">
              <path d="M 80 0 L 0 0 0 80" fill="none" stroke="#b7bdc4" strokeWidth="0.5" />
            </pattern>
          </defs>
          <rect width="100%" height="100%" fill="url(#heroGrid)" />
        </svg>

        <div className="container hero-grid" style={{ position:'relative', zIndex:2, height:'100%', display:'grid', gridTemplateColumns:'1fr 1fr', gap:64, alignItems:'center', paddingTop:110, paddingBottom:80 }}>

          {/* LEFT — words */}
          <div className="hero-copy">
            <div className="fade-up in" style={{ display:'flex', alignItems:'center', gap:14, marginBottom:28, fontSize:11, letterSpacing:'.24em', textTransform:'uppercase', color:'var(--accent)', fontWeight:500 }}>
              <span style={{ width:28, height:1, background:'var(--accent)' }} />
              Commercial Janitorial · Est. 2004
            </div>

            <h1 className="display fade-up in" style={{ fontSize:'clamp(52px, 6.5vw, 108px)', margin:0, color:'#fff', lineHeight:.98 }}>
              Experience<br/>
              <em className="italic-light" style={{ fontStyle:'italic' }}>the image.</em>
            </h1>

            <div className="fade-up in" style={{ fontSize:'clamp(15px, 1.1vw, 18px)', lineHeight:1.6, color:'rgba(255,255,255,.78)', marginTop:32, maxWidth:480, fontWeight:300, transitionDelay:'.15s' }}>
              Commercial cleaning across North Idaho and Spokane since 2004 — banks, clinics, offices, schools. Every account Todd has came from a referral.
            </div>

            <div className="fade-up in" style={{ display:'flex', gap:16, marginTop:40, alignItems:'center', flexWrap:'wrap', transitionDelay:'.3s' }}>
              <a href="tel:12088183175" className="btn btn-light">
                Call Todd
                <span className="mono" style={{ color:'var(--accent)', letterSpacing:0 }}>208·818·3175</span>
              </a>
              <a href="#services" className="btn btn-ghost" style={{ color:'rgba(255,255,255,.9)' }}>
                See what we clean →
              </a>
            </div>

            {/* Scroll cue — hint morphs when cleaning is underway */}
            <ScrollCue progress={progress} />
          </div>

          {/* RIGHT — foggy window + squeegee */}
          <div className="hero-window-wrap">
            <SqueegeeWindow progress={progress} />
          </div>
        </div>

        {/* Footer data strip */}
        <div style={{ position:'absolute', bottom:0, left:0, right:0, padding:'20px 0', borderTop:'1px solid rgba(255,255,255,.1)', background:'rgba(11,20,48,.6)', backdropFilter:'blur(8px)', zIndex:3 }}>
          <div className="container" style={{ display:'flex', justifyContent:'space-between', alignItems:'center', fontFamily:'var(--mono)', fontSize:11, color:'rgba(255,255,255,.55)', gap:16, flexWrap:'wrap' }}>
            <span>22 yrs · Word-of-mouth only</span>
            <span>Licensed · Bonded · Insured · Green Certified</span>
            <span>Hayden · Coeur d'Alene · Sandpoint · Spokane</span>
          </div>
        </div>

        {/* Progress hairline at top of viewport — subtle scrubbing feedback */}
        <div style={{ position:'absolute', top:0, left:0, right:0, height:2, zIndex:4, background:'rgba(255,255,255,.06)' }}>
          <div style={{ height:'100%', width:`${progress*100}%`, background:'var(--accent)', transition:'width .05s linear' }} />
        </div>
      </section>
    </div>
  );
}

function ScrollCue({ progress }) {
  let label = 'SCROLL TO CLEAN';
  if (progress > 0.02 && progress < 0.98) label = `CLEANING · ${Math.round(progress*100)}%`;
  else if (progress >= 0.98) label = 'KEEP SCROLLING';
  return (
    <div className="fade-up in" style={{ marginTop:56, display:'flex', alignItems:'center', gap:14, fontFamily:'var(--mono)', fontSize:11, color:'rgba(255,255,255,.5)', letterSpacing:'.15em', transitionDelay:'.45s' }}>
      <span style={{ display:'inline-block', width:24, height:1, background:'rgba(255,255,255,.3)' }} />
      {label}
      {progress < 0.02 && <span style={{ marginLeft:4, display:'inline-block', animation:'bounce-arrow 1.6s ease-in-out infinite' }}>↓</span>}
    </div>
  );
}

// ── Squeegee window component ──────────────────────────
// A framed window. Behind it: a sharp city scene.
// In front: a foggy/dripping overlay with a clean band that expands left→right as `progress` goes 0→1.
function SqueegeeWindow({ progress }) {
  // Pacific Northwest — misty evergreens, moody light over water/mountains
  const cityImg = 'https://images.unsplash.com/photo-1502786129293-79981df4e689?auto=format&fit=crop&w=1400&q=80';

  // Squeegee position (0..1) — RIGHT to LEFT: 100% → 0%
  const sx = 100 - progress * 100;
  // Clean band is everything to the right of the squeegee
  const cleanEdge = 100 - progress * 100;

  // Droplets — randomized but stable across renders
  const droplets = React.useMemo(() => {
    const d = [];
    for (let i = 0; i < 60; i++) {
      d.push({
        x: Math.random() * 100,
        y: Math.random() * 100,
        r: 3 + Math.random() * 7,
        opacity: .6 + Math.random() * .4,
      });
    }
    return d;
  }, []);

  // Short drip trails under a subset of droplets
  const drips = React.useMemo(() => {
    const d = [];
    for (let i = 0; i < 22; i++) {
      d.push({
        x: Math.random() * 100,
        yStart: Math.random() * 65,
        length: 10 + Math.random() * 28,
        opacity: .4 + Math.random() * .4,
        delay: Math.random() * 6,
        duration: 5 + Math.random() * 6,
      });
    }
    return d;
  }, []);

  return (
    <div className="squeegee-window" style={{
      position:'relative',
      width:'100%',
      aspectRatio:'4 / 5',
      maxHeight:'70vh',
      background:'#0a0f24',
      border:'1px solid rgba(255,255,255,.08)',
      boxShadow:'0 30px 80px rgba(0,0,0,.4), inset 0 0 0 1px rgba(255,255,255,.03)',
      overflow:'hidden',
    }}>
      {/* SHARP BACKGROUND — Pacific Northwest, evergreens in mist */}
      <img src={cityImg} alt="" style={{
        position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover',
        filter:'brightness(.72) contrast(1.02) saturate(.85)',
      }} />

      {/* Subtle tint to marry with the navy */}
      <div style={{ position:'absolute', inset:0, background:'linear-gradient(180deg, rgba(11,20,48,.18) 0%, rgba(11,20,48,.38) 100%)' }} />

      {/* SUBTLE CONDENSATION OVERLAY — clipped by clean band (right-to-left reveal).
          Much lighter than before — think morning mist on glass, not milk. */}
      <div style={{
        position:'absolute', inset:0,
        clipPath: `polygon(0 0, ${cleanEdge}% 0, ${cleanEdge}% 100%, 0 100%)`,
        transition: 'clip-path .08s linear',
      }}>
        {/* Light haze — soft frost, not opaque */}
        <div style={{ position:'absolute', inset:0, background:'rgba(235,240,245,.28)', backdropFilter:'blur(3px)', WebkitBackdropFilter:'blur(3px)' }} />
        {/* Gentle uneven condensation patches */}
        <div style={{ position:'absolute', inset:0, background:'radial-gradient(ellipse at 25% 35%, rgba(255,255,255,.22), transparent 55%), radial-gradient(ellipse at 75% 65%, rgba(255,255,255,.18), transparent 60%), radial-gradient(ellipse at 15% 85%, rgba(220,230,240,.15), transparent 50%)' }} />

        {/* A few delicate drips — fewer and softer */}
        <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position:'absolute', inset:0, width:'100%', height:'100%' }}>
          {drips.slice(0, 10).map((d, i) => (
            <line key={i}
              x1={d.x} y1={d.yStart} x2={d.x} y2={d.yStart + d.length}
              stroke="rgba(255,255,255,.35)" strokeWidth="0.3" strokeLinecap="round" opacity={d.opacity * .5}
              style={{ animation: `drip ${d.duration}s ${d.delay}s ease-in infinite` }}
            />
          ))}
        </svg>
      </div>

      {/* CLEAN EDGE — very subtle water line left by the blade */}
      {progress > 0 && progress < 1 && (
        <div style={{
          position:'absolute', top:0, bottom:0,
          left:`calc(${cleanEdge}% - 1px)`,
          width:2,
          background:'rgba(255,255,255,.35)',
          zIndex:6, pointerEvents:'none',
        }} />
      )}

      {/* SQUEEGEE — minimal, professional. Thin charcoal handle, steel channel, black blade. */}
      {progress > 0.002 && (
        <div style={{
          position:'absolute', top:0, bottom:0,
          left:`${sx}%`,
          transform:'translateX(-50%)',
          width:4,
          zIndex:7, pointerEvents:'none',
          transition:'left .05s linear',
        }}>
          {/* Handle — slim matte charcoal, slight angle like it's being held */}
          <div style={{
            position:'absolute', top:'50%', right:'100%',
            transform:'translateY(-50%) rotate(-6deg)',
            transformOrigin:'right center',
            marginRight:-2,
            width:78, height:6,
            background:'linear-gradient(180deg, #2a2f38 0%, #1a1e26 100%)',
            borderRadius:1,
            boxShadow:'0 2px 6px rgba(0,0,0,.35)',
          }} />
          {/* Ferrule — tiny brass collar where handle meets head */}
          <div style={{
            position:'absolute', top:'50%', right:'100%',
            transform:'translateY(-50%)',
            width:6, height:10,
            background:'linear-gradient(180deg, #8a7a55, #5a4a2d)',
            borderRadius:1,
          }} />
          {/* Steel channel — the thin metal spine holding the blade */}
          <div style={{
            position:'absolute', top:2, bottom:2, left:0, width:3,
            background:'linear-gradient(90deg, #9aa3ae 0%, #d8dde3 50%, #8892a0 100%)',
            boxShadow:'0 0 4px rgba(0,0,0,.35)',
          }} />
          {/* Rubber blade — thin black line */}
          <div style={{
            position:'absolute', top:6, bottom:6, left:3, width:1.5,
            background:'#0a0a0a',
          }} />
        </div>
      )}

      {/* FULL CLEAN — shine flash */}
      {progress >= 1 && (
        <div style={{
          position:'absolute', inset:0,
          background:'linear-gradient(110deg, transparent 40%, rgba(255,255,255,.15) 50%, transparent 60%)',
          animation:'sparkle 2s ease-out',
          pointerEvents:'none',
        }} />
      )}
    </div>
  );
}

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