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

/* ==========================================================
   SECTION: Two wavelengths — SVG cross-section + spectrum + waveform
   ========================================================== */
function WavelengthsSection() {
  const { t } = useApp();
  const copy = t.wavelengths;
  const [wl, setWl] = useState(850); // 630 or 850
  const ref = useReveal();

  const is630 = wl === 630;
  // Realistic penetration depth as fraction of visible 20mm range:
  // 630nm → ~1mm (stops in upper dermis) = 0.20
  // 850nm → ~8-10mm (deep into muscle)   = 0.78
  const depth = is630 ? 0.22 : 0.80;

  return (
    <section className="lx-section-dark" id="science" ref={ref} data-screen-label="Wavelengths">
      {/* ambient orbs */}
      <div aria-hidden="true" style={{
        position:"absolute", inset:0, pointerEvents:"none", overflow:"hidden", zIndex:0,
      }}>
        <div style={{position:"absolute", left:"-10%", top:"20%", width:420, height:420, borderRadius:"50%",
          background:"radial-gradient(circle, rgba(229,9,20,0.18) 0%, transparent 60%)", filter:"blur(60px)",
          animation:"lxBreath 8s ease-in-out infinite"}}/>
        <div style={{position:"absolute", right:"-15%", bottom:"10%", width:520, height:520, borderRadius:"50%",
          background:"radial-gradient(circle, rgba(196,16,32,0.14) 0%, transparent 60%)", filter:"blur(80px)",
          animation:"lxBreath 10s ease-in-out 2s infinite"}}/>
      </div>

      <div className="lx-container lx-reveal" style={{position:"relative", zIndex:1}}>
        <div style={{textAlign:"center", marginBottom:72}}>
          <div className="lx-eyebrow on-dark" style={{color:"#ff4a57"}}>{copy.eyebrow}</div>
          <h2 className="lx-section-title lx-mt-16" style={{whiteSpace:"pre-line"}}>{copy.title}</h2>
          <p className="lx-subtitle on-dark lx-mt-24" style={{maxWidth:720, margin:"24px auto 0"}}>{copy.subtitle}</p>
        </div>

        <div className="wl-grid">
          {/* LEFT — SKIN CROSS-SECTION */}
          <div className="wl-xsection">
            <SkinCrossSection wl={wl} depth={depth} layerLabels={copy.layers}/>
            {/* live depth badge */}
            <div className="wl-depth-badge">
              <span className="wl-depth-label">{copy.scrubLabel}</span>
              <span className="wl-depth-value">
                <span key={wl} className="wl-depth-num">{is630 ? "~1" : "~8"}</span>
                <span className="wl-depth-unit">mm</span>
              </span>
            </div>
          </div>

          {/* RIGHT — CONTROL PANEL */}
          <div className="wl-panel">
            {/* Toggle */}
            <div className="wl-toggle">
              {[
                {v:630, t:copy.redTitle, short:"630 nm"},
                {v:850, t:copy.irTitle, short:"850 nm"},
              ].map(({v, t:lbl, short}) => (
                <button key={v} onClick={() => setWl(v)}
                  className={`wl-toggle-btn ${wl === v ? "is-active" : ""}`}>
                  <span className="wl-toggle-dot"/>
                  <span className="wl-toggle-short">{short}</span>
                  <span className="wl-toggle-full">{lbl}</span>
                </button>
              ))}
              <div className="wl-toggle-glider" style={{transform: `translateX(${is630 ? 0 : 100}%)`}}/>
            </div>

            {/* Big number */}
            <div className="wl-number">
              <div key={wl} className="wl-number-main">
                {wl}<span className="wl-number-unit">nm</span>
              </div>
              <p className="wl-number-desc">{is630 ? copy.redDesc : copy.irDesc}</p>
            </div>

            {/* Spectrum bar with animated marker */}
            <SpectrumBar wl={wl}/>

            {/* Waveform oscilloscope */}
            <WaveformDisplay wl={wl}/>
          </div>
        </div>
      </div>

      <style>{`
        /* === WAVELENGTHS SECTION === */
        .wl-grid {
          display: grid;
          grid-template-columns: 1.1fr 1fr;
          gap: 48px;
          align-items: stretch;
        }
        .wl-xsection {
          position: relative;
          aspect-ratio: 3 / 4;
          border-radius: 22px;
          overflow: hidden;
          background: #050303;
          border: 1px solid rgba(255,255,255,0.06);
          box-shadow: 0 30px 80px rgba(0,0,0,0.6), inset 0 0 40px rgba(0,0,0,0.5);
        }
        .wl-depth-badge {
          position: absolute;
          left: 16px; bottom: 16px;
          display: flex; flex-direction: column; gap: 2px;
          padding: 10px 14px;
          background: rgba(10,4,6,0.72);
          backdrop-filter: blur(12px);
          -webkit-backdrop-filter: blur(12px);
          border: 1px solid rgba(255,255,255,0.08);
          border-radius: 10px;
        }
        .wl-depth-label {
          font-size: 10px; letter-spacing: 0.1em;
          text-transform: uppercase;
          color: rgba(255,255,255,0.45);
        }
        .wl-depth-value {
          display: flex; align-items: baseline; gap: 4px;
          font-variant-numeric: tabular-nums;
        }
        .wl-depth-num {
          display: inline-block;
          font-size: 26px; font-weight: 500;
          color: #fff;
          animation: lxNumberPop 500ms cubic-bezier(0.28,0,0.22,1);
        }
        .wl-depth-unit { font-size: 13px; color: rgba(255,255,255,0.55); }

        .wl-panel { display: flex; flex-direction: column; gap: 28px; }

        /* toggle */
        .wl-toggle {
          position: relative;
          display: grid;
          grid-template-columns: 1fr 1fr;
          padding: 4px;
          background: rgba(255,255,255,0.05);
          border: 1px solid rgba(255,255,255,0.08);
          border-radius: 14px;
          overflow: hidden;
        }
        .wl-toggle-glider {
          position: absolute;
          left: 4px; top: 4px; bottom: 4px;
          width: calc(50% - 4px);
          background: linear-gradient(135deg, rgba(229,9,20,0.28), rgba(139,26,26,0.35));
          border: 1px solid rgba(255,75,87,0.4);
          border-radius: 11px;
          transition: transform 600ms cubic-bezier(0.28,0,0.22,1);
          box-shadow: 0 0 20px rgba(229,9,20,0.35);
          pointer-events: none;
        }
        .wl-toggle-btn {
          position: relative; z-index: 1;
          display: flex; align-items: center; gap: 10px;
          padding: 14px 16px;
          background: transparent; border: 0; cursor: pointer;
          color: rgba(255,255,255,0.55);
          font-family: inherit; font-size: 14px; font-weight: 500;
          letter-spacing: -0.01em; text-align: left;
          transition: color 400ms;
        }
        .wl-toggle-btn.is-active { color: #fff; }
        .wl-toggle-btn:hover:not(.is-active) { color: rgba(255,255,255,0.8); }
        .wl-toggle-dot {
          width: 8px; height: 8px; border-radius: 50%;
          background: rgba(255,255,255,0.25);
          transition: all 400ms;
        }
        .wl-toggle-btn.is-active .wl-toggle-dot {
          background: #ff4a57;
          box-shadow: 0 0 10px 2px rgba(255,74,87,0.8);
        }
        .wl-toggle-full { display: inline; }
        .wl-toggle-short { display: none; font-weight: 600; }

        /* big number */
        .wl-number-main {
          font-size: clamp(62px, 8vw, 96px);
          font-weight: 200;
          letter-spacing: -0.04em;
          line-height: 1;
          color: #fff;
          background: linear-gradient(180deg, #fff 0%, #ff8390 100%);
          -webkit-background-clip: text;
          background-clip: text;
          -webkit-text-fill-color: transparent;
          animation: lxNumberPop 600ms cubic-bezier(0.28,0,0.22,1);
          text-shadow: 0 0 60px rgba(255,74,87,0.3);
        }
        .wl-number-unit { font-size: 0.42em; opacity: 0.5; font-weight: 300; margin-left: 6px; }
        .wl-number-desc {
          margin-top: 14px; max-width: 420px;
          font-size: 15px; line-height: 1.5;
          color: rgba(255,255,255,0.7);
        }

        /* responsive */
        @media (max-width: 900px) {
          .wl-grid { grid-template-columns: 1fr; gap: 36px; }
          .wl-xsection { aspect-ratio: 4 / 5; max-width: 560px; margin: 0 auto; width: 100%; }
        }
        @media (max-width: 520px) {
          .wl-panel { gap: 22px; }
          .wl-toggle-full { display: none; }
          .wl-toggle-short { display: inline; }
          .wl-toggle-btn { padding: 12px 12px; font-size: 13px; }
          .wl-xsection { aspect-ratio: 3 / 4; border-radius: 18px; }
          .wl-depth-badge { padding: 8px 12px; }
          .wl-depth-num { font-size: 22px; }
        }

        /* keyframes */
        @keyframes lxNumberPop {
          0%   { opacity: 0; transform: translateY(12px) scale(0.92); filter: blur(6px); }
          60%  { opacity: 1; filter: blur(0); }
          100% { opacity: 1; transform: translateY(0) scale(1); filter: blur(0); }
        }
        @keyframes lxPhotonDrop {
          0%   { opacity: 0; transform: translateY(-40%) scaleY(0.2); }
          30%  { opacity: 1; }
          80%  { opacity: 0.9; }
          100% { opacity: 0; transform: translateY(0) scaleY(1); }
        }
        @keyframes lxDiodeGlow {
          0%, 100% { opacity: 0.55; transform: scale(1); }
          50%      { opacity: 1;    transform: scale(1.15); }
        }
        @keyframes lxMarkerPulse {
          0%, 100% { transform: translate(-50%,-50%) scale(1);   opacity: 0.9; }
          50%      { transform: translate(-50%,-50%) scale(1.35); opacity: 0.55; }
        }
        @keyframes lxDigitShift {
          from { opacity: 0; transform: translateY(8px); }
          to   { opacity: 1; transform: translateY(0); }
        }
        @keyframes lxScanLine {
          0%   { transform: translateY(-100%); }
          100% { transform: translateY(100%); }
        }
      `}</style>
    </section>
  );
}

