/* =====================================================================
   Hero v2 — CSS shader background, animated headline, stat sidebar.
   ===================================================================== */
const { useEffect: useEfHr, useRef: useRefHr, useState: useStHr } = React;

/* Plains horizon — soft Oklahoma silhouette anchoring the sky scene.
   Two parallax planes (mid + front) of low rolling horizon with a few
   site-relevant accents: a grain elevator cluster, a windmill, a lone
   mesquite. Pure SVG. Tones shift with TOD via color-mix on accent. */
function HeroHorizon({ tod }) {
  const silhouette = {
    night:   'color-mix(in oklab, var(--ink-000) 92%, var(--accent) 8%)',
    sunrise: 'color-mix(in oklab, var(--ink-100) 86%, var(--accent) 14%)',
    day:     'color-mix(in oklab, var(--ink-100) 84%, var(--accent) 16%)',
    sunset:  'color-mix(in oklab, var(--ink-000) 90%, var(--accent) 10%)',
  }[tod] || 'var(--ink-000)';
  const midPlane = {
    night:   'color-mix(in oklab, var(--ink-100) 70%, var(--accent) 6%)',
    sunrise: 'color-mix(in oklab, var(--ink-200) 72%, var(--accent) 16%)',
    day:     'color-mix(in oklab, var(--ink-200) 70%, var(--accent) 12%)',
    sunset:  'color-mix(in oklab, var(--ink-100) 70%, var(--accent) 14%)',
  }[tod] || 'var(--ink-100)';
  return (
    <svg aria-hidden viewBox="0 0 1600 600" preserveAspectRatio="xMidYMax slice"
      style={{ position:'absolute', left:0, right:0, bottom:0, width:'100%',
        height:'58%', pointerEvents:'none' }}>
      <defs>
        <linearGradient id="horizonFade" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="var(--bg)" stopOpacity="0"/>
          <stop offset="55%" stopColor="var(--bg)" stopOpacity="0.35"/>
          <stop offset="100%" stopColor="var(--bg)" stopOpacity="0.85"/>
        </linearGradient>
      </defs>
      {/* Mid-plane: distant rolling plains */}
      <g style={{ transition:'fill 1.2s var(--ease-out)' }}>
        <path fill={midPlane}
          d="M0,460 C120,440 220,432 340,438 C460,444 540,460 660,452 C780,444 880,418 1000,420 C1120,422 1220,444 1340,438 C1460,432 1540,420 1600,418 L1600,600 L0,600 Z"/>
        <g fill={midPlane} opacity="0.95">
          <rect x="218" y="402" width="10" height="38"/>
          <rect x="232" y="394" width="14" height="46"/>
          <rect x="250" y="398" width="12" height="42"/>
          <rect x="266" y="396" width="10" height="44"/>
        </g>
      </g>
      {/* Front-plane: closer horizon with accents */}
      <g style={{ transition:'fill 1.2s var(--ease-out)' }}>
        <path fill={silhouette}
          d="M0,508 C100,500 180,494 290,500 C400,506 480,520 590,512 C700,504 800,488 920,492 C1040,496 1140,514 1260,510 C1380,506 1480,498 1600,494 L1600,600 L0,600 Z"/>
        {/* Lone tree */}
        <g fill={silhouette}>
          <rect x="1086" y="478" width="3" height="24"/>
          <ellipse cx="1087.5" cy="476" rx="14" ry="10"/>
          <ellipse cx="1080" cy="481" rx="9" ry="6"/>
          <ellipse cx="1095" cy="481" rx="9" ry="6"/>
        </g>
        {/* Windmill */}
        <g fill={silhouette}>
          <path d="M120,506 L122,468 L124,506 Z"/>
          <circle cx="123" cy="465" r="2.4"/>
          <path d="M123,465 L131,461 M123,465 L119,457 M123,465 L115,469 M123,465 L127,473"
            stroke={silhouette} strokeWidth="1.4" fill="none" strokeLinecap="round"/>
        </g>
        <path d="M620,514 C760,510 880,504 1020,506"
          stroke="color-mix(in oklab, var(--fg-1) 12%, transparent)"
          strokeWidth="0.6" fill="none" strokeDasharray="1 4" opacity="0.55"/>
        <rect x="0" y="488" width="1600" height="112" fill="url(#horizonFade)"/>
      </g>
    </svg>
  );
}

