// Diagram.jsx — tabbed filtration stages, content from CMS filterTiers BlockList
function Diagram() {
  const FALLBACK_TIERS = [
    { tab: '3', title: '3-Stage', label: 'SYS-01', tagline: 'Essentials',
      note: 'Entry-level for good municipal water. Clean taste, removes chlorine and sediment.',
      stages: [
        { n: '01', title: 'Sediment', short: 'Sediment', desc: 'Spun polypropylene captures rust, silt, and particulate down to 5 microns.' },
        { n: '02', title: 'Carbon',   short: 'Carbon',   desc: 'Activated coconut-shell carbon removes chlorine, taste, and odor compounds.' },
        { n: '03', title: 'Polish',   short: 'Polish',   desc: 'A final fine-carbon polish for balanced, ready-to-drink flavor.' },
      ] },
    { tab: '5', title: '5-Stage', 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',   short: 'Sediment',   desc: 'Spun polypropylene captures rust, silt, and particulate down to 5 microns.' },
        { n: '02', title: 'Pre-carbon', short: 'Pre-carbon', desc: 'Activated coconut-shell carbon removes chlorine, chloramines, and taste/odor compounds.' },
        { n: '03', title: 'Membrane',   short: 'Membrane',   desc: 'A 0.0001-micron RO membrane rejects lead, PFAS, nitrates, microplastics, and dissolved solids.' },
        { n: '04', title: 'Mineral',    short: 'Mineral',    desc: 'Re-mineralization cartridge adds calcium and magnesium, lifting pH to 7.4-8.2 for balanced taste.' },
        { n: '05', title: 'Polish',     short: 'Polish',     desc: 'A final carbon block polishes flavor and removes residual odors before your glass.' },
      ] },
    { tab: '7', title: '7-Stage', 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',   short: 'Sediment',   desc: 'Multi-gradient sediment capture from 20 microns down to 1 - protects every stage that follows.' },
        { n: '02', title: 'KDF',        short: 'KDF',        desc: 'KDF-55 media removes heavy metals, hydrogen sulfide, and inhibits bacterial growth.' },
        { n: '03', title: 'Pre-carbon', short: 'Pre-carbon', desc: 'High-surface-area carbon block for chlorine, chloramines, VOCs, and pesticides.' },
        { n: '04', title: 'Membrane',   short: 'Membrane',   desc: 'Premium 100 GPD RO membrane - lead, PFAS, nitrates, microplastics, and 99.9% TDS.' },
        { n: '05', title: 'Mineral',    short: 'Mineral',    desc: 'Calcium, magnesium and potassium are re-introduced; pH rebalanced to 7.8-8.4.' },
        { n: '06', title: 'UV',         short: 'UV',         desc: 'A 254nm ultraviolet chamber sterilizes any remaining microbes in the line.' },
        { n: '07', title: 'Polish',     short: 'Polish',     desc: 'Final coconut-carbon polish + flavor buffer for a consistently neutral, clean finish.' },
      ] },
  ];

  const fromCms = (window.__AQUO_CONTENT__ && window.__AQUO_CONTENT__.filterTiers) || [];
  const tiersArr = (Array.isArray(fromCms) && fromCms.length > 0) ? fromCms : FALLBACK_TIERS;

  const [tierIdx, setTierIdx] = React.useState(Math.min(1, tiersArr.length - 1));
  const [active, setActive] = React.useState(0);
  const current = tiersArr[tierIdx] || tiersArr[0];
  const stages = current.stages || [];

  // when switching tier, clamp active
  React.useEffect(() => {
    setActive(a => Math.min(a, Math.max(0, stages.length - 1)));
  }, [tierIdx, 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">
          {tiersArr.map((t, i) => (
            <button key={`${t.tab || i}-${i}`}
                    role="tab"
                    aria-selected={tierIdx === i}
                    className={`diag-tab${tierIdx === i ? ' active' : ''}`}
                    onClick={() => setTierIdx(i)}>
              <span className="diag-tab-num">{t.title || t.tab || (t.stages ? t.stages.length : '')}</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={`${tierIdx}-${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;
                // label box width (in SVG units) — wider than the tank so long text wraps
                const labelW = stages.length <= 3 ? 110 : stages.length <= 5 ? 96 : 80;
                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>
                    <foreignObject x={cx - labelW/2} y={358} width={labelW} height={48}>
                      <div xmlns="http://www.w3.org/1999/xhtml" style={{
                        fontFamily: 'Space Grotesk, sans-serif',
                        fontWeight: 400,
                        fontSize: `${fontSize}px`,
                        color,
                        textAlign: 'center',
                        lineHeight: 1.15,
                        wordBreak: 'break-word',
                        overflowWrap: 'anywhere',
                      }}>
                        {s.shortLabel || s.title}
                      </div>
                    </foreignObject>
                  </g>
                );
              })}
            </svg>
          </div>

          <div className="diagram-stages">
            {stages.map((s, i) => (
              <div key={`${tierIdx}-${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;