/* ------------- SVG skin cross-section ------------- */
function SkinCrossSection({ wl, depth, layerLabels }) {
  const is630 = wl === 630;

  // Panel band: y 0–70.  Skin zones 70–780, label zone 780–800.
  const panelH = 70;
  const skinStart = panelH;
  const skinEnd = 780;
  const skinH = skinEnd - skinStart;  // 710

  // Layers scaled by anatomical proportion (not 1:1 — compressed for readability):
  // Naskórek 4%, Skóra wł. 22%, Podskórna 28%, Mięśnie 32%, Stawy 14%
  const proportions = [0.04, 0.22, 0.28, 0.32, 0.14];
  const layers = [];
  let acc = skinStart;
  const palettes = [
    ["#f0d4c0", "#d8a898"],   // naskórek
    ["#c89685", "#8a5e50"],   // skóra właściwa
    ["#e0c090", "#b88860"],   // podskórna (fat)
    ["#8a3a28", "#521c12"],   // mięśnie
    ["#d8c2a2", "#8c7258"],   // stawy (bone/cartilage)
  ];
  const mmLabels = ["0.1 mm", "1.5 mm", "5 mm", "15 mm", "30 mm+"];
  for (let i=0; i<5; i++) {
    const h = proportions[i] * skinH;
    layers.push({
      name: layerLabels[i],
      y1: acc, y2: acc + h,
      c1: palettes[i][0], c2: palettes[i][1],
      mm: mmLabels[i],
    });
    acc += h;
  }

  const beamEndY = skinStart + depth * skinH;
  const beamColor = is630 ? "#ff3850" : "#c41528";
  const beamCore  = is630 ? "#ff6b78" : "#ee2838";
  const haloColor = is630 ? "#ff4a57" : "#c41020";

  // depth ruler — labeled in mm, mapped to the viewBox
  const rulerMarks = [
    { mm: "0",   y: skinStart },
    { mm: "1",   y: skinStart + 0.04 * skinH },
    { mm: "3",   y: skinStart + 0.18 * skinH },
    { mm: "8",   y: skinStart + 0.40 * skinH },
    { mm: "20",  y: skinStart + 0.75 * skinH },
    { mm: "50+", y: skinEnd },
  ];

  const nbBeams = 7;
  const beamXs = [...Array(nbBeams)].map((_, i) => 96 + i * 68);

  // cell particles: 630 in upper zones, 850 in muscle depth
  const particles = is630
    ? [...Array(20)].map((_, i) => ({
        x: 70 + (i * 29) % 480,
        y: skinStart + 0.06 * skinH + (i * 11) % (0.18 * skinH),
        r: 1.5 + (i % 3) * 0.6,
        d: (i % 6) * 0.12,
        color: "#ffc694",
      }))
    : [...Array(26)].map((_, i) => ({
        x: 60 + (i * 23) % 500,
        y: skinStart + 0.52 * skinH + (i * 13) % (0.22 * skinH),
        r: 2 + (i % 3) * 0.8,
        d: (i % 5) * 0.14,
        color: "#ffa070",
      }));

  return (
    <svg viewBox="0 0 600 800" preserveAspectRatio="xMidYMid slice"
      style={{position:"absolute", inset:0, width:"100%", height:"100%", display:"block"}}>
      <defs>
        {layers.map((l, i) => (
          <linearGradient key={i} id={`lxLayer${i}`} x1="0" x2="0" y1="0" y2="1">
            <stop offset="0%" stopColor={l.c1} stopOpacity="0.92"/>
            <stop offset="100%" stopColor={l.c2} stopOpacity="0.95"/>
          </linearGradient>
        ))}
        <linearGradient id="lxBeamGrad" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0%"  stopColor={beamCore}  stopOpacity="1"/>
          <stop offset="50%" stopColor={beamColor} stopOpacity="0.55"/>
          <stop offset="100%" stopColor={beamColor} stopOpacity="0"/>
        </linearGradient>
        <radialGradient id="lxPanelGlow" cx="0.5" cy="1" r="0.7">
          <stop offset="0%" stopColor={beamCore} stopOpacity="0.9"/>
          <stop offset="60%" stopColor={beamColor} stopOpacity="0.25"/>
          <stop offset="100%" stopColor={beamColor} stopOpacity="0"/>
        </radialGradient>
        <radialGradient id="lxCellGlow" cx="0.5" cy="0.5" r="0.5">
          <stop offset="0%" stopColor="#fff" stopOpacity="0.9"/>
          <stop offset="60%" stopColor={haloColor} stopOpacity="0.5"/>
          <stop offset="100%" stopColor={haloColor} stopOpacity="0"/>
        </radialGradient>
        <filter id="lxBlur4"><feGaussianBlur stdDeviation="3"/></filter>
        <filter id="lxBlur8"><feGaussianBlur stdDeviation="6"/></filter>
      </defs>

      {/* Background depth gradient — very dark skin tone beyond layers */}
      <rect x="0" y="0" width="600" height="800" fill="#050303"/>

      {/* LED panel at top */}
      <g>
        <rect x="40" y="8" width="520" height="56" rx="20" fill="#0c0507" stroke="rgba(255,255,255,0.08)" strokeWidth="1"/>
        <rect x="40" y="8" width="520" height="56" rx="20" fill="url(#lxPanelGlow)" opacity="0.8"/>
        {/* diode row */}
        {[...Array(9)].map((_, i) => {
          const x = 80 + i * 55;
          return (
            <g key={i}>
              <circle cx={x} cy={36} r="10" fill={haloColor} opacity="0.18"
                style={{animation:`lxDiodeGlow 1.8s ease-in-out ${i*0.1}s infinite`, transformOrigin:`${x}px 36px`}}/>
              <circle cx={x} cy={36} r="4.5" fill={beamCore}
                style={{animation:`lxDiodeGlow 1.8s ease-in-out ${i*0.1}s infinite`, transformOrigin:`${x}px 36px`}}/>
            </g>
          );
        })}
        {/* panel highlight */}
        <rect x="50" y="14" width="500" height="6" rx="3" fill="rgba(255,255,255,0.08)"/>
      </g>

      {/* Skin layers */}
      {layers.map((l, i) => (
        <g key={i}>
          <rect x="0" y={l.y1} width="600" height={l.y2 - l.y1} fill={`url(#lxLayer${i})`}/>
          {/* subtle texture bands */}
          {i === 1 && [...Array(8)].map((_, k) => (
            <line key={k} x1="0" x2="600" y1={l.y1 + (k+1)*(l.y2-l.y1)/9}
              y2={l.y1 + (k+1)*(l.y2-l.y1)/9 + 2}
              stroke="rgba(0,0,0,0.06)" strokeWidth="2"/>
          ))}
          {i === 3 && [...Array(6)].map((_, k) => (
            <line key={k} x1="0" x2="600" y1={l.y1 + (k+1)*(l.y2-l.y1)/7}
              y2={l.y1 + (k+1)*(l.y2-l.y1)/7}
              stroke="rgba(0,0,0,0.12)" strokeWidth="1"/>
          ))}
          {/* boundary */}
          <line x1="0" x2="600" y1={l.y1} y2={l.y1}
            stroke="rgba(0,0,0,0.22)" strokeWidth="0.5"/>
        </g>
      ))}

      {/* Photon beams — glow layer */}
      {beamXs.map((x, i) => (
        <rect key={`aura-${i}`} x={x - 10} y={skinStart} width="20" height={beamEndY - skinStart}
          fill="url(#lxBeamGrad)" filter="url(#lxBlur8)" opacity="0.55"
          style={{animation:`lxPhotonDrop 1.6s cubic-bezier(0.28,0,0.22,1) ${i*0.12}s infinite`,
                  transition:"height 700ms cubic-bezier(0.28,0,0.22,1), y 700ms"}}/>
      ))}
      {/* Photon beams — core */}
      {beamXs.map((x, i) => (
        <rect key={`core-${i}`} x={x - 1.2} y={skinStart} width="2.4" height={beamEndY - skinStart}
          fill="url(#lxBeamGrad)"
          style={{animation:`lxPhotonDrop 1.6s cubic-bezier(0.28,0,0.22,1) ${i*0.12}s infinite`,
                  transition:"height 700ms cubic-bezier(0.28,0,0.22,1), y 700ms"}}/>
      ))}

      {/* Cell activity particles */}
      {particles.map((p, i) => (
        <g key={i}>
          <circle cx={p.x} cy={p.y} r={p.r * 3} fill="url(#lxCellGlow)" opacity="0.5"
            filter="url(#lxBlur4)"
            style={{animation:`lxCellPulse 2.4s ease-in-out ${p.d}s infinite`, transformOrigin:`${p.x}px ${p.y}px`}}/>
          <circle cx={p.x} cy={p.y} r={p.r} fill={p.color}
            style={{animation:`lxCellPulse 2.4s ease-in-out ${p.d}s infinite`, transformOrigin:`${p.x}px ${p.y}px`}}/>
        </g>
      ))}

      {/* Active depth line */}
      <g style={{transition:"transform 700ms cubic-bezier(0.28,0,0.22,1)"}}>
        <line x1="40" x2="560" y1={beamEndY} y2={beamEndY}
          stroke={beamCore} strokeWidth="1.2" strokeDasharray="5 5" opacity="0.7"
          style={{transition:"y1 700ms cubic-bezier(0.28,0,0.22,1), y2 700ms"}}/>
        <circle cx="40" cy={beamEndY} r="5" fill={beamCore}
          style={{transition:"cy 700ms cubic-bezier(0.28,0,0.22,1)"}}/>
        <circle cx="40" cy={beamEndY} r="10" fill={beamCore} opacity="0.35"
          style={{transition:"cy 700ms cubic-bezier(0.28,0,0.22,1)", animation:"lxPulse 1.8s ease-in-out infinite"}}/>
      </g>

      {/* Layer labels on right */}
      {layers.map((l, i) => (
        <g key={`lbl-${i}`}>
          <text x="578" y={(l.y1 + l.y2)/2 - 4} textAnchor="end"
            fontSize="13" fill="#fff" fontWeight="500"
            style={{letterSpacing:"0.04em"}}>{l.name}</text>
          <text x="578" y={(l.y1 + l.y2)/2 + 12} textAnchor="end"
            fontSize="10" fill="rgba(255,255,255,0.55)"
            style={{letterSpacing:"0.1em", textTransform:"uppercase"}}>{l.mm}</text>
        </g>
      ))}

      {/* Depth ruler */}
      <g>
        <line x1="22" x2="22" y1={skinStart} y2={skinEnd} stroke="rgba(255,255,255,0.2)" strokeWidth="1"/>
        {rulerMarks.map((m, i) => (
          <g key={i}>
            <line x1="18" x2="26" y1={m.y} y2={m.y} stroke="rgba(255,255,255,0.35)" strokeWidth="1"/>
            <text x="14" y={m.y + 3} textAnchor="end" fontSize="10" fill="rgba(255,255,255,0.55)"
              fontVariantNumeric="tabular-nums">{m.mm}</text>
          </g>
        ))}
        <text x="14" y={skinStart - 8} textAnchor="end" fontSize="9"
          fill="rgba(255,255,255,0.35)"
          style={{letterSpacing:"0.15em", textTransform:"uppercase"}}>mm</text>
      </g>
    </svg>
  );
}

