// Diagram.jsx — tabbed filtration stages (3 / 5 / 7)
function Diagram() {
  const tiers = {
    '3': {
      label: 'SYS-01',
      tagline: 'Essentials',
      note: 'Entry-level for good municipal water. Clean taste, removes chlorine and sediment.',
      stages: [
        { n: '01', title: 'Sediment', desc: 'Spun polypropylene captures rust, silt, and particulate down to 5 microns.' },
        { n: '02', title: 'Carbon',   desc: 'Activated coconut-shell carbon removes chlorine, taste, and odor compounds.' },
        { n: '03', title: 'Polish',   desc: 'A final fine-carbon polish for balanced, ready-to-drink flavor.' },
      ],
    },
    '5': {
      label: 'SYS-03',
      tagline: 'Household',
      note: 'Our bestseller. Reverse-osmosis certified for lead, PFAS, and 99.9% of dissolved solids.',
      stages: [
        { n: '01', title: 'Sediment',   desc: 'Spun polypropylene captures rust, silt, and particulate down to 5 microns.' },
        { n: '02', title: 'Pre-carbon', desc: 'Activated coconut-shell carbon removes chlorine, chloramines, and taste/odor compounds.' },
        { n: '03', title: 'Membrane',   desc: 'A 0.0001-micron RO membrane rejects lead, PFAS, nitrates, microplastics, and dissolved solids.' },
        { n: '04', title: 'Mineral',    desc: 'Re-mineralization cartridge adds calcium and magnesium, lifting pH to 7.4–8.2 for balanced taste.' },
        { n: '05', title: 'Polish',     desc: 'A final carbon block polishes flavor and removes residual odors before your glass.' },
      ],
    },
    '7': {
      label: 'SYS-07',
      tagline: 'Pro',
      note: 'Whole-home grade. Adds UV sterilization and alkaline balancing for the most demanding water.',
      stages: [
        { n: '01', title: 'Sediment',   desc: 'Multi-gradient sediment capture from 20 microns down to 1 — protects every stage that follows.' },
        { n: '02', title: 'KDF',        desc: 'KDF-55 media removes heavy metals, hydrogen sulfide, and inhibits bacterial growth.' },
        { n: '03', title: 'Pre-carbon', desc: 'High-surface-area carbon block for chlorine, chloramines, VOCs, and pesticides.' },
        { n: '04', title: 'Membrane',   desc: 'Premium 100 GPD RO membrane — lead, PFAS, nitrates, microplastics, and 99.9% TDS.' },
        { n: '05', title: 'Mineral',    desc: 'Calcium, magnesium and potassium are re-introduced; pH rebalanced to 7.8–8.4.' },
        { n: '06', title: 'UV',         desc: 'A 254nm ultraviolet chamber sterilizes any remaining microbes in the line.' },
        { n: '07', title: 'Polish',     desc: 'Final coconut-carbon polish + flavor buffer for a consistently neutral, clean finish.' },
      ],
    },
  };

  const [tier, setTier] = React.useState('5');
  const [active, setActive] = React.useState(2);
  const current = tiers[tier];
  const stages = current.stages;

  // when switching tier, clamp active
  React.useEffect(() => {
    setActive(a => Math.min(a, stages.length - 1));
  }, [tier, stages.length]);

  // evenly space stops across the pipe
  const left = 10, right = 90;
  const step = stages.length > 1 ? (right - left) / (stages.length - 1) : 0;
  const stops = stages.map((_, i) => left + i * step);

  const neon = '#00E5FF';
  const soft = 'rgba(140, 165, 196, 0.6)';

  return (
    <section className="diagram-section" data-screen-label="04 How it works">
      <div className="wrap">
        <div className="section-head">
          <div>
            <div className="eyebrow">Anatomy — pick your system</div>
            <h2 className="section-title">
              Three stages, five, or <span className="glow">seven.</span>
            </h2>
          </div>
          <p className="section-note">
            Three systems for three kinds of home. Switch between them and the
            rig reconfigures — same principle, different scale.
          </p>
        </div>

        <div className="diag-tabs" role="tablist">
          {Object.keys(tiers).map(k => {
            const t = tiers[k];
            return (
              <button key={k}
                      role="tab"
                      aria-selected={tier === k}
                      className={`diag-tab${tier === k ? ' active' : ''}`}
                      onClick={() => setTier(k)}>
                <span className="diag-tab-num">{k}-STAGE</span>
                <span className="diag-tab-meta">
                  <span className="diag-tab-label">{t.label}</span>
                  <span className="diag-tab-tagline">{t.tagline}</span>
                </span>
              </button>
            );
          })}
        </div>

        <div className="diag-note"><span className="mono">{current.label}</span> · {current.note}</div>

        <div className="diagram-wrap">
          <div className="diagram-canvas">
            <svg viewBox="0 0 600 440" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
              <defs>
                <linearGradient id="pipeGrad" x1="0" y1="0" x2="1" y2="0">
                  <stop offset="0" stopColor={neon} stopOpacity="0.3"/>
                  <stop offset="1" stopColor="#4A9EFF" stopOpacity="0.8"/>
                </linearGradient>
                <filter id="neonGlow" x="-50%" y="-50%" width="200%" height="200%">
                  <feGaussianBlur stdDeviation="3" result="blur"/>
                  <feMerge><feMergeNode in="blur"/><feMergeNode in="SourceGraphic"/></feMerge>
                </filter>
              </defs>

              <text x="30" y="198" fontFamily="IBM Plex Mono" fontSize="10" fill={soft} letterSpacing="2">TAP →</text>
              <text x="528" y="198" fontFamily="IBM Plex Mono" fontSize="10" fill={neon} letterSpacing="2">GLASS</text>

              <rect x="70" y="212" width="460" height="16" rx="2" fill="url(#pipeGrad)" filter="url(#neonGlow)"/>

              <g>
                {[0, 0.2, 0.4, 0.6, 0.8].map((d, i) => (
                  <circle key={`${tier}-${i}`} r="3" fill={neon} filter="url(#neonGlow)">
                    <animateMotion dur="5s" begin={`${d * -5}s`} repeatCount="indefinite"
                      path="M70 220 L530 220" />
                  </circle>
                ))}
              </g>

              {stages.map((s, i) => {
                const cx = 60 + (stops[i] / 100) * 480;
                const isActive = active === i;
                const color = isActive ? neon : soft;
                const fillc = isActive ? 'rgba(0,229,255,0.12)' : 'rgba(13,22,40,0.8)';
                // narrower tanks when more stages
                const w = stages.length <= 3 ? 60 : stages.length <= 5 ? 52 : 40;
                const fontSize = stages.length >= 7 ? 12 : 15;
                return (
                  <g key={i} style={{ cursor: 'pointer' }}
                     onMouseEnter={() => setActive(i)}
                     onClick={() => setActive(i)}
                     filter={isActive ? 'url(#neonGlow)' : undefined}>
                    <rect x={cx - w/2} y={130} width={w} height={180} rx={4}
                          fill={fillc} stroke={color} strokeWidth={isActive ? 1.5 : 1}
                          style={{ transition: 'all 220ms' }}/>
                    <rect x={cx - w/2 - 4} y={122} width={w + 8} height={8} rx={1} fill={color}/>
                    <rect x={cx - w/2 - 4} y={310} width={w + 8} height={8} rx={1} fill={color}/>
                    <circle cx={cx} cy={180} r={isActive ? 12 : 8} fill={color} opacity={0.25}>
                      <animate attributeName="r" values={isActive ? '10;14;10' : '8;8;8'} dur="2s" repeatCount="indefinite"/>
                    </circle>
                    <circle cx={cx} cy={220} r={isActive ? 14 : 10} fill={color} opacity={0.18}/>
                    <circle cx={cx} cy={260} r={isActive ? 10 : 7} fill={color} opacity={0.28}/>
                    <text x={cx} y={350} textAnchor="middle" fontFamily="IBM Plex Mono" fontSize="10" fill={color} letterSpacing="2">
                      {s.n}
                    </text>
                    <text x={cx} y={370} textAnchor="middle" fontFamily="Space Grotesk" fontWeight="400" fontSize={fontSize} fill={color}>
                      {s.title}
                    </text>
                  </g>
                );
              })}
            </svg>
          </div>

          <div className="diagram-stages">
            {stages.map((s, i) => (
              <div key={`${tier}-${i}`} className={`dstage${active === i ? ' active' : ''}`}
                   onClick={() => setActive(i)}
                   onMouseEnter={() => setActive(i)}>
                <span className="num">{s.n}</span>
                <div>
                  <div className="title">{s.title}</div>
                  <div className="dstage-desc">{s.desc}</div>
                </div>
                <svg className="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <path d="M9 6l6 6-6 6"/>
                </svg>
              </div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

window.Diagram = Diagram;