/* Oklahoma silhouette — actual state outline, used as a faint backdrop mark.
   Path traced from a simplified state boundary; sits low-right behind the
   stat sidebar where it doesn't compete with the headline. */
function OklahomaMark() {
  return (
    <svg aria-hidden viewBox="0 0 200 110" preserveAspectRatio="xMidYMid meet"
      style={{ position:'absolute', right:'-3%', bottom:'8%', width:'42%', maxWidth:560,
        opacity:0.10, color:'var(--fg-1)', mixBlendMode:'screen',
        pointerEvents:'none', transition:'opacity 1.2s var(--ease-out)' }}>
      {/* Panhandle + main body — recognizable OK shape */}
      <path d="M 6,32 L 52,32 L 52,18 L 134,18 L 142,22 L 152,20 L 162,24
               L 174,22 L 188,28 L 194,40 L 192,58 L 184,70 L 174,78 L 168,86
               L 158,92 L 144,96 L 128,98 L 110,96 L 92,98 L 76,96 L 60,92
               L 48,88 L 38,82 L 28,78 L 20,72 L 14,62 L 8,50 L 6,32 Z"
        fill="none" stroke="currentColor" strokeWidth="0.6"/>
      {/* OKC marker — small target where Oklahoma City sits */}
      <g transform="translate(118,62)">
        <circle r="1.4" fill="var(--accent)"/>
        <circle r="4" fill="none" stroke="var(--accent)" strokeWidth="0.4" opacity="0.7"/>
        <circle r="8" fill="none" stroke="var(--accent)" strokeWidth="0.3" opacity="0.4"/>
      </g>
      <text x="124" y="60" fontFamily="JetBrains Mono, monospace" fontSize="3"
        fill="currentColor" opacity="0.7" letterSpacing="0.2">OKC · HQ</text>
      <text x="100" y="108" fontFamily="JetBrains Mono, monospace" fontSize="2.4"
        textAnchor="middle" fill="currentColor" opacity="0.5" letterSpacing="0.4">
        OKLAHOMA · 35.47°N 97.52°W
      </text>
    </svg>
  );
}

/* Edition mark — small vertical type running up the right edge.
   The only typographic flourish in the backdrop; everything else was
   removed for being too noisy. */
function HeroBackdropType() {
  return (
    <div aria-hidden style={{ position:'absolute', inset:0, overflow:'hidden',
      pointerEvents:'none', zIndex:1 }}>
      <div style={{ position:'absolute', right:18, top:'50%',
        transform:'translateY(-50%) rotate(-90deg)', transformOrigin:'center',
        fontFamily:'var(--font-mono)', fontSize:10, letterSpacing:'0.4em',
        color:'var(--fg-1)', opacity:0.22, whiteSpace:'nowrap', userSelect:'none' }}>
        EDITION №07 · BUILT IN OKC · EST. 2019
      </div>
    </div>
  );
}

function HeroShader({ tod }) {
  // Single dominant directional wash per TOD — replaces the previous 3-stop
  // multi-gradient soup. One light source, more editorial.
  const washes = {
    night:   'radial-gradient(ellipse 90% 70% at 78% 22%, rgba(122,168,255,0.28) 0%, transparent 60%)',
    sunrise: 'radial-gradient(ellipse 100% 75% at 82% 75%, rgba(255,200,87,0.34) 0%, transparent 62%)',
    day:     'radial-gradient(ellipse 95% 80% at 65% 28%, rgba(20,184,166,0.30) 0%, transparent 62%)',
    sunset:  'radial-gradient(ellipse 100% 75% at 18% 78%, rgba(255,122,61,0.34) 0%, transparent 62%)',
  };
  return (
    <div style={{ position:'absolute', inset:0, zIndex:0, overflow:'hidden' }}>
      {/* Base — TOD-aware sky scene canvas */}
      <div style={{ position:'absolute', inset:0, opacity:0.85 }}>
        <SkyScene/>
      </div>
      {/* Plains horizon — sense of place */}
      <HeroHorizon tod={tod}/>
      {/* Single dominant wash — anchors a clear light direction */}
      <div style={{ position:'absolute', inset:0, mixBlendMode:'screen',
        background:washes[tod]||washes.night, transition:'background 2.5s ease',
        pointerEvents:'none' }}/>

      {/* Edition mark only — no big "midwest" word, no state silhouette,
          no grid, no crosshair register marks. */}
      <HeroBackdropType/>

      {/* Soft film grain — kept, but quieter than before */}
      <div aria-hidden style={{ position:'absolute', inset:0, pointerEvents:'none',
        opacity:0.22, mixBlendMode:'overlay',
        backgroundImage:`url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='220' height='220'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 0  0 0 0 0 0  0 0 0 0 0  0 0 0 0.55 0'/></filter><rect width='100%25' height='100%25' filter='url(%23n)'/></svg>")`,
        backgroundSize:'220px 220px' }}/>

      {/* Slow horizontal scan line */}
      <div aria-hidden style={{ position:'absolute', left:0, right:0, height:1,
        background:'linear-gradient(90deg, transparent, color-mix(in oklab, var(--accent) 65%, transparent) 50%, transparent)',
        opacity:0.28, animation:'mwHeroScan 14s linear infinite', willChange:'transform' }}/>

      {/* Soft vignette — just enough to focus eye, not a heavy frame */}
      <div style={{ position:'absolute', inset:0, pointerEvents:'none',
        background:'radial-gradient(circle at 50% 45%, transparent 45%, color-mix(in oklab, var(--bg) 60%, transparent) 100%)' }}/>
    </div>
  );
}