/* ------------- Spectrum bar with animated marker ------------- */
function SpectrumBar({ wl }) {
  const pos = ((wl - 600) / 300) * 100;  // percent
  const marks = [
    { nm: 600, l: "600" },
    { nm: 630, l: "630", active: wl === 630 },
    { nm: 700, l: "700" },
    { nm: 800, l: "800" },
    { nm: 850, l: "850", active: wl === 850 },
    { nm: 900, l: "900" },
  ];

  return (
    <div style={{padding:"20px 0", borderTop:"1px solid rgba(255,255,255,0.08)"}}>
      <div style={{
        display:"flex", justifyContent:"space-between", alignItems:"center",
        fontSize:11, letterSpacing:"0.1em", textTransform:"uppercase",
        color:"rgba(255,255,255,0.4)", marginBottom:22,
      }}>
        <span>Spektrum · nm</span>
        <span style={{color:"#ff4a57"}}>{wl === 630 ? "Red visible" : "Near-infrared"}</span>
      </div>

      <div style={{position:"relative", height:58}}>
        {/* Color spectrum bar */}
        <div style={{
          position:"absolute", left:0, right:0, top:22, height:14, borderRadius:7,
          background:"linear-gradient(to right, #ff7a00 0%, #ff3520 18%, #e50914 35%, #a00a12 55%, #5a0a0f 78%, #1a0508 100%)",
          boxShadow:"inset 0 0 12px rgba(0,0,0,0.6), 0 0 20px rgba(229,9,20,0.12)",
        }}/>
        {/* Tick marks */}
        {marks.map((m, i) => {
          const x = ((m.nm - 600) / 300) * 100;
          return (
            <div key={i} style={{position:"absolute", left:`${x}%`, top:0, height:"100%", transform:"translateX(-50%)"}}>
              <div style={{
                position:"absolute", left:"50%", top: m.active ? 6 : 16, width:1,
                height: m.active ? 26 : 6,
                background: m.active ? "#fff" : "rgba(255,255,255,0.3)",
                transform:"translateX(-50%)",
                transition:"all 400ms",
              }}/>
              <div style={{
                position:"absolute", left:"50%", top: m.active ? 40 : 26, transform:"translateX(-50%)",
                fontSize: m.active ? 12 : 10,
                fontWeight: m.active ? 600 : 400,
                color: m.active ? "#fff" : "rgba(255,255,255,0.4)",
                fontVariantNumeric:"tabular-nums",
                whiteSpace:"nowrap",
                transition:"all 400ms",
              }}>{m.l}</div>
            </div>
          );
        })}
        {/* Animated marker */}
        <div style={{
          position:"absolute", left:`${pos}%`, top:29,
          transform:"translate(-50%,-50%)",
          transition:"left 800ms cubic-bezier(0.28,0,0.22,1)",
          pointerEvents:"none",
        }}>
          <div style={{
            position:"absolute", left:"50%", top:"50%",
            width:40, height:40, borderRadius:"50%",
            background:"radial-gradient(circle, rgba(255,255,255,0.6) 0%, rgba(255,48,64,0.35) 40%, transparent 70%)",
            filter:"blur(3px)",
            animation:"lxMarkerPulse 2s ease-in-out infinite",
          }}/>
          <div style={{
            position:"absolute", left:"50%", top:"50%", transform:"translate(-50%,-50%)",
            width:16, height:16, borderRadius:"50%",
            background:"#fff",
            boxShadow:"0 0 0 2px rgba(255,255,255,0.3), 0 0 14px rgba(255,255,255,0.9), 0 0 28px rgba(255,48,64,0.8)",
          }}/>
        </div>
      </div>
    </div>
  );
}

