/* global React */
const { useState, useEffect, useRef } = React;

// ============ NAV ============
function Nav() {
  return (
    <nav className="nav">
      <div className="wrap nav__inner">
        <a href="#top" className="nav__logo">PRIME<span className="dot" /></a>
        <div className="nav__links">
          <a href="#cases">שימושים</a>
          <a href="#specs">מפרט</a>
          <a href="#calc">מחשבון</a>
          <a href="#where">איפה לראות</a>
          <a href="#faq">שאלות</a>
          <a href="#contact">צור קשר</a>
        </div>
        <div className="nav__cta">
          <a href="#contact" className="btn btn--primary" style={{padding: "12px 20px", fontSize: 14}}>השאר פרטים</a>
        </div>
      </div>
    </nav>
  );
}

// ============ HERO with sound visualizer ============
function Hero() {
  const [time, setTime] = useState(0);
  useEffect(() => {
    let raf;
    let t0 = performance.now();
    const tick = (now) => {
      setTime((now - t0) / 1000);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <section className="hero" id="top" data-screen-label="01 Hero">
      <div className="wrap hero__grid">
        <div className="hero__copy">
          <span className="eyebrow">LOOK SHARP. SOUND PURE.</span>
          <h1>
            <span className="accent">LOOK</span> SHARP.<br/>
            SOUND <em style={{fontStyle:'italic',color:'var(--copper)'}}>PURE</em>.
          </h1>
          <p className="lead">
            פאנלים אקוסטיים בגובה 2.80 מ׳ — בלי חיבורים נראים, בלי פשרות.
            סופגים את הרעש, מחזירים את הסאונד, והופכים את הקיר שלך לאובייקט עיצוב.
          </p>
          <div className="hero__ctas">
            <a href="#contact" className="btn btn--primary">
              <span>קבל ייעוץ חינם</span>
              <span className="arrow">←</span>
            </a>
            <a href="#calc" className="btn btn--ghost">חשב לחדר שלך</a>
          </div>
          <div className="hero__stats">
            <div className="hero__stat">
              <div className="num">0.80<small>NRC</small></div>
              <div className="label">ספיגת רעש</div>
            </div>
            <div className="hero__stat">
              <div className="num">GRS<small>V4.0</small></div>
              <div className="label">תקן ממוחזר</div>
            </div>
            <div className="hero__stat">
              <div className="num">7<small>days</small></div>
              <div className="label">ייצור והתקנה</div>
            </div>
          </div>
        </div>
        <div className="hero__viz">
          <SoundWaveViz t={time} />
        </div>
      </div>
    </section>
  );
}

// Sophisticated multi-layer acoustic visualization
function SoundWaveViz({ t }) {
  const W = 600, H = 600;
  const panelX = 60, panelY = 60, panelW = 180, panelH = 480;
  const panelRight = panelX + panelW;
  const cy = H/2;
  const sourceX = W - 70;

  // ====== Multi-frequency continuous wavefronts ======
  // Three frequency bands traveling right→left, attenuating near panel.
  const FREQS = [
    { freq: 0.6, amp: 28, color: 'var(--copper)', speed: 1.0, weight: 1.4 },  // low
    { freq: 1.2, amp: 18, color: '#ff9d6e',       speed: 1.3, weight: 1.0 },  // mid
    { freq: 2.4, amp: 10, color: 'var(--volt)',   speed: 1.6, weight: 0.8 },  // high
  ];
  // Build continuous waveform paths for each frequency (sine traveling)
  const wavePaths = FREQS.map((F, fi) => {
    const pts = [];
    for (let x = sourceX; x >= panelRight - 10; x -= 4) {
      const distFromSource = sourceX - x;
      // attenuation envelope: stays full to ~50px before panel, then collapses INTO panel
      const distToPanel = x - panelRight;
      const env = distToPanel > 60
        ? 1
        : Math.max(0, distToPanel / 60);
      const phase = distFromSource * 0.04 * F.freq - t * 2.4 * F.speed;
      const y = cy + Math.sin(phase) * F.amp * env;
      pts.push([x, y]);
    }
    return { ...F, pts, fi };
  });

  // ====== Particle stream — energy flowing into the panel ======
  // Each particle has a stable phase offset so motion is continuous.
  const PARTICLE_COUNT = 22;
  const particles = [];
  for (let i = 0; i < PARTICLE_COUNT; i++) {
    const seed = i * 7919; // deterministic
    const phase = ((t * 0.18 + i / PARTICLE_COUNT) % 1);
    const startX = sourceX;
    const endX = panelRight + 4;
    const x = startX - phase * (startX - endX);
    // sinusoidal vertical drift along the path, narrowing toward panel
    const yOffset = Math.sin(phase * Math.PI * 3 + i * 0.7) * (1 - phase) * 80;
    const y = cy + yOffset + ((seed % 100) - 50) * (1 - phase) * 0.3;
    const size = 0.8 + (1 - phase) * 1.4;
    const opacity = phase < 0.05 ? phase / 0.05 : phase > 0.92 ? (1 - phase) / 0.08 : 1;
    particles.push({ x, y, size, opacity, key: i });
  }

  // ====== Spectrum analyzer inside panel (responds to wave activity) ======
  const SPECTRUM_BINS = 18;
  const spectrum = [];
  for (let i = 0; i < SPECTRUM_BINS; i++) {
    // each bin oscillates with a unique frequency to mimic absorbed energy
    const f1 = Math.sin(t * 4 + i * 0.45);
    const f2 = Math.sin(t * 2.3 + i * 0.7 + 1.1);
    const f3 = Math.sin(t * 7 + i * 0.2);
    const v = (f1 * 0.6 + f2 * 0.3 + f3 * 0.1) * 0.5 + 0.5; // 0..1
    // taper: low bins stronger than high
    const taper = 1 - (i / SPECTRUM_BINS) * 0.5;
    spectrum.push(v * taper);
  }

  // ====== Live dB readouts ======
  // before-panel level: high (drives the source pulse)
  const sourcePulse = 0.7 + 0.3 * Math.sin(t * 6) * Math.sin(t * 2.7);
  const dbIn = 78 + Math.round(sourcePulse * 7);
  const dbOut = 32 + Math.round(Math.sin(t * 1.5) * 4);
  const reduction = dbIn - dbOut;

  // ====== Frequency response curve (plotted along bottom) ======
  const responsePts = [];
  for (let i = 0; i < 60; i++) {
    const x = panelRight + 30 + i * 5;
    const freqProgress = i / 60;
    // simulated NRC curve — peak absorption mid-band
    const absorption = 0.3 + Math.sin(freqProgress * Math.PI) * 0.55 + Math.sin(t * 1.2 + freqProgress * 6) * 0.04;
    const y = H - 60 - absorption * 50;
    responsePts.push([x, y]);
  }
  const responsePath = `M ${responsePts.map(p => p.join(',')).join(' L ')}`;

  // panel perforations
  const dots = [];
  for (let r = 0; r < 19; r++) {
    for (let c = 0; c < 9; c++) {
      // pulse opacity based on local spectrum
      const binIdx = Math.floor((r / 19) * SPECTRUM_BINS);
      const pulse = spectrum[binIdx] || 0;
      dots.push({ x: panelX + 16 + c*16, y: panelY + 18 + r*24, r: 1.4, opacity: 0.3 + pulse * 0.5 });
    }
  }

  return (
    <svg viewBox={`0 0 ${W} ${H}`} style={{width:'100%',height:'100%',overflow:'visible'}}>
      <defs>
        <linearGradient id="panelGrad" x1="0" x2="1">
          <stop offset="0" stopColor="#0f0f0f" />
          <stop offset="0.5" stopColor="#1a1a1a" />
          <stop offset="1" stopColor="#262626" />
        </linearGradient>
        <radialGradient id="haloGlow" cx="0.5" cy="0.5" r="0.5">
          <stop offset="0" stopColor="var(--volt)" stopOpacity="0.35" />
          <stop offset="0.6" stopColor="var(--volt)" stopOpacity="0.05" />
          <stop offset="1" stopColor="var(--volt)" stopOpacity="0" />
        </radialGradient>
        <radialGradient id="sourceGlow" cx="0.5" cy="0.5" r="0.5">
          <stop offset="0" stopColor="var(--copper)" stopOpacity="0.6" />
          <stop offset="1" stopColor="var(--copper)" stopOpacity="0" />
        </radialGradient>
        <linearGradient id="waveFade" x1="0" y1="0" x2="1" y2="0">
          <stop offset="0" stopColor="var(--volt)" stopOpacity="1"/>
          <stop offset="1" stopColor="var(--volt)" stopOpacity="0.2"/>
        </linearGradient>
        <mask id="panelMask">
          <rect x={panelX} y={panelY} width={panelW} height={panelH} rx="20" fill="white"/>
        </mask>
        <filter id="softblur"><feGaussianBlur stdDeviation="1.2"/></filter>
      </defs>

      {/* Halo behind panel */}
      <ellipse cx={panelX + panelW/2} cy={cy} rx="220" ry="280" fill="url(#haloGlow)" />

      {/* === Frequency bands (continuous wavefronts) === */}
      {wavePaths.map(W => {
        const path = `M ${W.pts.map(p => p.join(',')).join(' L ')}`;
        return (
          <g key={W.fi}>
            <path d={path} fill="none" stroke={W.color} strokeWidth={W.weight} opacity="0.9" />
            <path d={path} fill="none" stroke={W.color} strokeWidth={W.weight + 2} opacity="0.18" filter="url(#softblur)" />
          </g>
        );
      })}

      {/* === Particle stream === */}
      {particles.map(p => (
        <circle key={p.key} cx={p.x} cy={p.y} r={p.size} fill="var(--volt)" opacity={p.opacity * 0.85} />
      ))}

      {/* === Source === */}
      <g>
        <circle cx={sourceX} cy={cy} r={28 + sourcePulse * 14} fill="url(#sourceGlow)" />
        <circle cx={sourceX} cy={cy} r={6 + sourcePulse * 2} fill="var(--copper)" />
        <circle cx={sourceX} cy={cy} r="14" fill="none" stroke="var(--copper)" strokeWidth="0.6" opacity="0.4" />
      </g>

      {/* Source dB readout */}
      <g transform={`translate(${sourceX - 80}, ${cy - 70})`}>
        <text fontFamily="var(--font-mono)" fontSize="9" fill="#5a5a56" letterSpacing="2">INPUT · 250Hz</text>
        <text y="22" fontFamily="var(--font-display)" fontSize="32" fill="var(--copper)">{dbIn}<tspan fontSize="11" fill="#5a5a56" dx="3">dB</tspan></text>
      </g>

      {/* === Panel === */}
      <g>
        <rect x={panelX} y={panelY} width={panelW} height={panelH} rx="20" fill="url(#panelGrad)" stroke="#2a2a2a" />
        {/* slat texture */}
        {Array.from({length: 11}).map((_, i) => (
          <line key={`s-${i}`} x1={panelX + 12 + i*16} y1={panelY + 12} x2={panelX + 12 + i*16} y2={panelY + panelH - 12} stroke="#0a0a0a" strokeWidth="0.5" opacity="0.6"/>
        ))}
        {/* perforations with reactive opacity */}
        {dots.map((d,i) => <circle key={i} cx={d.x} cy={d.y} r={d.r} fill="var(--volt)" opacity={d.opacity * 0.18} />)}

        {/* === Spectrum analyzer inside panel === */}
        <g mask="url(#panelMask)">
          <g transform={`translate(${panelX + 22}, ${cy})`}>
            {spectrum.map((v, i) => {
              const h = 8 + v * 110;
              const y = -h/2;
              const isHigh = v > 0.7;
              return (
                <g key={i}>
                  <rect x={i * 7.6} y={y} width="3.4" height={h} rx="1.7" fill={isHigh ? "var(--volt)" : "var(--volt)"} opacity={0.4 + v * 0.5} />
                  <rect x={i * 7.6} y={y} width="3.4" height="3" rx="1.5" fill="var(--volt)" />
                  <rect x={i * 7.6} y={y + h - 3} width="3.4" height="3" rx="1.5" fill="var(--volt)" />
                </g>
              );
            })}
          </g>
          {/* center line */}
          <line x1={panelX + 22} y1={cy} x2={panelX + panelW - 22} y2={cy} stroke="var(--volt)" strokeWidth="0.4" opacity="0.3" strokeDasharray="2 3"/>
        </g>

        {/* Panel labels */}
        <g transform={`translate(${panelX + 16}, ${panelY + panelH - 18})`}>
          <text fontFamily="var(--font-mono)" fontSize="9" fill="#5a5a56" letterSpacing="1.5">PRIME LINE · 280×120 · NRC 0.80</text>
        </g>
        <g transform={`translate(${panelX + panelW - 70}, ${panelY + 24})`}>
          <circle cx="0" cy="-3" r="3" fill="var(--volt)">
            <animate attributeName="opacity" values="1;0.3;1" dur="1.4s" repeatCount="indefinite"/>
          </circle>
          <text x="8" fontFamily="var(--font-mono)" fontSize="9" fill="var(--volt)" letterSpacing="1.5">REC</text>
        </g>
      </g>

      {/* === OUTPUT readout (left of panel) === */}
      <g transform={`translate(8, ${cy - 70})`}>
        <text fontFamily="var(--font-mono)" fontSize="9" fill="#5a5a56" letterSpacing="2">OUTPUT</text>
        <text y="22" fontFamily="var(--font-display)" fontSize="32" fill="var(--volt)">{dbOut}<tspan fontSize="11" fill="#5a5a56" dx="3">dB</tspan></text>
        <text y="40" fontFamily="var(--font-mono)" fontSize="9" fill="var(--volt)" letterSpacing="2">−{reduction} dB</text>
      </g>

      {/* === Frequency response curve === */}
      <g>
        <text x={panelRight + 30} y={H - 130} fontFamily="var(--font-mono)" fontSize="9" fill="#5a5a56" letterSpacing="2">ABSORPTION · 125Hz–4kHz</text>
        <line x1={panelRight + 30} y1={H - 50} x2={panelRight + 30 + 60*5} y2={H - 50} stroke="#2a2a2a" strokeWidth="0.5"/>
        <line x1={panelRight + 30} y1={H - 110} x2={panelRight + 30} y2={H - 50} stroke="#2a2a2a" strokeWidth="0.5"/>
        <path d={responsePath} fill="none" stroke="var(--volt)" strokeWidth="1.5"/>
        {/* fill under curve */}
        <path d={`${responsePath} L ${panelRight + 30 + 59*5},${H-50} L ${panelRight + 30},${H-50} Z`} fill="var(--volt)" opacity="0.08"/>
        {/* axis labels */}
        <text x={panelRight + 30} y={H - 38} fontFamily="var(--font-mono)" fontSize="8" fill="#5a5a56">125</text>
        <text x={panelRight + 30 + 59*5} y={H - 38} fontFamily="var(--font-mono)" fontSize="8" fill="#5a5a56" textAnchor="end">4kHz</text>
        <text x={panelRight + 25} y={H - 105} fontFamily="var(--font-mono)" fontSize="8" fill="#5a5a56" textAnchor="end">1.0</text>
        <text x={panelRight + 25} y={H - 50} fontFamily="var(--font-mono)" fontSize="8" fill="#5a5a56" textAnchor="end">0</text>
      </g>

      {/* Top-right corner: frequency band legend */}
      <g transform={`translate(${W - 140}, 20)`}>
        <text fontFamily="var(--font-mono)" fontSize="9" fill="#5a5a56" letterSpacing="2">FREQUENCY BANDS</text>
        {FREQS.map((F, i) => (
          <g key={i} transform={`translate(0, ${16 + i*14})`}>
            <line x1="0" y1="0" x2="20" y2="0" stroke={F.color} strokeWidth={F.weight}/>
            <text x="28" y="3" fontFamily="var(--font-mono)" fontSize="8" fill="#8a8a86">{['LOW · 125Hz', 'MID · 1kHz', 'HIGH · 4kHz'][i]}</text>
          </g>
        ))}
      </g>
    </svg>
  );
}

window.Nav = Nav;
window.Hero = Hero;
