/* Bridgehead — Diagnostic (early-stage pain point discovery) */

const { useState, useEffect, useRef, useMemo } = React;

// ============= BURST (pixel explosion) =============
function BubbleBurst({ keySeed = 0 }) {
  const particles = useMemo(() => {
    const N = 36;
    return Array.from({ length: N }, (_, i) => {
      const angle = (i / N) * Math.PI * 2 + (Math.random() - 0.5) * 0.5;
      const dist = 90 + Math.random() * 180;
      return {
        id: i,
        dx: Math.cos(angle) * dist,
        dy: Math.sin(angle) * dist,
        size: 3 + Math.floor(Math.random() * 5),
        rot: (Math.random() - 0.5) * 720,
        delay: Math.random() * 80,
        dur: 700 + Math.random() * 420,
        hue: Math.random() < 0.18 ? 'ink' : 'accent',
      };
    });
  }, [keySeed]);

  return (
    <span className="diag-burst" aria-hidden="true">
      {particles.map(p => (
        <span
          key={p.id}
          className={`burst-px ${p.hue}`}
          style={{
            '--dx': `${p.dx}px`,
            '--dy': `${p.dy}px`,
            '--size': `${p.size}px`,
            '--rot': `${p.rot}deg`,
            '--delay': `${p.delay}ms`,
            '--dur': `${p.dur}ms`,
          }}
        />
      ))}
      <span className="burst-ring" />
      <span className="burst-ring two" />
    </span>
  );
}

// ============= SEGMENT / AREA BUBBLES =============
function BubbleField({ items, picking, onPick, variant = 'segment' }) {
  const motion = useMemo(() =>
    items.map((_, i) => {
      const seed = (i * 9301 + 49297) % 233280;
      const rand = (s) => (s % 233280) / 233280;
      const r1 = rand(seed);
      const r2 = rand(seed * 7);
      const r3 = rand(seed * 13);
      return {
        delay: `${-(r1 * 6).toFixed(2)}s`,
        dur: `${(6 + r2 * 4).toFixed(2)}s`,
        ampY: `${(10 + r3 * 12).toFixed(0)}px`,
        ampX: `${(8 + r1 * 14).toFixed(0)}px`,
        yOffset: `${((i % 2 === 0 ? 1 : -1) * (16 + r2 * 28)).toFixed(0)}px`,
        rotation: `${((r3 - 0.5) * 8).toFixed(1)}deg`,
      };
    }),
    [items.map(it => it.id).join(',')]
  );

  return (
    <div className={`diag-bubbles var-${variant}`}>
      {items.map((it, i) => {
        const isPicked = picking === it.id;
        const isFading = picking && picking !== it.id;
        return (
          <button
            key={it.id}
            className={`diag-bubble ${isPicked ? 'picked' : ''} ${isFading ? 'fading' : ''}`}
            onClick={() => !picking && onPick(it.id)}
            style={{
              '--float-delay': motion[i].delay,
              '--float-dur': motion[i].dur,
              '--float-amp-y': motion[i].ampY,
              '--float-amp-x': motion[i].ampX,
              '--y-offset': motion[i].yOffset,
              '--rot': motion[i].rotation,
              '--fade-delay': `${i * 25}ms`,
            }}
          >
            <span className="orb">
              <span className="bt">{it.title}</span>
              <span className="bb">{it.blurb}</span>
            </span>
            {isPicked && <BubbleBurst keySeed={it.id} />}
          </button>
        );
      })}
    </div>
  );
}