/* ------------- Oscilloscope waveform ------------- */
function WaveformDisplay({ wl }) {
  // Shorter λ = more cycles in fixed window.
  // 630nm: 9 cycles; 850nm: 5 cycles (frequency proportional to 1/λ)
  const cycles = wl === 630 ? 9 : 5;
  const amp = 14;
  const w = 320; const h = 64;
  const points = [];
  for (let i = 0; i <= 160; i++) {
    const x = (i / 160) * w;
    const y = h/2 + Math.sin((i/160) * cycles * Math.PI * 2) * amp;
    points.push(`${x},${y.toFixed(2)}`);
  }
  const path = "M" + points.join(" L");
  const color = wl === 630 ? "#ff3848" : "#c41528";
  const freqTHz = wl === 630 ? "476" : "353";

  return (
    <div style={{
      padding:"18px 20px",
      background:"linear-gradient(180deg, rgba(10,4,6,0.6), rgba(10,4,6,0.3))",
      borderRadius:14, border:"1px solid rgba(255,255,255,0.06)",
      position:"relative", overflow:"hidden",
    }}>
      {/* scan line */}
      <div aria-hidden="true" style={{
        position:"absolute", inset:0,
        background:"linear-gradient(180deg, transparent 0%, rgba(255,74,87,0.1) 50%, transparent 100%)",
        animation:"lxScanLine 4s linear infinite",
        pointerEvents:"none",
      }}/>

      <div style={{display:"flex", justifyContent:"space-between", alignItems:"center", marginBottom:8, position:"relative"}}>
        <span style={{fontSize:10, letterSpacing:"0.12em", color:"rgba(255,255,255,0.4)", textTransform:"uppercase"}}>
          Fala · {wl === 630 ? "Widzialna" : "Podczerwień"}
        </span>
        <span style={{fontSize:10, letterSpacing:"0.12em", color:"#ff4a57", textTransform:"uppercase", fontVariantNumeric:"tabular-nums"}}>
          {freqTHz} THz
        </span>
      </div>

      <svg viewBox={`0 0 ${w} ${h}`} style={{width:"100%", height:64, display:"block", position:"relative"}}>
        <defs>
          <linearGradient id={`waveGrad${wl}`} x1="0" x2="1" y1="0" y2="0">
            <stop offset="0%"  stopColor={color} stopOpacity="0.15"/>
            <stop offset="20%" stopColor={color} stopOpacity="1"/>
            <stop offset="80%" stopColor={color} stopOpacity="1"/>
            <stop offset="100%" stopColor={color} stopOpacity="0.15"/>
          </linearGradient>
        </defs>
        {/* grid */}
        <line x1="0" x2={w} y1={h/2} y2={h/2} stroke="rgba(255,255,255,0.08)" strokeDasharray="2 4"/>
        {[...Array(5)].map((_, i) => (
          <line key={i} x1={(i+1) * w/6} x2={(i+1) * w/6} y1="0" y2={h}
            stroke="rgba(255,255,255,0.05)"/>
        ))}
        {/* blur aura */}
        <path key={`blur-${wl}`} d={path} fill="none"
          stroke={color} strokeWidth="5" opacity="0.35"
          filter="url(#lxBlur4)"
          style={{animation:"lxFadeIn 600ms"}}/>
        {/* core line */}
        <path key={`core-${wl}`} d={path} fill="none"
          stroke={`url(#waveGrad${wl})`} strokeWidth="2" strokeLinecap="round"
          style={{animation:"lxFadeIn 600ms"}}/>
      </svg>
    </div>
  );
}