function CornerMark({ corner }) {
  const pos = {
    nw: { top:24, left:24, borderTop:'1px solid var(--border-strong)', borderLeft:'1px solid var(--border-strong)' },
    ne: { top:24, right:24, borderTop:'1px solid var(--border-strong)', borderRight:'1px solid var(--border-strong)' },
    sw: { bottom:24, left:24, borderBottom:'1px solid var(--border-strong)', borderLeft:'1px solid var(--border-strong)' },
    se: { bottom:24, right:24, borderBottom:'1px solid var(--border-strong)', borderRight:'1px solid var(--border-strong)' },
  }[corner];
  return <div style={{ position:'absolute', width:14, height:14, opacity:0.45, zIndex:2, ...pos }}/>;
}

function TypedVerb({ mounted, words }) {
  const [wi, setWi] = useStHr(0);
  const [chars, setChars] = useStHr('');
  useEfHr(() => {
    if (!mounted) return;
    const word = words[wi]; let i = 0; setChars('');
    const timers = [];
    const type = setInterval(() => {
      i++; setChars(word.slice(0,i));
      if(i>=word.length){
        clearInterval(type);
        timers.push(setTimeout(()=>{
          let e=word.length;
          const er=setInterval(()=>{
            e--; setChars(word.slice(0,e));
            if(e<=0){
              clearInterval(er);
              timers.push(setTimeout(()=>setWi(w=>(w+1)%words.length),120));
            }
          },55);
          timers.push(er);
        },1900));
      }
    },75);
    timers.push(type);
    return () => { timers.forEach(t => { clearInterval(t); clearTimeout(t); }); };
  }, [wi, mounted]);
  // Reserve enough inline-width for the longest word so the line never reflows.
  const longest = words.reduce((a,b)=>a.length>=b.length?a:b, '');
  return (
    <span style={{
      color:'var(--accent)',
      display:'inline-block',
      whiteSpace:'nowrap',
      verticalAlign:'baseline',
      // Use ch units sized to the longest word + a little slack for the cursor
      minWidth: `${longest.length + 1}ch`,
    }}>
      {chars}
      <span style={{display:'inline-block',width:3,height:'0.82em',background:'var(--accent)',
        marginLeft:2,verticalAlign:'middle',animation:'mwBreathe 1s ease-in-out infinite'}}/>
    </span>
  );
}

function HeroLine({ children, delay = 0, mounted }) {
  return (
    <span style={{ display:'block',
      opacity: mounted?1:0, transform: mounted?'translateY(0)':'translateY(18px)',
      transition:`opacity .7s ${delay}ms var(--ease-out), transform .7s ${delay}ms var(--ease-out)` }}>
      {children}
    </span>
  );
}