// ============= SIGNAL BUBBLES (multi-select) =============
function SignalBubbles({ items, selected, onToggle }) {
  const motion = useMemo(() =>
    items.map((_, i) => {
      const seed = (i * 4561 + 12289) % 233280;
      const rand = (s) => (s % 233280) / 233280;
      const r1 = rand(seed);
      const r2 = rand(seed * 11);
      return {
        delay: `${-(r1 * 5).toFixed(2)}s`,
        dur: `${(5 + r2 * 3).toFixed(2)}s`,
        ampY: `${(8 + r1 * 10).toFixed(0)}px`,
        ampX: `${(6 + r2 * 10).toFixed(0)}px`,
      };
    }),
    [items.map(it => it.id).join(',')]
  );

  return (
    <div className="diag-signals">
      {items.map((p, i) => {
        const on = selected.has(p.id);
        return (
          <button
            key={p.id}
            className={`diag-sig ${on ? 'on' : ''}`}
            onClick={() => onToggle(p.id)}
            style={{
              '--float-delay': motion[i].delay,
              '--float-dur': motion[i].dur,
              '--float-amp-y': motion[i].ampY,
              '--float-amp-x': motion[i].ampX,
            }}
          >
            <span className="sig-orb">
              <span className="sig-check" aria-hidden="true">
                <svg viewBox="0 0 12 12"><path d="M2.5 6.4 L5 8.8 L9.5 3.6" /></svg>
              </span>
              <span className="sig-label">{p.short}</span>
            </span>
            <span className="sig-ripple" />
          </button>
        );
      })}
    </div>
  );
}

// ============= CUSTOM INPUT ORB (Something else) =============
function CustomInputOrb({ value, onChange, isVisible }) {
  const [isFocused, setIsFocused] = useState(false);
  const textareaRef = useRef(null);

  useEffect(() => {
    if (isVisible && textareaRef.current) {
      setTimeout(() => textareaRef.current?.focus(), 400);
    }
  }, [isVisible]);

  if (!isVisible) return null;

  return (
    <div className={`custom-orb-wrap ${isFocused ? 'focused' : ''}`}>
      <div className="custom-orb">
        <div className="custom-orb-glow" />
        <div className="custom-orb-ring" />
        <div className="custom-orb-inner">
          <span className="custom-orb-label">Tell us more</span>
          <textarea
            ref={textareaRef}
            className="custom-orb-input"
            placeholder="What's the specific challenge you're facing?"
            value={value}
            onChange={(e) => onChange(e.target.value)}
            onFocus={() => setIsFocused(true)}
            onBlur={() => setIsFocused(false)}
            rows={3}
          />
          <span className="custom-orb-hint">This helps us prepare for our call</span>
        </div>
        <div className="custom-orb-particles">
          {[...Array(8)].map((_, i) => (
            <span key={i} className="particle" style={{ '--i': i }} />
          ))}
        </div>
      </div>
    </div>
  );
}