/* ==========================================================
   SECTION: How it works — 10 min session, 3 steps + live timer
   ========================================================== */
function HowItWorksSection() {
  const { t } = useApp();
  const copy = t.howItWorks;
  const ref = useReveal();
  const [secs, setSecs] = useState(600);
  const [running, setRunning] = useState(false);

  useEffect(() => {
    if (!running) return;
    if (secs <= 0) { setRunning(false); return; }
    const id = setTimeout(() => setSecs((s) => s - 1), 1000);
    return () => clearTimeout(id);
  }, [running, secs]);

  const mm = String(Math.floor(secs/60)).padStart(2,"0");
  const ss = String(secs%60).padStart(2,"0");
  const pct = 1 - secs/600;

  return (
    <section className="lx-section-light" ref={ref} data-screen-label="How It Works">
      <div className="lx-container lx-reveal">
        <div style={{textAlign:"center", marginBottom:72}}>
          <div className="lx-eyebrow">{copy.eyebrow}</div>
          <h2 className="lx-section-title lx-mt-16">{copy.title}</h2>
          <p className="lx-subtitle lx-mt-24" style={{maxWidth:680, margin:"24px auto 0"}}>{copy.subtitle}</p>
        </div>

        {/* Timer */}
        <div style={{
          display:"flex", flexDirection:"column", alignItems:"center", gap:20,
          marginBottom:80,
        }}>
          <div style={{
            position:"relative", width:260, height:260, borderRadius:"50%",
            background:"#fff",
            boxShadow:"0 30px 80px rgba(0,0,0,0.08)",
            display:"grid", placeItems:"center",
          }}>
            {/* Progress ring */}
            <svg viewBox="0 0 200 200" style={{position:"absolute", inset:0, width:"100%", height:"100%", transform:"rotate(-90deg)"}}>
              <circle cx="100" cy="100" r="90" fill="none" stroke="rgba(0,0,0,0.06)" strokeWidth="4"/>
              <circle cx="100" cy="100" r="90" fill="none" stroke="url(#timerGrad)" strokeWidth="4" strokeLinecap="round"
                strokeDasharray={`${2*Math.PI*90}`}
                strokeDashoffset={`${2*Math.PI*90 * (1 - pct)}`}
                style={{transition:"stroke-dashoffset 1s linear"}}/>
              <defs>
                <linearGradient id="timerGrad" x1="0" x2="1" y1="0" y2="1">
                  <stop offset="0%" stopColor="#8b1a1a"/>
                  <stop offset="100%" stopColor="#e50914"/>
                </linearGradient>
              </defs>
            </svg>
            <div style={{textAlign:"center"}}>
              <div style={{fontSize:12, letterSpacing:"0.12em", textTransform:"uppercase", color:"rgba(0,0,0,0.4)"}}>{copy.timerLabel}</div>
              <div style={{fontSize:64, fontWeight:300, letterSpacing:"-0.04em", fontVariantNumeric:"tabular-nums", marginTop:4}}>
                {mm}:{ss}
              </div>
            </div>
          </div>
          <button onClick={() => { if (secs === 0) setSecs(600); setRunning(!running); }}
            className="lx-btn lx-btn-primary" style={{padding:"12px 28px"}}>
            {running ? "Pauza" : (secs === 600 ? "Start" : (secs === 0 ? "Restart" : "Wznów"))}
          </button>
        </div>

        <div style={{display:"grid", gridTemplateColumns:"repeat(3, 1fr)", gap:32}} className="hiw-grid">
          {copy.steps.map((s, i) => (
            <div key={i} style={{textAlign:"left"}}>
              <div style={{fontSize:14, fontWeight:600, color:"#e50914", letterSpacing:"0.08em"}}>{s.n}</div>
              <h3 style={{fontSize:26, fontWeight:600, letterSpacing:"-0.015em", margin:"12px 0 10px"}}>{s.t}</h3>
              <p className="lx-body" style={{margin:0}}>{s.d}</p>
            </div>
          ))}
        </div>
      </div>
      <style>{`@media (max-width: 720px) { .hiw-grid { grid-template-columns: 1fr !important; } }`}</style>
    </section>
  );
}

