// Live graph preview — static designed mock.
// 18 nodes, channel groupings, edges colored/styled by product.
// Slow ambient drift on nodes, slow pulse on a few "live" edges.

const CHANNEL_COLORS = {
  you:       { fill: '#15110E', stroke: '#15110E', text: '#FBF7F0' },
  direct:    { fill: '#FFE34D', stroke: '#15110E', text: '#15110E' },
  partner:   { fill: '#FF5C8A', stroke: '#15110E', text: '#FFFFFF' },
  ecosystem: { fill: '#E8E0FF', stroke: '#15110E', text: '#15110E' },
};

// product → edge color + dash
const PRODUCTS = {
  platform: { color: '#15110E', dash: 'none' },
  data:     { color: '#FF5C8A', dash: '4 4' },
  services: { color: '#2BB673', dash: '1 5' },
};

// Static layout, designed by hand to look balanced. Coords in a 1000×620 viewbox.
// channel: which group; r: radius
const NODES = [
  // YOU at center
  { id: 'you', label: 'You', x: 500, y: 310, r: 30, channel: 'you', sub: '' },

  // DIRECT cluster (top-left, yellow)
  { id: 'maya',   label: 'Maya Chen',     x: 230, y: 110, r: 22, channel: 'direct',    sub: 'Acme · CRO' },
  { id: 'omar',   label: 'Omar Reyes',    x: 130, y: 240, r: 20, channel: 'direct',    sub: 'Acme · VP Eng' },
  { id: 'lin',    label: 'Lin Zhao',      x: 280, y: 220, r: 18, channel: 'direct',    sub: 'Northwind' },
  { id: 'jen',    label: 'Jen Park',      x: 170, y: 380, r: 18, channel: 'direct',    sub: 'Halcyon' },
  { id: 'rafa',   label: 'Rafa Nuñez',    x: 90,  y: 360, r: 16, channel: 'direct',    sub: 'Halcyon · Ops' },

  // PARTNER cluster (top-right, coral)
  { id: 'sasha',  label: 'Sasha Iyer',    x: 770, y: 130, r: 22, channel: 'partner',   sub: 'Bridgepoint' },
  { id: 'devon',  label: 'Devon Hart',    x: 870, y: 250, r: 20, channel: 'partner',   sub: 'Bridgepoint · CS' },
  { id: 'ines',   label: 'Inés Moreau',   x: 720, y: 240, r: 18, channel: 'partner',   sub: 'Veridian' },
  { id: 'kai',    label: 'Kai Tanaka',    x: 920, y: 360, r: 18, channel: 'partner',   sub: 'Lattice Co.' },

  // ECOSYSTEM cluster (bottom, lavender)
  { id: 'priya',  label: 'Priya Shah',    x: 350, y: 510, r: 20, channel: 'ecosystem', sub: 'Foundry' },
  { id: 'tomas',  label: 'Tomás Vidal',   x: 480, y: 560, r: 18, channel: 'ecosystem', sub: 'Foundry · GTM' },
  { id: 'noor',   label: 'Noor Khalid',   x: 620, y: 540, r: 20, channel: 'ecosystem', sub: 'Cinder' },
  { id: 'eli',    label: 'Eli Brandt',    x: 760, y: 500, r: 18, channel: 'ecosystem', sub: 'Cinder · Dev' },
  { id: 'mira',   label: 'Mira Costa',    x: 240, y: 430, r: 16, channel: 'ecosystem', sub: 'Indigo Labs' },
  { id: 'wen',    label: 'Wen Liu',       x: 850, y: 440, r: 16, channel: 'ecosystem', sub: 'Northforge' },
  { id: 'arjun',  label: 'Arjun Mehta',   x: 410, y: 130, r: 16, channel: 'direct',    sub: 'Northwind · CFO' },
  { id: 'cleo',   label: 'Cleo Park',     x: 600, y: 130, r: 16, channel: 'partner',   sub: 'Veridian · BD' },
];

