// Part 2, "How TGM works": pinned, scroll-scrubbed story.
// Phase 1 INGEST  ->  Phase 2 CHUNK  ->  Phase 3 CONNECT (knowledge graph)
// Dark, premium restyle that continues the hero's living-graph aesthetic.
const { useEffect: useEffectSS, useRef: useRefSS, useState: useStateSS } = React;

gsap.registerPlugin(ScrollTrigger);

// Brand candy palette, matches the hero knowledge-graph background
const TGM_C = { code: '#6E9BFF', docs: '#3FE0AE', res: '#B49BFF', more: '#FF6FB0' };

function ScrollSection() {
    const sectionRef = useRefSS(null);

    const step1LabelRef = useRefSS(null);
    const step1CardsRef = useRefSS([]);
    const step2LabelRef = useRefSS(null);
    const step3LabelRef = useRefSS(null);

    const canvasRef = useRefSS(null);
    const morphNodesRef = useRefSS([]);
    const dotContainersRef = useRefSS([]);

    // Step-rail elements driven imperatively (no re-render during scroll)
    const railItemsRef = useRefSS([]);
    const railFillRef = useRefSS(null);
    const activeStepRef = useRefSS(0);

    const [canvasSize, setCanvasSize] = useStateSS({ width: 512, height: 460 });
    const [navHeight, setNavHeight] = useStateSS(80);
    const canvasSizeRef = useRefSS({ width: 512, height: 460 });

    useEffectSS(() => {
        const updateNav = () => {
            const nav = document.querySelector('nav');
            if (nav) setNavHeight(nav.offsetHeight);
        };
        updateNav();
        window.addEventListener('resize', updateNav);

        if (canvasRef.current) {
            const ro = new ResizeObserver(entries => {
                for (let entry of entries) {
                    const newSize = { width: entry.contentRect.width, height: entry.contentRect.height };
                    setCanvasSize(newSize);
                    canvasSizeRef.current = newSize;
                    ScrollTrigger.refresh();
                }
            });
            ro.observe(canvasRef.current);
            return () => {
                window.removeEventListener('resize', updateNav);
                ro.disconnect();
            };
        }
    }, []);

    const steps = [
        { n: '01', tag: 'Ingest', title: 'Ingest your data', desc: 'One API call. Text and markdown in; other formats convert during onboarding.' },
        { n: '02', tag: 'Chunk', title: 'Split into passages', desc: 'Sentence-level passages that keep their exact bytes. No schema, no tagging.' },
        { n: '03', tag: 'Connect', title: 'Build the graph', desc: 'Passages link by meaning. Search in ~22 ms, about half a second end-to-end.' }
    ];

    const categories = [
        { label: 'Code', icon: Code, color: TGM_C.code, chunks: ['auth.py', 'router.py', '...', 'models.py'] },
        { label: 'Docs', icon: FileText, color: TGM_C.docs, chunks: ['contract.md', 'policy.md', '...', 'handbook.md'] },
        { label: 'Research', icon: FlaskConical, color: TGM_C.res, chunks: ['study.pdf', 'results.pdf', '...', 'review.pdf'] }
    ];

    const baseNodes = [
        { cx: 0.10, cy: 0.16, color: TGM_C.code, label: 'auth.py' },
        { cx: 0.09, cy: 0.50, color: TGM_C.code, label: 'router.py' },
        { cx: 0.16, cy: 0.84, color: TGM_C.code, label: 'models.py' },
        { cx: 0.46, cy: 0.12, color: TGM_C.docs, label: 'contract.md' },
        { cx: 0.52, cy: 0.46, color: TGM_C.docs, label: 'policy.md' },
        { cx: 0.44, cy: 0.82, color: TGM_C.docs, label: 'handbook.md' },
        { cx: 0.84, cy: 0.18, color: TGM_C.res, label: 'study.pdf' },
        { cx: 0.88, cy: 0.54, color: TGM_C.res, label: 'results.pdf' },
        { cx: 0.80, cy: 0.86, color: TGM_C.res, label: 'review.pdf' }
    ];

    const baseEdges = [
        { n1: 0, n2: 3, color: TGM_C.code },
        { n1: 1, n2: 4, color: TGM_C.code },
        { n1: 2, n2: 5, color: TGM_C.code },
        { n1: 3, n2: 6, color: TGM_C.docs },
        { n1: 4, n2: 7, color: TGM_C.docs },
        { n1: 5, n2: 8, color: TGM_C.docs },
        { n1: 0, n2: 1, color: TGM_C.code },
        { n1: 3, n2: 4, color: TGM_C.docs },
        { n1: 7, n2: 8, color: TGM_C.res },
        { n1: 1, n2: 3, color: TGM_C.docs },
        { n1: 4, n2: 8, color: TGM_C.res }
    ];

    const graphNodes = baseNodes.map(n => ({
        cx: n.cx * canvasSize.width,
        cy: n.cy * canvasSize.height,
        left: (n.cx * canvasSize.width) - 24,
        top: (n.cy * canvasSize.height) - 24,
        color: n.color,
        label: n.label
    }));

    const edges = baseEdges.map(e => {
        const x1 = graphNodes[e.n1].cx, y1 = graphNodes[e.n1].cy;
        const x2 = graphNodes[e.n2].cx, y2 = graphNodes[e.n2].cy;
        // gentle curve: perpendicular offset on the midpoint
        const mx = (x1 + x2) / 2, my = (y1 + y2) / 2;
        const dx = x2 - x1, dy = y2 - y1;
        const len = Math.hypot(dx, dy) || 1;
        const off = Math.min(len * 0.12, 26);
        return { x1, y1, x2, y2, qx: mx + (-dy / len) * off, qy: my + (dx / len) * off, color: e.color };
    });

    const getInitialPositionPercent = (colIndex, itemIndex) => {
        const left = `${6 + colIndex * 34}%`;
        let top = '4%';
        if (itemIndex === 1) top = '24%';
        else if (itemIndex === 2) top = '44%';
        else if (itemIndex === 3) top = '58%';
        return { left, top };
    };

    const setActiveStep = (idx) => {
        if (activeStepRef.current === idx) return;
        activeStepRef.current = idx;
        railItemsRef.current.forEach((el, i) => {
            if (!el) return;
            el.classList.toggle('active', i === idx);
            el.classList.toggle('done', i < idx);
        });
    };

    useEffectSS(() => {
        const tl = gsap.timeline({
            scrollTrigger: {
                trigger: sectionRef.current,
                start: 'top top',
                end: '+=120%',
                scrub: 0.4,
                pin: true,
                anticipatePin: 1,
                invalidateOnRefresh: true,
                onUpdate: (self) => {
                    const p = self.progress;
                    if (railFillRef.current) railFillRef.current.style.height = `${Math.min(100, p * 100)}%`;
                    setActiveStep(p < 0.17 ? 0 : (p < 0.5 ? 1 : 2));
                }
            }
        });

        gsap.set(step2LabelRef.current, { y: 16, opacity: 0 });
        gsap.set(canvasRef.current, { y: 14, opacity: 0 });
        gsap.set(step3LabelRef.current, { y: 16, opacity: 0 });

        // Phase 1 -> 2
        tl.to(step1LabelRef.current, { opacity: 0, y: -18, duration: 0.5, ease: 'power2.inOut' }, 0);
        tl.to(step1CardsRef.current, { opacity: 0, y: -18, scale: 0.92, duration: 0.8, stagger: 0.1, ease: 'power2.inOut' }, 0);

        tl.to(step2LabelRef.current, { opacity: 1, y: 0, duration: 0.5, ease: 'power2.out' }, 0.5);
        tl.to(canvasRef.current, { opacity: 1, y: 0, duration: 0.5, ease: 'power2.out' }, 0.5);

        tl.fromTo(morphNodesRef.current.concat(dotContainersRef.current),
            { opacity: 0, y: 14 },
            { opacity: 1, y: 0, duration: 0.6, stagger: 0.05, ease: 'power2.out' },
            0.6);

        // Phase 2 -> 3
        const step3Start = 1.6;

        tl.to(step2LabelRef.current, { opacity: 0, y: -18, duration: 0.4 }, step3Start);
        tl.to(step3LabelRef.current, { opacity: 1, y: 0, duration: 0.4 }, step3Start + 0.2);

        // stage gains a soft glowing frame (stays dark)
        tl.to(canvasRef.current, {
            backgroundColor: 'rgba(255,255,255,0.025)',
            borderColor: 'rgba(123,92,255,0.28)',
            boxShadow: '0 0 60px rgba(123,92,255,0.16), inset 0 0 60px rgba(123,92,255,0.05)',
            duration: 0.6,
            ease: 'power2.inOut'
        }, step3Start);

        tl.to(dotContainersRef.current, { opacity: 0, duration: 0.3 }, step3Start);
        tl.to('.chunk-text-wrapper', { opacity: 0, duration: 0.3 }, step3Start);

        tl.to(morphNodesRef.current, {
            width: () => window.innerWidth < 768 ? '36px' : '48px',
            height: () => window.innerWidth < 768 ? '36px' : '48px',
            borderRadius: 10,
            backgroundColor: (i, el) => el.dataset.color,
            borderColor: 'transparent',
            boxShadow: (i, el) => `0 0 18px ${el.dataset.color}`,
            duration: 0.4,
            ease: 'power2.out'
        }, step3Start + 0.1);

        tl.to('.chunk-icon-wrapper', { opacity: 1, duration: 0.3 }, step3Start + 0.3);

        morphNodesRef.current.forEach((node, i) => {
            tl.to(node, {
                top: () => (baseNodes[i].cy * canvasSizeRef.current.height) - (window.innerWidth < 768 ? 18 : 24),
                left: () => (baseNodes[i].cx * canvasSizeRef.current.width) - (window.innerWidth < 768 ? 18 : 24),
                duration: 0.6,
                ease: 'power2.inOut'
            }, step3Start + 0.5 + (i * 0.05));
        });

        tl.to('.graph-path', { strokeDashoffset: 0, duration: 0.4, stagger: 0.08, ease: 'power1.inOut' }, step3Start + 1.2);
        tl.to('.node-label', { opacity: 1, y: 0, duration: 0.4, stagger: 0.05, ease: 'power2.out' }, step3Start + 1.4);

        return () => ScrollTrigger.getAll().forEach(t => t.kill());
    }, []);

    return (
        <>
            <style>{`
            .tgm2 {
                position: relative;
                width: 100vw;
                height: 100vh;
                overflow: hidden;
                box-sizing: border-box;
                background:
                    radial-gradient(110% 80% at 18% 0%, rgba(123,92,255,0.14), transparent 55%),
                    radial-gradient(90% 70% at 100% 100%, rgba(63,224,174,0.10), transparent 55%),
                    linear-gradient(180deg, #07070f 0%, #0a0a16 100%);
                display: flex;
                flex-direction: column;
                align-items: center;
                padding: 84px 0 56px;
            }
            /* faint grid + top/bottom fades to blend with neighbours */
            .tgm2::before {
                content: '';
                position: absolute; inset: 0;
                background-image:
                    linear-gradient(rgba(255,255,255,0.035) 1px, transparent 1px),
                    linear-gradient(90deg, rgba(255,255,255,0.035) 1px, transparent 1px);
                background-size: 46px 46px;
                mask-image: radial-gradient(120% 90% at 50% 30%, #000 35%, transparent 80%);
                -webkit-mask-image: radial-gradient(120% 90% at 50% 30%, #000 35%, transparent 80%);
                pointer-events: none;
            }
            .tgm2::after {
                content: '';
                position: absolute; left: 0; right: 0; top: 0; height: 120px;
                background: linear-gradient(180deg, #06060e, transparent);
                pointer-events: none;
            }

            .tgm2-head {
                position: relative; z-index: 2;
                text-align: center;
                margin-bottom: 54px;
                padding: 0 24px;
            }
            .tgm2-eyebrow {
                font-size: 12px; font-weight: 600; letter-spacing: 0.28em;
                text-transform: uppercase;
                color: #9b8bff;
                margin-bottom: 14px;
            }
            .tgm2-title {
                font-family: 'Bricolage Grotesque', sans-serif;
                font-weight: 700;
                font-size: clamp(30px, 4.4vw, 56px);
                line-height: 1.04;
                letter-spacing: -0.03em;
                color: #fff;
                margin: 0;
            }
            .tgm2-title .accent {
                background: linear-gradient(100deg, #7b5cff, #6e9bff 45%, #3fe0ae);
                -webkit-background-clip: text; background-clip: text; color: transparent;
            }

            .tgm2-cols {
                position: relative; z-index: 2;
                display: flex;
                width: 100%;
                max-width: 1180px;
                margin: 0 auto;
                padding: 0 32px;
                box-sizing: border-box;
                flex: 1;
                gap: 56px;
                min-height: 0;
            }

            /* ---- Left: step rail ---- */
            .tgm2-rail {
                width: 38%;
                min-width: 280px;
                position: sticky;
                top: ${navHeight + 28}px;
                height: fit-content;
                padding-left: 28px;
            }
            .rail-track {
                position: absolute; left: 7px; top: 8px; bottom: 8px; width: 2px;
                background: rgba(255,255,255,0.10);
                border-radius: 2px; overflow: hidden;
            }
            .rail-fill {
                position: absolute; left: 0; top: 0; width: 100%; height: 0%;
                background: linear-gradient(180deg, #7b5cff, #3fe0ae);
                box-shadow: 0 0 12px rgba(123,92,255,0.6);
                transition: height 0.12s linear;
            }
            .rail-item {
                position: relative;
                padding: 0 0 38px 0;
                opacity: 0.42;
                transition: opacity 0.4s ease, transform 0.4s ease;
            }
            .rail-item:last-child { padding-bottom: 0; }
            .rail-item.active { opacity: 1; }
            .rail-item.done { opacity: 0.62; }
            .rail-dot {
                position: absolute; left: -28px; top: 2px;
                width: 16px; height: 16px; border-radius: 50%;
                background: #0a0a16; border: 2px solid rgba(255,255,255,0.22);
                box-sizing: border-box;
                transition: all 0.4s ease;
            }
            .rail-item.active .rail-dot {
                border-color: #7b5cff;
                background: #7b5cff;
                box-shadow: 0 0 0 5px rgba(123,92,255,0.18), 0 0 16px rgba(123,92,255,0.7);
            }
            .rail-item.done .rail-dot { border-color: #3fe0ae; background: #3fe0ae; }
            .rail-kicker {
                display: inline-flex; align-items: baseline; gap: 10px;
                margin-bottom: 9px;
            }
            .rail-num {
                font-family: 'JetBrains Mono', monospace;
                font-size: 12px; font-weight: 600; letter-spacing: 0.1em;
                color: #6e9bff;
            }
            .rail-tag {
                font-family: 'JetBrains Mono', monospace;
                font-size: 11px; font-weight: 600; letter-spacing: 0.24em;
                text-transform: uppercase; color: rgba(255,255,255,0.5);
            }
            .rail-title {
                font-family: 'Bricolage Grotesque', sans-serif;
                font-size: clamp(19px, 1.8vw, 24px); font-weight: 600;
                color: #fff; margin: 0 0 8px 0; letter-spacing: -0.01em;
            }
            .rail-desc {
                font-family: 'Hanken Grotesk', sans-serif;
                font-size: 14.5px; line-height: 1.6;
                color: rgba(255,255,255,0.62); margin: 0; max-width: 380px;
            }

            /* ---- Right: stage ---- */
            .tgm2-stage {
                width: 62%; min-width: 320px;
                position: relative; height: 100%;
            }
            .stage-label {
                font-family: 'JetBrains Mono', monospace;
                font-size: 12px; font-weight: 600; letter-spacing: 0.2em;
                text-transform: uppercase; color: #9b8bff;
                margin-bottom: 26px;
            }
            .src-card {
                width: clamp(116px, 27%, 158px);
                aspect-ratio: 1 / 1;
                background: rgba(255,255,255,0.04);
                border-radius: 18px;
                display: flex; flex-direction: column; align-items: center; justify-content: center;
                gap: 14px;
                backdrop-filter: blur(8px);
                -webkit-backdrop-filter: blur(8px);
            }
            .src-card .src-name {
                font-family: 'Hanken Grotesk', sans-serif;
                font-weight: 600; font-size: 15px; color: #fff;
            }
            .step2-chunk {
                width: clamp(132px, 30%, 188px);
                height: 46px;
            }
            .tgm-canvas {
                width: 100%;
                min-height: 420px;
                aspect-ratio: 1.2 / 1;
                margin-top: 0;
            }

            @media (max-width: 920px) {
                .tgm2 { height: auto; min-height: 100vh; padding-top: 96px; }
                .tgm2-cols { flex-direction: column; gap: 40px; }
                .tgm2-rail { position: relative; top: 0 !important; width: 100%; min-width: 0; }
                .tgm2-stage { width: 100%; min-width: 0; }
            }
            `}</style>

            <section ref={sectionRef} id="how-it-works" data-screen-label="How It Works" className="tgm2">

                <div className="tgm2-head">
                    <div className="tgm2-eyebrow">How it works</div>
                    <h2 className="tgm2-title">
                        From scattered files to <span className="accent">living memory</span>
                    </h2>
                </div>

                <div className="tgm2-cols">

                    {/* LEFT, step rail */}
                    <div className="tgm2-rail">
                        <div className="rail-track"><div ref={railFillRef} className="rail-fill"></div></div>
                        {steps.map((s, i) => (
                            <div key={s.n} ref={el => railItemsRef.current[i] = el} className={`rail-item ${i === 0 ? 'active' : ''}`}>
                                <span className="rail-dot"></span>
                                <span className="rail-kicker">
                                    <span className="rail-num">{s.n}</span>
                                    <span className="rail-tag">{s.tag}</span>
                                </span>
                                <h3 className="rail-title">{s.title}</h3>
                                <p className="rail-desc">{s.desc}</p>
                            </div>
                        ))}
                    </div>

                    {/* RIGHT, stage */}
                    <div className="tgm2-stage">

                        {/* Phase 1: INGEST */}
                        <div style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
                            <div ref={step1LabelRef} className="stage-label">Ingest any source</div>
                            <div style={{ display: 'flex', gap: 'clamp(8px, 2%, 16px)', width: '100%' }}>
                                {categories.map((cat, i) => {
                                    const Icon = cat.icon;
                                    return (
                                        <div key={cat.label} ref={el => step1CardsRef.current[i] = el}
                                            className="src-card"
                                            style={{ border: `1.5px solid ${cat.color}55`, boxShadow: `0 8px 30px ${cat.color}22, inset 0 0 24px ${cat.color}10` }}>
                                            <Icon size={42} strokeWidth={1.5} color={cat.color} />
                                            <span className="src-name">{cat.label}</span>
                                        </div>
                                    );
                                })}
                                <div ref={el => step1CardsRef.current[categories.length] = el}
                                    className="src-card"
                                    style={{ border: `1.5px dashed ${TGM_C.more}66`, boxShadow: `0 8px 30px ${TGM_C.more}1f` }}>
                                    <Plus size={42} strokeWidth={1.5} color={TGM_C.more} />
                                    <span className="src-name">More</span>
                                </div>
                            </div>
                        </div>

                        {/* Phases 2 & 3 */}
                        <div style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', display: 'flex', flexDirection: 'column', pointerEvents: 'none' }}>
                            <div style={{ position: 'relative', height: '18px', marginBottom: '26px' }}>
                                <div ref={step2LabelRef} className="stage-label" style={{ position: 'absolute', top: 0, left: 0, marginBottom: 0 }}>Split into semantic chunks</div>
                                <div ref={step3LabelRef} className="stage-label" style={{ position: 'absolute', top: 0, left: 0, marginBottom: 0 }}>One connected knowledge graph</div>
                            </div>

                            <div ref={canvasRef} className="tgm-canvas" style={{
                                position: 'relative',
                                background: 'transparent', border: '1px solid transparent', borderRadius: '20px', pointerEvents: 'auto'
                            }}>
                                <svg style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', pointerEvents: 'none', zIndex: 0, overflow: 'visible' }}>
                                    {edges.map((edge, i) => (
                                        <path
                                            key={`edge-${i}`}
                                            className="graph-path"
                                            d={`M ${edge.x1} ${edge.y1} Q ${edge.qx} ${edge.qy} ${edge.x2} ${edge.y2}`}
                                            fill="none"
                                            stroke={edge.color}
                                            strokeWidth="1.5"
                                            strokeDasharray="1200"
                                            strokeDashoffset="1200"
                                            opacity="0.55"
                                            style={{ filter: `drop-shadow(0 0 4px ${edge.color}aa)` }}
                                        ></path>
                                    ))}
                                </svg>

                                {categories.map((cat, colIndex) => (
                                    <div key={cat.label} style={{ width: '100%', position: 'absolute' }}>
                                        {cat.chunks.map((chunk, itemIndex) => {
                                            const { left, top } = getInitialPositionPercent(colIndex, itemIndex);
                                            const Icon = cat.icon;

                                            if (chunk === '...') {
                                                const dIdx = colIndex;
                                                return (
                                                    <div key={`dots-${colIndex}`} ref={el => dotContainersRef.current[dIdx] = el}
                                                        style={{ position: 'absolute', left, top, width: '30%', height: '24px', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: '6px' }}>
                                                        <div style={{ width: '4px', height: '4px', borderRadius: '50%', backgroundColor: 'rgba(255,255,255,0.35)' }}></div>
                                                        <div style={{ width: '4px', height: '4px', borderRadius: '50%', backgroundColor: 'rgba(255,255,255,0.35)' }}></div>
                                                        <div style={{ width: '4px', height: '4px', borderRadius: '50%', backgroundColor: 'rgba(255,255,255,0.35)' }}></div>
                                                    </div>
                                                );
                                            }

                                            const nIdx = colIndex * 3 + (itemIndex > 2 ? itemIndex - 1 : itemIndex);
                                            return (
                                                <div key={chunk} style={{ position: 'absolute', left: 0, top: 0, width: '100%', height: '100%' }}>
                                                    <div ref={el => morphNodesRef.current[nIdx] = el} data-color={cat.color}
                                                        className="step2-chunk"
                                                        style={{
                                                            position: 'absolute', left, top,
                                                            background: 'rgba(255,255,255,0.05)', border: `1.5px solid ${cat.color}88`, borderRadius: '10px',
                                                            boxSizing: 'border-box', overflow: 'hidden', zIndex: 5,
                                                            backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)'
                                                        }}>
                                                        <div className="chunk-text-wrapper font-mono" style={{
                                                            position: 'absolute', top: 0, left: 0, width: '100%', height: '100%',
                                                            display: 'flex', alignItems: 'center', padding: '0 12px', boxSizing: 'border-box',
                                                            color: 'rgba(255,255,255,0.86)', fontSize: '12px', fontWeight: 500
                                                        }}>
                                                            <div style={{ width: '6px', height: '6px', borderRadius: '50%', backgroundColor: cat.color, marginRight: '9px', flexShrink: 0, boxShadow: `0 0 8px ${cat.color}` }}></div>
                                                            {chunk}
                                                        </div>
                                                        <div className="chunk-icon-wrapper" style={{
                                                            position: 'absolute', top: 0, left: 0, width: '100%', height: '100%',
                                                            display: 'flex', alignItems: 'center', justifyContent: 'center', opacity: 0
                                                        }}>
                                                            <Icon size={20} color="#0a0a16" style={{ width: 'clamp(14px, 1.8vw, 20px)' }} />
                                                        </div>
                                                    </div>

                                                    <div className="node-label font-mono" style={{
                                                        position: 'absolute',
                                                        left: graphNodes[nIdx].cx,
                                                        top: graphNodes[nIdx].cy + 32,
                                                        transform: 'translateX(-50%)',
                                                        color: 'rgba(255,255,255,0.5)',
                                                        fontSize: 'clamp(9px, 0.8vw, 11px)',
                                                        whiteSpace: 'nowrap',
                                                        opacity: 0
                                                    }}>
                                                        {graphNodes[nIdx].label}
                                                    </div>
                                                </div>
                                            );
                                        })}
                                    </div>
                                ))}
                            </div>
                        </div>

                    </div>
                </div>
            </section>
        </>
    );
}

Object.assign(window, { ScrollSection });