/* ==========================================================
   SECTION: Products — 3 cards, hover glow
   ========================================================== */
function ProductsSection() {
  const { t } = useApp();
  const copy = t.products;
  const ref = useReveal();

  return (
    <section className="lx-section-white" id="products" ref={ref} data-screen-label="Products">
      <div className="lx-container-wide lx-reveal">
        <div style={{textAlign:"center", marginBottom:72}}>
          <div className="lx-eyebrow">{copy.eyebrow}</div>
          <h2 className="lx-section-title lx-mt-16">{copy.title}</h2>
          <p className="lx-subtitle lx-mt-24" style={{maxWidth:640, margin:"24px auto 0"}}>{copy.subtitle}</p>
        </div>
        <div style={{display:"grid", gridTemplateColumns:"repeat(3,1fr)", gap:20}} className="prod-grid">
          {copy.items.map((p) => <ProductCard key={p.slug} p={p} cta={copy.cta}/>) }
        </div>
      </div>
      <style>{`@media (max-width: 900px) { .prod-grid { grid-template-columns: 1fr !important; } }`}</style>
    </section>
  );
}

function ProductCard({ p, cta }) {
  const [hover, setHover] = useState(false);
  const stripeUrl = (window.LUMAFLEX_CONFIG?.stripe?.[p.slug]) || "";
  const href = stripeUrl || "#compare";
  const target = stripeUrl ? "_blank" : undefined;
  const rel = stripeUrl ? "noopener" : undefined;
  return (
    <div onMouseEnter={() => setHover(true)} onMouseLeave={() => setHover(false)}
      style={{
        background:"#f5f5f7",
        borderRadius: 22,
        padding: 32,
        position:"relative",
        overflow:"hidden",
        transition:"all 400ms cubic-bezier(0.28,0,0.22,1)",
        transform: hover ? "translateY(-4px)" : "translateY(0)",
      }}>
      <div style={{
        position:"absolute", inset:0,
        background: `radial-gradient(60% 50% at 50% 40%, rgba(var(--lx-red-glow), ${hover ? 0.22 : 0}) 0%, rgba(var(--lx-red-glow), 0) 70%)`,
        transition:"opacity 500ms",
        pointerEvents:"none",
      }}/>
      <div style={{position:"relative"}}>
        <div style={{display:"flex", justifyContent:"space-between", alignItems:"flex-start", marginBottom:12}}>
          <div>
            <div style={{fontSize:12, letterSpacing:"0.08em", textTransform:"uppercase", color:"#e50914", fontWeight:600}}>{p.tag}</div>
            <h3 style={{fontSize:28, fontWeight:600, letterSpacing:"-0.02em", margin:"6px 0 0"}}>{p.name}</h3>
          </div>
          <div style={{textAlign:"right"}}>
            <div style={{fontSize:20, fontWeight:600, letterSpacing:"-0.015em"}}>{p.price}</div>
            <div style={{fontSize:12, opacity:0.5}}>{p.priceSub}</div>
          </div>
        </div>

        <div style={{
          position:"relative", height:300, display:"grid", placeItems:"center",
          margin:"24px -8px 16px",
        }}>
          <div style={{
            position:"absolute", inset: "20%", borderRadius:"50%",
            background: "radial-gradient(circle, rgba(var(--lx-red-glow), calc(0.4 * var(--lx-intensity))) 0%, transparent 70%)",
            filter:"blur(20px)",
            opacity: hover ? 1 : 0.5,
            transition:"opacity 500ms",
          }}/>
          <img src={p.image} alt={p.name} style={{
            position:"relative", maxHeight:"100%", maxWidth:"100%", objectFit:"contain",
            transition:"transform 700ms cubic-bezier(0.28,0,0.22,1)",
            transform: hover ? "scale(1.05)" : "scale(1)",
          }}/>
        </div>

        <p className="lx-body" style={{margin:"0 0 16px", minHeight:50}}>{p.desc}</p>
        <div style={{fontSize:12, color:"rgba(0,0,0,0.5)", letterSpacing:"-0.01em", marginBottom:24}}>{p.specs}</div>
        <a href={href} target={target} rel={rel} className="lx-btn lx-btn-primary" style={{width:"100%"}} data-product={p.slug}>{cta}</a>
      </div>
    </div>
  );
}

Object.assign(window, { WavelengthsSection, HowItWorksSection, ProductsSection });