// Edges. Some emphasized = live pulse. weight = thickness (relationship age).
const EDGES = [
  // You → direct
  { from: 'you', to: 'maya',   product: 'platform', weight: 3.5, live: true },
  { from: 'you', to: 'omar',   product: 'platform', weight: 2.5 },
  { from: 'you', to: 'lin',    product: 'data',     weight: 2 },
  { from: 'you', to: 'jen',    product: 'platform', weight: 1.6 },
  { from: 'you', to: 'arjun',  product: 'data',     weight: 1.6 },

  // You → partner
  { from: 'you', to: 'sasha',  product: 'platform', weight: 3, live: true },
  { from: 'you', to: 'ines',   product: 'services', weight: 1.6 },
  { from: 'you', to: 'cleo',   product: 'data',     weight: 1.4 },

  // You → ecosystem
  { from: 'you', to: 'priya',  product: 'platform', weight: 2 },
  { from: 'you', to: 'noor',   product: 'services', weight: 1.4 },
  { from: 'you', to: 'mira',   product: 'data',     weight: 1.2 },

  // Internal direct
  { from: 'maya', to: 'omar',  product: 'platform', weight: 2.5 },
  { from: 'maya', to: 'arjun', product: 'platform', weight: 1.6 },
  { from: 'omar', to: 'lin',   product: 'data',     weight: 1.4 },
  { from: 'jen',  to: 'rafa',  product: 'platform', weight: 2 },
  { from: 'lin',  to: 'arjun', product: 'data',     weight: 1.4 },

  // Internal partner
  { from: 'sasha', to: 'devon', product: 'platform', weight: 2.5 },
  { from: 'sasha', to: 'ines',  product: 'services', weight: 1.6 },
  { from: 'devon', to: 'kai',   product: 'data',     weight: 1.4, live: true },
  { from: 'ines',  to: 'cleo',  product: 'platform', weight: 1.6 },

  // Internal ecosystem
  { from: 'priya', to: 'tomas', product: 'platform', weight: 2 },
  { from: 'noor',  to: 'eli',   product: 'services', weight: 2 },
  { from: 'priya', to: 'noor',  product: 'data',     weight: 1.4 },
  { from: 'eli',   to: 'wen',   product: 'platform', weight: 1.4 },
  { from: 'mira',  to: 'priya', product: 'data',     weight: 1.2 },

  // Cross-channel bridges (the magic)
  { from: 'lin',   to: 'priya', product: 'data',     weight: 1.2 },
  { from: 'sasha', to: 'cleo',  product: 'platform', weight: 1.6 },
  { from: 'kai',   to: 'wen',   product: 'data',     weight: 1.2 },
  { from: 'jen',   to: 'mira',  product: 'platform', weight: 1.4 },
  { from: 'devon', to: 'noor',  product: 'services', weight: 1.2, live: true },
];