// ============= BUILD CONSTELLATION (orbital visual) =============
function BuildConstellation({ sol, segment }) {
  const items = useMemo(() => sol.spec.filter(s => !s.c), [sol.spec]);
  const N = items.length;
  const [revealed, setRevealed] = useState(0);
  const [hover, setHover] = useState(null);
  const timer = useRef(null);

  useEffect(() => {
    setRevealed(0);
    let i = 0;
    const tick = () => {
      i += 1;
      if (i <= N) {
        setRevealed(i);
        timer.current = setTimeout(tick, 260);
      }
    };
    timer.current = setTimeout(tick, 600);
    return () => clearTimeout(timer.current);
  }, [sol.title]);

  // SVG coordinate space
  const W = 1000, H = 620;
  const cx = W / 2, cy = H / 2;
  const rx = 330, ry = 220;
  const positions = useMemo(() =>
    items.map((_, i) => {
      const angle = -Math.PI / 2 + (i / N) * Math.PI * 2;
      return {
        angle,
        x: cx + Math.cos(angle) * rx,
        y: cy + Math.sin(angle) * ry,
        xPct: (cx + Math.cos(angle) * rx) / W * 100,
        yPct: (cy + Math.sin(angle) * ry) / H * 100,
      };
    }),
    [N]
  );

  return (
    <div className="diag-cnstl">
      <div className="cnstl-stage">
        <svg className="cnstl-svg" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet">
          <defs>
            <radialGradient id="coreGrad" cx="50%" cy="45%" r="60%">
              <stop offset="0%" stopColor="rgba(246,244,238,0.05)" />
              <stop offset="100%" stopColor="var(--ink)" />
            </radialGradient>
            <filter id="coreGlow">
              <feGaussianBlur stdDeviation="6" />
            </filter>
          </defs>

          {/* faint outer ring */}
          <ellipse cx={cx} cy={cy} rx={rx} ry={ry} className="cnstl-ring" />

          {/* connection lines */}
          {positions.map((p, i) => {
            const active = i < revealed;
            return (
              <g key={`l-${i}`} className={`cnstl-line ${active ? 'on' : ''} ${hover === i ? 'hot' : ''}`}>
                <line x1={cx} y1={cy} x2={p.x} y2={p.y} className="link" pathLength="1" />
                <line x1={cx} y1={cy} x2={p.x} y2={p.y} className="link-flow" pathLength="1" />
              </g>
            );
          })}

          {/* core glow */}
          <circle cx={cx} cy={cy} r="130" className="core-glow" />
          <circle cx={cx} cy={cy} r="118" className="core-fill" />
          <circle cx={cx} cy={cy} r="118" className="core-stroke" />
          <circle cx={cx} cy={cy} r="138" className="core-orbit" />

          {/* nodes */}
          {positions.map((p, i) => {
            if (i >= revealed) return null;
            return (
              <g key={`n-${i}`} className={`cnstl-node ${hover === i ? 'hot' : ''}`}>
                <circle cx={p.x} cy={p.y} r="14" className="node-halo" />
                <circle cx={p.x} cy={p.y} r="6" className="node-dot" />
              </g>
            );
          })}
        </svg>

        {/* HTML overlays */}
        <div className="cnstl-overlay">
          <div className="core-label">
            <span className="core-tag">We'd explore</span>
            <span className="core-name">{sol.title}</span>
            <span className="core-meta">for your {segment.title.toLowerCase()}</span>
          </div>

          {positions.map((p, i) => {
            if (i >= revealed) return null;
            const it = items[i];
            const isRight = Math.cos(p.angle) >= -0.1;
            const isTop = Math.sin(p.angle) < -0.2;
            const isBottom = Math.sin(p.angle) > 0.2;
            return (
              <div
                key={`o-${i}`}
                className={`cnstl-lbl ${isRight ? 'right' : 'left'} ${isTop ? 'top' : ''} ${isBottom ? 'bottom' : ''}`}
                style={{ left: `${p.xPct}%`, top: `${p.yPct}%` }}
                onMouseEnter={() => setHover(i)}
                onMouseLeave={() => setHover(null)}
              >
                <span className="lk">{it.k.replace(/_/g, ' ')}</span>
                <span className="lv">{it.v}</span>
              </div>
            );
          })}
        </div>
      </div>

      <div className="cnstl-progress" aria-hidden="true">
        <span>Discovery areas</span>
        <span className="bars">
          {Array.from({ length: N }, (_, i) => (
            <span key={i} className={i < revealed ? 'b on' : 'b'} />
          ))}
        </span>
        <span>{String(revealed).padStart(2, '0')} / {String(N).padStart(2, '0')}</span>
      </div>
    </div>
  );
}

// ============= DONE STAGE (completed step) =============
function DoneStage({ label, value, summary, onEdit }) {
  return (
    <div className="diag-stage done">
      <div className="stage-inner">
        <span className="done-label">{label}</span>
        <span className="done-value">{value}</span>
        {summary && <span className="done-summary">— {summary}</span>}
        <button className="done-edit" onClick={onEdit}>change</button>
      </div>
    </div>
  );
}