function Hero({ tod }) {
  const [time, setTime] = useStHr(() => new Date());
  const [mounted, setMounted] = useStHr(false);
  const [stripScrolled, setStripScrolled] = useStHr(false);
  useEfHr(() => {
    const tick = setInterval(() => setTime(new Date()), 1000);
    const m = setTimeout(() => setMounted(true), 80);
    const fn = () => setStripScrolled(window.scrollY > 60);
    fn(); window.addEventListener('scroll', fn, {passive:true});
    return () => { clearInterval(tick); clearTimeout(m); window.removeEventListener('scroll', fn); };
  }, []);
  const hhmm = time.toLocaleTimeString('en-US', { hour12:false, timeZone:'America/Chicago' });

  return (
    <section id="top" style={{ position:'relative', minHeight:'100svh', borderBottom:'1px solid var(--border)', overflow:'clip', background:'var(--bg)' }}>
      <HeroShader tod={tod}/>
      <div aria-hidden style={{ position:'absolute', inset:0, pointerEvents:'none',
        background:'linear-gradient(180deg, color-mix(in oklab,var(--bg) 50%,transparent) 0%, transparent 22%, transparent 72%, color-mix(in oklab,var(--bg) 75%,transparent) 100%)' }}/>
      <div aria-hidden style={{ position:'absolute', inset:0, pointerEvents:'none',
        background:'linear-gradient(90deg, color-mix(in oklab,var(--bg) 52%,transparent) 0%, transparent 42%)' }}/>
      <div aria-hidden style={{ position:'absolute', inset:0, pointerEvents:'none',
        backgroundImage:'linear-gradient(to right, color-mix(in oklab,var(--fg) 5%,transparent) 1px, transparent 1px)',
        backgroundSize:'calc(100% / 12) 100%' }}/>
      <CornerMark corner="nw"/><CornerMark corner="ne"/>
      <CornerMark corner="sw"/><CornerMark corner="se"/>

      {/* Sub-strip. The .mw-strip class lets globals.css collapse the
          three-column layout into a single centered line below 640px,
          where the long flanking spans wrap into multi-line panels and
          eat ~20% of the viewport. Side spans carry .mw-strip-side so
          the same media query can hide them; the center carries
          .mw-strip-center so it re-centers when alone. Desktop layout
          (>=768px) is unchanged — the inline gridTemplateColumns wins
          there because the media query doesn't apply. */}
      <div className="mw-strip" style={{ position:'sticky', top:'var(--mw-nav-h,57px)', zIndex:40,
        borderBottom:'1px solid var(--border)',
        borderTop:'1px solid color-mix(in oklab,var(--border) 50%,transparent)',
        display:'grid', gridTemplateColumns:'1fr auto 1fr',
        padding: stripScrolled?'5px clamp(20px,4vw,40px)':'12px clamp(20px,4vw,40px)',
        gap:16, fontFamily:'var(--font-mono)', fontSize:stripScrolled?9:10, letterSpacing:'0.16em',
        color:'var(--fg-3)', textTransform:'uppercase',
        background:'color-mix(in oklab,var(--bg) 80%,transparent)',
        backdropFilter:'blur(14px)', WebkitBackdropFilter:'blur(14px)',
        transition:'padding .25s var(--ease-out), font-size .25s var(--ease-out)' }}>
        <span className="mw-strip-side">35.47°N · 97.52°W — OKLAHOMA STATE</span>
        <span className="mw-strip-center" style={{color:'var(--fg-1)',display:'inline-flex',alignItems:'center',gap:8}}>
          <span style={{width:stripScrolled?5:6,height:stripScrolled?5:6,background:'var(--accent)',
            boxShadow:'0 0 10px var(--accent)',animation:'mwBreathe 2s infinite',
            transition:'width .25s, height .25s'}}/>
          LIVE · {hhmm} CT · {tod.toUpperCase()}
        </span>
        <span className="mw-strip-side" style={{textAlign:'right'}}>SERVING OKC METRO &amp; BEYOND</span>
      </div>

      {/* Main content */}
      <div style={{ position:'relative', zIndex:2,
        padding:'clamp(72px,12vh,130px) clamp(20px,4vw,48px) clamp(72px,10vh,110px)',
        maxWidth:1440, margin:'0 auto' }}>
        <div className="mw-hero-grid" style={{
          display:'grid',
          gridTemplateColumns:'minmax(0,1fr)',
          gap:48, alignItems:'start' }}>

          {/* Left — headline */}
          <div style={{position:'relative',zIndex:1,minWidth:0}}>
            <div style={{ fontFamily:'var(--font-mono)', fontSize:11, letterSpacing:'0.14em', color:'var(--fg-2)',
              marginBottom:28, display:'flex', alignItems:'center', gap:12, flexWrap:'wrap',
              opacity:mounted?1:0, transform:mounted?'translateY(0)':'translateY(8px)',
              transition:'opacity .5s, transform .5s var(--ease-out)' }}>
              <span style={{width:8,height:8,background:'var(--accent)',boxShadow:'0 0 16px var(--accent)',animation:'mwBreathe 2.2s ease-in-out infinite'}}/>
              <span>OKLAHOMA'S WEBSITE STUDIO</span>
              <span style={{opacity:.4}}>|</span>
              <span>{(() => {
                /* Auto-derive "BOOKING <SEASON> <YEAR>" from the
                   studio's local time (America/Chicago). Lead by one
                   month so the label advertises the NEXT season, not
                   the one we're already in. May 3 → June → SUMMER.
                   Dec → next Jan → next-year WINTER.

                   Using Intl.DateTimeFormat with an explicit timezone
                   keeps the label deterministic across visitors —
                   without it, a viewer in Asia or Europe near a
                   month boundary could see a different season or year
                   than someone in Oklahoma. */
                const fmt = new Intl.DateTimeFormat('en-US', {
                  timeZone: 'America/Chicago',
                  month: 'numeric',
                  year: 'numeric',
                });
                const parts = fmt.formatToParts(new Date());
                const monthPart = parts.find((p) => p.type === 'month');
                const yearPart = parts.find((p) => p.type === 'year');
                const m0 = monthPart ? Number(monthPart.value) - 1 : 0;
                const y0 = yearPart ? Number(yearPart.value) : new Date().getFullYear();
                let m = m0 + 1;
                let y = y0;
                if (m > 11) { m = 0; y += 1; }
                const season = m <= 1 ? 'WINTER'
                  : m <= 4 ? 'SPRING'
                  : m <= 7 ? 'SUMMER'
                  : m <= 10 ? 'FALL'
                  : 'WINTER';
                return `BOOKING ${season} ${y}`;
              })()}</span>
            </div>
            <h1 style={{ margin:0, fontFamily:'var(--font-display)',
              fontSize:'clamp(40px,11vw,160px)', lineHeight:0.82,
              letterSpacing:'-0.05em', fontWeight:500, color:'var(--fg-1)', textWrap:'balance',
              overflow:'visible', overflowWrap:'break-word' }}>
              <HeroLine delay={100} mounted={mounted}>
                A website <em style={{fontStyle:'italic',fontFamily:'var(--font-editorial)',fontWeight:400,color:'var(--accent)'}}>your customers</em>
              </HeroLine>
              <HeroLine delay={280} mounted={mounted}>
                <span>
                  actually{' '}
                  <TypedVerb mounted={mounted} words={['find','enjoy','trust','remember','call']}/>
                </span>
              </HeroLine>
            </h1>
            <p style={{
              margin: '20px 0 0',
              fontSize: 'clamp(13px, 1.4vw, 16px)',
              color: 'var(--fg-2)',
              maxWidth: 720,
              lineHeight: 1.5,
            }}>
              Oklahoma's website studio. We build custom websites for service businesses,
              retailers, and real estate professionals in OKC and across the country —
              no templates, no Squarespace, no platform tax.
            </p>
            <div style={{ display:'grid', gridTemplateColumns:'1fr auto', gap:32, marginTop:48, alignItems:'end',
              opacity:mounted?1:0, transform:mounted?'translateY(0)':'translateY(20px)',
              transition:'opacity .6s 0.5s, transform .6s var(--ease-out) 0.5s' }} className="mw-hero-bottom">
              <div style={{maxWidth:560}}>
                <p style={{fontSize:'clamp(15px,1.7vw,19px)',lineHeight:1.5,color:'var(--fg-2)',margin:'0 0 12px',textWrap:'pretty'}}>
                  Lawn care, hydraulic shops, restaurants, real estate — whatever your trade, we hand-build a website in Oklahoma City that gets you found on Google and converts visitors into phone calls. No templates. No Squarespace. Code we write, a site you own.
                </p>
                <p style={{fontSize:14,lineHeight:1.55,color:'var(--fg-3)',margin:0}}>
                  Show up on Google. Look good on every device. Want a smart helper that talks to customers 24/7? We can wire that in too.
                </p>
              </div>
              <div style={{display:'flex',gap:10,flexWrap:'wrap'}}>
                <MagButton variant="primary" size="lg" href="#contact">Get a free quote</MagButton>
                <MagButton variant="ghost" size="lg" href="#work" noArrow>See our work</MagButton>
              </div>
            </div>
          </div>

          {/* Right — stat cards (removed; can be reintroduced later) */}
        </div>
      </div>
    </section>
  );
}

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