// Code samples: 4 stories with tabs and problem/approach/constraint structure

function Kw({ children }) { return <span style={{color:'#c58dff'}}>{children}</span>; }
function Ty({ children }) { return <span style={{color:'#7dcfff'}}>{children}</span>; }
function Fn({ children }) { return <span style={{color:'#ff6a3d'}}>{children}</span>; }
function Nm({ children }) { return <span style={{color:'#ff9e64'}}>{children}</span>; }

function CineCode() {
  const isMobile = useIsMobile();
  const px = isMobile ? '24px' : '56px';

  const samples = [
    {
      id: 'session',
      tab: 'NetworkedSession.cs',
      title: <>20 users,<br/><span style={{color: cine.accent}}>7 countries.</span></>,
      stack: ['Photon', 'C#', 'Reliable Ordered', 'Delta sync'],
      problem: 'Engineers in Chile, Canada, USA, Peru, Colombia, Mexico and Australia needed to collaborate on the same 3D bench in real time. Naïve full-state broadcasts crushed bandwidth and lagged on transcontinental links.',
      cause: 'Sending the whole world state on every tick is fine on LAN, fatal across the Atlantic. Out-of-order packets also kept overwriting newer state with older state.',
      fix: 'Tick-stamped delta sync over reliable-ordered channels. Each peer applies updates only if the tick is newer than its last seen tick, so late packets drop instead of corrupting the scene. State diffs reduced typical session traffic by ~85% across 20 concurrent users.',
      code: [
        ['c', '// broadcast only what changed this tick'],
        [null, <><Kw>public async</Kw> <Ty>Task</Ty> <Fn>BroadcastDelta</Fn>() {'{'}</>],
        [null, <>  <Ty>var</Ty> delta = _world.<Fn>DiffSinceTick</Fn>(_lastSentTick);</>],
        [null, <>  <Kw>if</Kw> (delta.IsEmpty) <Kw>return</Kw>;</>],
        [null, <>  delta.Tick = ++_lastSentTick;</>],
        [null, <>  <Kw>await</Kw> _hub.<Fn>Send</Fn>(delta, <Ty>Channel</Ty>.ReliableOrdered);</>],
        [null, '}'],
        [null, ''],
        ['c', '// drop stale packets, apply newer ones'],
        [null, <><Kw>public void</Kw> <Fn>OnPeerDelta</Fn>(<Ty>PeerDelta</Ty> delta) {'{'}</>],
        [null, <>  <Kw>if</Kw> (delta.Tick &lt;= _lastSeenTick[delta.PeerId])</>],
        [null, <>    <Kw>return</Kw>;</>],
        [null, <>  _world.<Fn>Apply</Fn>(delta);</>],
        [null, <>  _lastSeenTick[delta.PeerId] = delta.Tick;</>],
        [null, '}'],
      ],
    },
    {
      id: 'pipeline',
      tab: 'AssetImporter.cs',
      title: <>CAD into<br/><span style={{color: cine.accent}}>Unity, live.</span></>,
      stack: ['Unity', 'C#', 'OBJ · FBX · DXF · CAD', 'Streams'],
      problem: 'Geologists arrived with CSV survey rows, point clouds, DXF mine layouts, OBJ meshes from external tools and FBX from artists. Everything needed to live inside one Unity scene, round-trippable, without restarting the app.',
      cause: 'Each format has its own quirks (axis flips, units, winding order). Per-format ad-hoc importers turned into a maintenance hole.',
      fix: 'Single dispatch entry point that routes by extension, with shared post-processing (units → meters, Y-up, smooth normals) and an export inverse. Streams are read off the main thread so the UI never freezes on a 200MB mesh.',
      code: [
        [null, <><Kw>public async</Kw> <Ty>Task</Ty>&lt;<Ty>ImportedAsset</Ty>&gt; <Fn>Import</Fn>(<Ty>string</Ty> path) {'{'}</>],
        [null, <>  <Ty>string</Ty> ext = <Ty>Path</Ty>.<Fn>GetExtension</Fn>(path).<Fn>ToLower</Fn>();</>],
        [null, <>  <Ty>ImportedAsset</Ty> raw = ext <Kw>switch</Kw> {'{'}</>],
        [null, <>    <Nm>".obj"</Nm> =&gt; <Kw>await</Kw> <Fn>ParseObj</Fn>(path),</>],
        [null, <>    <Nm>".fbx"</Nm> =&gt; <Kw>await</Kw> <Fn>ParseFbx</Fn>(path),</>],
        [null, <>    <Nm>".dxf"</Nm> =&gt; <Kw>await</Kw> <Fn>ParseDxf</Fn>(path),</>],
        [null, <>    <Nm>".csv"</Nm> =&gt; <Kw>await</Kw> <Fn>ParseCsv</Fn>(path),</>],
        [null, <>    _    =&gt; <Kw>throw new</Kw> <Ty>NotSupportedException</Ty>(ext),</>],
        [null, '  };'],
        [null, ''],
        ['c', '  // normalize: meters, Y-up, recompute normals'],
        [null, <>  <Kw>return</Kw> <Fn>Normalize</Fn>(raw);</>],
        [null, '}'],
      ],
    },
    {
      id: 'cluster',
      tab: 'DiscontinuityClusterer.cs',
      title: <>Grouping<br/><span style={{color: cine.accent}}>rock by family.</span></>,
      stack: ['C#', 'Pattern recognition', 'Vector math', 'Stereonet'],
      problem: 'A mine bench can show hundreds of fractures with subtly different orientations. Geologists needed them grouped into structural families to reason about wedge failures and rockfall risk.',
      cause: 'Manual binning by dip/dip-direction is slow and human-biased. Angle-only comparisons also break across the ±180° pole flip.',
      fix: 'Cluster on the unit normal using absolute dot product so antiparallel normals collapse into the same family. New surfaces either join the closest family within tolerance or seed a new one. Families come out sorted by member count, ready for stereonet rendering.',
      code: [
        ['c', '// cluster discontinuities by orientation'],
        [null, <><Kw>foreach</Kw> (<Ty>var</Ty> d <Kw>in</Kw> discontinuities) {'{'}</>],
        [null, <>  <Ty>Family</Ty> best = <Kw>null</Kw>;</>],
        [null, <>  <Ty>float</Ty> bestScore = tolerance;</>],
        [null, ''],
        [null, <>  <Kw>foreach</Kw> (<Ty>var</Ty> f <Kw>in</Kw> _families) {'{'}</>],
        ['c', '    // |dot| handles antiparallel normals'],
        [null, <>    <Ty>float</Ty> s = <Ty>Mathf</Ty>.<Fn>Abs</Fn>(<Ty>Vector3</Ty>.<Fn>Dot</Fn>(f.Normal, d.Normal));</>],
        [null, <>    <Kw>if</Kw> (s &gt; bestScore) {'{'} best = f; bestScore = s; {'}'}</>],
        [null, '  }'],
        [null, ''],
        [null, <>  (best ?? <Fn>SeedNewFamily</Fn>(d.Normal)).<Fn>Add</Fn>(d);</>],
        [null, '}'],
        [null, ''],
        [null, <><Kw>return</Kw> _families.<Fn>OrderByDescending</Fn>(f =&gt; f.Count);</>],
      ],
    },
    {
      id: 'save',
      tab: 'AtomicSave.cs',
      title: <>No more<br/><span style={{color: cine.accent}}>corrupted saves.</span></>,
      stack: ['async/await', 'SemaphoreSlim', 'Atomic I/O', 'C#'],
      problem: 'Sessions hold heavy state — meshes, survey rows, sensor streams. File.WriteAllText on the main thread caused 40–80ms hitches and, worse, a crash mid-write left users with a half-written save.',
      cause: 'Synchronous I/O on the UI thread plus non-atomic file writes. Rapid saves also raced and landed out of order.',
      fix: 'Writes move to a background task, guarded by a SemaphoreSlim so only one save runs at a time. A CancellationTokenSource lets a newer save cancel the one in flight — last write wins. Atomic .tmp → rename guarantees the on-disk file is either the old version or the new one, never half of either.',
      code: [
        [null, <><Kw>public async</Kw> <Ty>Task</Ty> <Fn>SaveAsync</Fn>&lt;T&gt;(<Ty>string</Ty> slot, T data) {'{'}</>],
        ['c', '  // last write wins — cancel any prior'],
        [null, <>  _cts?.<Fn>Cancel</Fn>();</>],
        [null, <>  _cts = <Kw>new</Kw> <Ty>CancellationTokenSource</Ty>();</>],
        [null, ''],
        [null, <>  <Kw>await</Kw> _lock.<Fn>WaitAsync</Fn>(_cts.Token);</>],
        [null, '  try {'],
        [null, <>    <Ty>string</Ty> json = <Fn>JsonUtility.ToJson</Fn>(data);</>],
        [null, <>    <Kw>await</Kw> <Fn>WriteAtomicAsync</Fn>(<Fn>SlotPath</Fn>(slot), json, _cts.Token);</>],
        [null, '  }'],
        [null, <>  <Kw>finally</Kw> {'{'} _lock.<Fn>Release</Fn>(); {'}'}</>],
        [null, '}'],
      ],
    },
  ];

  const [active, setActive] = React.useState(0);
  const s = samples[active];

  return (
    <div id="code" style={{
      padding: isMobile ? '80px 0 80px' : '140px 0 140px',
      background: 'linear-gradient(180deg, #0a0a0c 0%, #050507 100%)',
      borderTop: `1px solid ${cine.line}`,
    }}>
      <CineSectionHead
        chapter="03 · Case studies"
        title={<>Code I actually<br/><span style={{color: cine.accent}}>wrote, & why.</span></>}
        meta={<>04 SYSTEMS<br/>PRODUCTION C#<br/>UNITY</>}
      />

      {/* tabs — horizontally scrollable on mobile */}
      <div style={{
        padding: `0 ${px}`, marginBottom: 48,
        overflowX: isMobile ? 'auto' : 'visible',
        WebkitOverflowScrolling: 'touch',
      }}>
        <div style={{
          display: 'flex', gap: 0,
          borderBottom: `1px solid ${cine.line}`,
          minWidth: isMobile ? 'max-content' : 'auto',
        }}>
          {samples.map((x, i) => (
            <div key={x.id} onClick={() => setActive(i)} style={{
              padding: isMobile ? '14px 16px' : '16px 24px',
              fontFamily: cine.mono,
              fontSize: isMobile ? 10 : 11,
              letterSpacing: 1.5,
              textTransform: 'uppercase',
              color: i === active ? cine.ink : cine.dim,
              cursor: 'pointer',
              borderBottom: i === active ? `2px solid ${cine.accent}` : '2px solid transparent',
              marginBottom: -1, transition: 'all 0.15s',
              whiteSpace: 'nowrap',
            }}>
              <span style={{ color: cine.accent, marginRight: 8 }}>0{i + 1}</span>
              {x.tab}
            </div>
          ))}
        </div>
      </div>

      {/* content — stacks on mobile */}
      <div style={{
        padding: `0 ${px}`, display: 'grid',
        gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr',
        gap: isMobile ? 40 : 56, alignItems: 'start',
      }}>
        <div>
          <h3 style={{
            fontFamily: cine.display, fontWeight: 500,
            fontSize: isMobile ? 36 : 56,
            letterSpacing: isMobile ? -0.5 : -1.5,
            margin: '0 0 44px', lineHeight: 0.98,
            color: cine.ink,
          }}>{s.title}</h3>

          {[['The symptom', s.problem], ['The cause', s.cause], ['The fix', s.fix]].map(([k, v]) => (
            <div key={k} style={{ marginBottom: 32 }}>
              <div style={{
                display: 'inline-block', padding: '6px 12px',
                background: cine.accentSoft, color: cine.accent,
                fontFamily: cine.mono, fontSize: 10, letterSpacing: 1.5,
                textTransform: 'uppercase', marginBottom: 16,
              }}>{k}</div>
              <p style={{
                margin: 0, fontFamily: cine.body,
                fontSize: isMobile ? 14 : 16.5,
                lineHeight: 1.65, color: cine.ink2,
              }}>{v}</p>
            </div>
          ))}

          <div style={{
            marginTop: 32, paddingTop: 24,
            borderTop: `1px solid ${cine.line}`,
            display: 'flex', gap: 8, flexWrap: 'wrap',
          }}>
            {s.stack.map(t => (
              <span key={t} style={{
                fontFamily: cine.mono, fontSize: 10, letterSpacing: 1.5,
                padding: '6px 10px', border: `1px solid ${cine.line}`,
                color: cine.dim, textTransform: 'uppercase',
              }}>{t}</span>
            ))}
          </div>
        </div>

        {/* code block */}
        <div style={{
          background: cine.bgDeep, border: `1px solid ${cine.line}`,
          position: 'relative', overflow: 'hidden',
        }}>
          <div style={{
            display: 'flex', alignItems: 'center',
            padding: '14px 18px',
            borderBottom: `1px solid ${cine.line}`,
            background: 'rgba(255,255,255,0.02)',
          }}>
            <div style={{ display: 'flex', gap: 6 }}>
              <span style={dot('#3a3a3a')}/><span style={dot('#3a3a3a')}/>
              <span style={dot(cine.accent, 0.55)}/>
            </div>
            <div style={{
              marginLeft: 'auto', fontFamily: cine.mono, fontSize: 10,
              color: cine.dim, letterSpacing: 2,
            }}>{s.tab}</div>
          </div>
          <pre style={{
            margin: 0, padding: '24px 28px',
            fontFamily: cine.mono,
            fontSize: isMobile ? 11 : 13.2,
            lineHeight: 1.75,
            color: cine.ink, whiteSpace: 'pre-wrap',
            overflowX: 'auto',
          }}>
            {s.code.map(([kind, line], i) => (
              <div key={i} style={{
                color: kind === 'c' ? cine.dim : cine.ink,
                minHeight: '1.75em',
              }}>{line}</div>
            ))}
          </pre>
        </div>
      </div>
    </div>
  );
}

function dot(color, op = 1) {
  return { width: 10, height: 10, borderRadius: '50%', background: color, opacity: op };
}
window.CineCode = CineCode;