// ============= MAIN DIAGNOSTIC =============
function Diagnostic() {
  const [segmentId, setSegmentId] = useState(null);
  const [areaId, setAreaId] = useState(null);
  const [points, setPoints] = useState(new Set());
  const [picking, setPicking] = useState(null);
  const [step, setStep] = useState(1);
  const [customText, setCustomText] = useState('');
  const userEngagedRef = useRef(false);

  const segment = DIAG_SEGMENTS.find(s => s.id === segmentId);
  const areaList = segmentId ? (DIAG_SEGMENT_AREAS[segmentId] || []).map(id => ({ ...DIAG_AREAS[id], id })).filter(a => a.title) : [];
  const area = areaId ? DIAG_AREAS[areaId] : null;

  const stage1Ref = useRef(null);
  const stage2Ref = useRef(null);
  const stage3Ref = useRef(null);
  const stage4Ref = useRef(null);

  useEffect(() => {
    const refs = { 1: stage1Ref, 2: stage2Ref, 3: stage3Ref, 4: stage4Ref };
    const r = refs[step]?.current;
    if (!r || !userEngagedRef.current) return;
    setTimeout(() => {
      const y = r.getBoundingClientRect().top + window.scrollY - 56;
      window.scrollTo({ top: y, behavior: 'smooth' });
    }, 220);
  }, [step]);

  // -------- GA4 tracking helper --------
  const trackEvent = (eventName, params = {}) => {
    if (typeof gtag === 'function') {
      gtag('event', eventName, params);
    }
  };

  // -------- handlers --------
  const pickSegment = (id) => {
    userEngagedRef.current = true;
    setPicking(id);
    const seg = DIAG_SEGMENTS.find(s => s.id === id);
    trackEvent('diagnostic_segment_selected', {
      event_category: 'diagnostic',
      segment_id: id,
      segment_name: seg?.title || id
    });
    setTimeout(() => {
      setSegmentId(id);
      setAreaId(null);
      setPoints(new Set());
      setPicking(null);
      setStep(2);
    }, 900);
  };

  const pickArea = (id) => {
    userEngagedRef.current = true;
    setPicking(id);
    const areaData = DIAG_AREAS[id];
    trackEvent('diagnostic_area_selected', {
      event_category: 'diagnostic',
      segment_id: segmentId,
      area_id: id,
      area_name: areaData?.title || id
    });
    setTimeout(() => {
      setAreaId(id);
      setPoints(new Set());
      setCustomText('');
      setPicking(null);
      setStep(3);
    }, 900);
  };

  const togglePoint = (pid) => {
    setPoints(prev => {
      const next = new Set(prev);
      if (next.has(pid)) next.delete(pid); else next.add(pid);
      return next;
    });
  };

  const compile = () => {
    userEngagedRef.current = true;
    const selectedPoints = Array.from(points)
      .map(pid => area.points.find(p => p.id === pid)?.short)
      .filter(Boolean);
    trackEvent('diagnostic_completed', {
      event_category: 'diagnostic',
      segment_id: segmentId,
      segment_name: segment?.title,
      area_id: areaId,
      area_name: area?.title,
      pain_points_count: points.size,
      pain_points: selectedPoints.join(', ')
    });
    setStep(4);
  };

  const editSegment = () => { userEngagedRef.current = true; setStep(1); };
  const editArea = () => { userEngagedRef.current = true; setStep(2); };
  const editSignals = () => { userEngagedRef.current = true; setStep(3); };

  // -------- stages --------
  const renderStage1 = () => {
    if (step !== 1) {
      return (
        <div ref={stage1Ref}>
          <DoneStage
            label="Operation"
            value={segment?.title?.toLowerCase()}
            summary={segment?.blurb}
            onEdit={editSegment}
          />
        </div>
      );
    }
    return (
      <div className="diag-stage" ref={stage1Ref}>
        <div className="stage-inner">
          <h2 className="diag-headline">Let's find what's <em>broken</em>.</h2>
          <p className="diag-prompt">tap the one that fits</p>
          <BubbleField items={DIAG_SEGMENTS} picking={picking} onPick={pickSegment} variant="segment" />
        </div>
      </div>
    );
  };

  const renderStage2 = () => {
    if (step < 2) return null;
    if (step !== 2) {
      return (
        <div ref={stage2Ref}>
          <DoneStage
            label="Friction in"
            value={area?.title?.toLowerCase()}
            summary={area?.blurb}
            onEdit={editArea}
          />
        </div>
      );
    }
    return (
      <div className="diag-stage" ref={stage2Ref}>
        <div className="stage-inner">
          <h2 className="diag-headline">Where's the <em>friction</em> in your {segment?.title?.toLowerCase()}?</h2>
          <p className="diag-prompt">pick the area that hurts most</p>
          <BubbleField items={areaList} picking={picking} onPick={pickArea} variant="area" />
        </div>
      </div>
    );
  };

  const renderStage3 = () => {
    if (step < 3 || !area) return null;
    if (step !== 3) {
      const sels = Array.from(points).slice(0, 3).map(p => area.points.find(x => x.id === p)?.short).filter(Boolean);
      return (
        <div ref={stage3Ref}>
          <DoneStage
            label="Signals"
            value={`${points.size} captured`}
            summary={sels.join(' · ') + (points.size > 3 ? ` · +${points.size - 3} more` : '')}
            onEdit={editSignals}
          />
        </div>
      );
    }
    // Check if "Something else" is selected
    const hasOther = Array.from(points).some(pid => pid.startsWith('other_'));

    return (
      <div className="diag-stage" ref={stage3Ref}>
        <div className="stage-inner">
          <h2 className="diag-headline">What's <em>actually happening?</em></h2>
          <p className="diag-prompt">tap anything that resonates · multiple OK</p>
          <SignalBubbles items={area.points} selected={points} onToggle={togglePoint} />
          <CustomInputOrb
            value={customText}
            onChange={setCustomText}
            isVisible={hasOther}
          />
          {points.size > 0 && (
            <div className="diag-continue">
              <span className="arrow-stalk" />
              <button className="compile-btn" onClick={compile}>
                <span>See what we'd explore</span>
                <span className="count">[ {points.size} ]</span>
                <span className="arr">→</span>
              </button>
              <span className="compile-hint">we'll outline our approach</span>
            </div>
          )}
        </div>
      </div>
    );
  };

  const renderStage4 = () => {
    if (step < 4 || !area) return null;
    const sol = area.solution;
    const selectedPoints = Array.from(points)
      .map(pid => area.points.find(p => p.id === pid))
      .filter(Boolean);

    return (
      <div className="diag-stage diag-result-stage" ref={stage4Ref}>
        <div className="stage-inner">
          <div className="diag-result-meta">Based on your signals</div>

          <BuildConstellation sol={sol} segment={segment} />

          <p className="diag-result-summary">{sol.summary}</p>

          <div className="diag-approach">
            <div className="approach-label">— on a discovery call, we'd —</div>
            <ul className="approach-list">
              {sol.approach.map((step, i) => (
                <li key={i}>{step}</li>
              ))}
            </ul>
          </div>

          <div className="diag-result-actions">
            <button
              className="btn-primary"
              onClick={() => {
                const painPointNames = selectedPoints.map(p => p.short);
                const context = {
                  segment: segment.title,
                  area: area.title,
                  painPoints: painPointNames,
                  solution: sol.title
                };
                if (customText.trim()) {
                  context.customNote = customText.trim();
                }
                window.openCalendlyBooking(context);
              }}
            >
              <span>Book a discovery call</span>
              <span className="arr">→</span>
            </button>
            <button className="btn-ghost" onClick={() => {
              userEngagedRef.current = true;
              setStep(2);
              setPoints(new Set());
              setAreaId(null);
            }}>
              Explore another area
            </button>
            <button className="btn-ghost" onClick={() => {
              userEngagedRef.current = true;
              setSegmentId(null);
              setAreaId(null);
              setPoints(new Set());
              setStep(1);
              setTimeout(() => stage1Ref.current?.scrollIntoView({ behavior: 'smooth', block: 'start' }), 100);
            }}>
              Start over
            </button>
          </div>
        </div>
      </div>
    );
  };

  return (
    <section id="diagnostic" data-screen-label="Diagnostic">
      <div className="wrap">
        <div className="diag-section-num">
          <span className="live" /> 01 / Diagnostic
        </div>
        {renderStage1()}
        {renderStage2()}
        {renderStage3()}
        {renderStage4()}
      </div>
    </section>
  );
}

const diagRoot = ReactDOM.createRoot(document.getElementById('diagnostic-root'));
diagRoot.render(<Diagnostic />);