function GraphPreview({ t }) {
  // Slow ambient drift — each node gets a tiny offset based on time + per-node phase
  const [tick, setTick] = React.useState(0);
  const [mode, setMode] = React.useState('poster'); // 'poster' | 'playing'
  const [teasing, setTeasing] = React.useState(false);
  const videoRef = React.useRef(null);
  const teaserRef = React.useRef(null);
  const frameRef = React.useRef(null);

  // Pause video when graph-frame leaves viewport (stay on video frame, don't auto-revert)
  React.useEffect(() => {
    if (mode !== 'playing' || !frameRef.current) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting && videoRef.current) videoRef.current.pause();
      });
    }, { threshold: 0.25 });
    io.observe(frameRef.current);
    return () => io.disconnect();
  }, [mode]);

  // Desktop hover teaser — only when prefers-reduced-motion: no-preference & not touch
  const canTease = React.useMemo(() => {
    if (typeof window === 'undefined') return false;
    const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const touch = window.matchMedia('(hover: none)').matches;
    return !reduce && !touch;
  }, []);

  const handlePosterEnter = () => {
    if (mode !== 'poster' || !canTease) return;
    setTeasing(true);
    const v = teaserRef.current;
    if (v) { v.currentTime = 0; v.play().catch(() => {}); window.setTimeout(() => { try { v.pause(); } catch(_){} }, 2000); }
  };
  const handlePosterLeave = () => {
    if (!teasing) return;
    setTeasing(false);
    if (teaserRef.current) { try { teaserRef.current.pause(); } catch(_){} }
  };

  const handlePlay = () => {
    setMode('playing');
    setTeasing(false);
    window.setTimeout(() => { videoRef.current?.play().catch(() => {}); }, 320);
  };
  const handleClose = () => {
    if (videoRef.current) { try { videoRef.current.pause(); } catch(_){} }
    setMode('poster');
  };
  React.useEffect(() => {
    let raf;
    const start = performance.now();
    const loop = (now) => {
      setTick((now - start) / 1000);
      raf = requestAnimationFrame(loop);
    };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  // Per-node drift offset — slow, small, distinct per node
  const drift = (id, idx) => {
    const seed = idx * 1.37;
    const dx = Math.sin(tick * 0.35 + seed) * 4;
    const dy = Math.cos(tick * 0.28 + seed * 1.3) * 3.5;
    return { dx, dy };
  };

  const nodeIndex = React.useMemo(() => {
    const m = {};
    NODES.forEach((n, i) => { m[n.id] = { ...n, idx: i }; });
    return m;
  }, []);

  const channels = ['direct', 'partner', 'ecosystem'];

  return (
    <div className="graph-wrap">
      <div
        className={`graph-frame graph-frame-${mode}`}
        ref={frameRef}
        onMouseEnter={handlePosterEnter}
        onMouseLeave={handlePosterLeave}
      >
        <div className="graph-bar">
          {mode === 'playing' && (
            <button
              type="button"
              className="graph-close"
              onClick={handleClose}
              aria-label="Close demo"
            >
              <svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true">
                <path d="M2 2 L10 10 M10 2 L2 10" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/>
              </svg>
            </button>
          )}
          <span className="graph-bar-dot" style={{background:'#FF5F57'}}></span>
          <span className="graph-bar-dot" style={{background:'#FFBD2E'}}></span>
          <span className="graph-bar-dot" style={{background:'#28CA42'}}></span>
          <span className="graph-bar-addr">connect.graph · {t.preview.legend.you.toLowerCase?.() || 'you'}</span>
          <span className="graph-bar-pulse">
            <span className="graph-bar-pulse-dot"></span>
            {t.hero.graph_caption}
          </span>
        </div>

        <svg className="graph-svg" viewBox="0 0 1000 620" preserveAspectRatio="xMidYMid meet">
          <defs>
            {/* soft channel halos */}
            <radialGradient id="halo-direct" cx="0.5" cy="0.5" r="0.5">
              <stop offset="0%" stopColor="#FFE34D" stopOpacity="0.45"></stop>
              <stop offset="100%" stopColor="#FFE34D" stopOpacity="0"></stop>
            </radialGradient>
            <radialGradient id="halo-partner" cx="0.5" cy="0.5" r="0.5">
              <stop offset="0%" stopColor="#FF5C8A" stopOpacity="0.32"></stop>
              <stop offset="100%" stopColor="#FF5C8A" stopOpacity="0"></stop>
            </radialGradient>
            <radialGradient id="halo-ecosystem" cx="0.5" cy="0.5" r="0.5">
              <stop offset="0%" stopColor="#E8E0FF" stopOpacity="0.7"></stop>
              <stop offset="100%" stopColor="#E8E0FF" stopOpacity="0"></stop>
            </radialGradient>
          </defs>

          {/* channel halos — give each cluster a soft watercolor */}
          <ellipse cx="195" cy="245" rx="230" ry="200" fill="url(#halo-direct)"></ellipse>
          <ellipse cx="800" cy="265" rx="220" ry="200" fill="url(#halo-partner)"></ellipse>
          <ellipse cx="500" cy="525" rx="380" ry="150" fill="url(#halo-ecosystem)"></ellipse>

          {/* channel labels */}
          <g className="graph-channel-label" fontFamily="'JetBrains Mono', monospace" fontSize="11" letterSpacing="0.12em" fill="#5C5550">
            <text x="60" y="60">DIRECT</text>
            <text x="900" y="60" textAnchor="end">PARTNER</text>
            <text x="500" y="610" textAnchor="middle">ECOSYSTEM</text>
          </g>

          {/* edges */}
          <g>
            {EDGES.map((e, i) => {
              const a = nodeIndex[e.from], b = nodeIndex[e.to];
              if (!a || !b) return null;
              const da = drift(a.id, a.idx);
              const db = drift(b.id, b.idx);
              const x1 = a.x + da.dx, y1 = a.y + da.dy;
              const x2 = b.x + db.dx, y2 = b.y + db.dy;
              const p = PRODUCTS[e.product];
              const dash = p.dash === 'none' ? undefined : p.dash;
              const baseOpacity = e.live ? 0.95 : 0.55;
              // Pulse for live edges: slow opacity wobble
              const opacity = e.live
                ? baseOpacity * (0.75 + 0.25 * Math.sin(tick * 1.6 + i))
                : baseOpacity;
              return (
                <line
                  key={i}
                  x1={x1} y1={y1} x2={x2} y2={y2}
                  stroke={p.color}
                  strokeWidth={e.weight}
                  strokeDasharray={dash}
                  strokeLinecap="round"
                  opacity={opacity}
                />
              );
            })}
          </g>

          {/* nodes */}
          <g>
            {NODES.map((n, i) => {
              const d = drift(n.id, i);
              const cx = n.x + d.dx, cy = n.y + d.dy;
              const c = CHANNEL_COLORS[n.channel];
              const isYou = n.id === 'you';
              return (
                <g key={n.id}>
                  {/* sticker shadow */}
                  <circle cx={cx + 2} cy={cy + 2} r={n.r} fill="#15110E" opacity="0.9"></circle>
                  <circle cx={cx} cy={cy} r={n.r} fill={c.fill} stroke={c.stroke} strokeWidth="1.5"></circle>
                  {isYou && (
                    <text x={cx} y={cy + 4} textAnchor="middle"
                          fontFamily="'Space Grotesk', system-ui, sans-serif"
                          fontWeight="700" fontSize="13" fill={c.text}
                          letterSpacing="-0.01em">
                      YOU
                    </text>
                  )}
                  {!isYou && (
                    <>
                      <text x={cx} y={cy + n.r + 14} textAnchor="middle"
                            fontFamily="'Space Grotesk', system-ui, sans-serif"
                            fontWeight="600" fontSize="12" fill="#15110E"
                            letterSpacing="-0.01em">
                        {n.label}
                      </text>
                      <text x={cx} y={cy + n.r + 27} textAnchor="middle"
                            fontFamily="'JetBrains Mono', monospace"
                            fontSize="9.5" fill="#5C5550" letterSpacing="0.02em">
                        {n.sub}
                      </text>
                    </>
                  )}
                </g>
              );
            })}
          </g>
        </svg>

        {/* legend overlay */}
        <div className="graph-legend">
          <div className="graph-legend-group">
            <div className="graph-legend-title">{t.preview.legend.channels}</div>
            <div className="graph-legend-row">
              <span className="graph-swatch" style={{background:'#15110E'}}></span>
              <span>{t.preview.legend.you}</span>
            </div>
            <div className="graph-legend-row">
              <span className="graph-swatch" style={{background:'#FFE34D', borderColor:'#15110E'}}></span>
              <span>{t.preview.legend.direct}</span>
            </div>
            <div className="graph-legend-row">
              <span className="graph-swatch" style={{background:'#FF5C8A', borderColor:'#15110E'}}></span>
              <span>{t.preview.legend.partner}</span>
            </div>
            <div className="graph-legend-row">
              <span className="graph-swatch" style={{background:'#E8E0FF', borderColor:'#15110E'}}></span>
              <span>{t.preview.legend.ecosystem}</span>
            </div>
          </div>
          <div className="graph-legend-group">
            <div className="graph-legend-title">{t.preview.legend.products}</div>
            <div className="graph-legend-row">
              <svg width="28" height="6"><line x1="0" y1="3" x2="28" y2="3" stroke="#15110E" strokeWidth="2.5"/></svg>
              <span>{t.preview.legend.platform}</span>
            </div>
            <div className="graph-legend-row">
              <svg width="28" height="6"><line x1="0" y1="3" x2="28" y2="3" stroke="#FF5C8A" strokeWidth="2.5" strokeDasharray="4 4"/></svg>
              <span>{t.preview.legend.data}</span>
            </div>
            <div className="graph-legend-row">
              <svg width="28" height="6"><line x1="0" y1="3" x2="28" y2="3" stroke="#2BB673" strokeWidth="2.5" strokeDasharray="1 4" strokeLinecap="round"/></svg>
              <span>{t.preview.legend.services}</span>
            </div>
          </div>
        </div>

        {/* desktop hover teaser — muted 2s loop layered over poster, only while teasing */}
        {canTease && (
          <video
            ref={teaserRef}
            className={`graph-teaser ${teasing && mode === 'poster' ? 'is-on' : ''}`}
            src="/connect-demo.mp4"
            muted
            playsInline
            loop
            preload="metadata"
            aria-hidden="true"
          />
        )}

        {/* play button overlay — visible only in poster mode */}
        {mode === 'poster' && (
          <button
            type="button"
            className="graph-play"
            onClick={handlePlay}
            aria-label={t.hero.playDemo || 'Play demo'}
          >
            <span className="graph-play-ring" aria-hidden="true"></span>
            <svg width="22" height="22" viewBox="0 0 22 22" aria-hidden="true">
              <path d="M6 3.5 L18 11 L6 18.5 Z" fill="#15110E"/>
            </svg>
          </button>
        )}

        {/* video — crossfades in over the SVG within the same chrome */}
        <video
          ref={videoRef}
          className={`graph-video ${mode === 'playing' ? 'is-on' : ''}`}
          src="/connect-demo.mp4"
          muted
          playsInline
          controls={mode === 'playing'}
          preload="metadata"
        />
      </div>
    </div>
  );
}

window.GraphPreview = GraphPreview;
