import { useState, useMemo } from 'react'
import { Tooltip } from './shared/Tooltip'
import { TooltipType } from './shared/tooltipDefinitions'
import type { TraceEvent } from '../../types/trace'

interface RequestDebuggerProps {
  traceEvents: TraceEvent[]
}

interface HTTPRequestEvents {
  sendRequest?: TraceEvent
  receiveResponse?: TraceEvent
  receivedData: TraceEvent[]
  finishLoading?: TraceEvent
  willSendRequest?: TraceEvent
  didReceiveResponse?: TraceEvent
  didFinishLoading?: TraceEvent
  didFailLoading?: TraceEvent
  resourceChangedPriority?: TraceEvent
  resourceChangePriority?: TraceEvent
  resourceMarkAsCached?: TraceEvent
  preloadRenderBlockingStatusChange?: TraceEvent
  // Navigation events
  navigationRequest?: TraceEvent[]
  willStartRequest?: TraceEvent[]
  willProcessResponse?: TraceEvent[]
  didCommitNavigation?: TraceEvent
  // URL Loader events
  throttlingURLLoader?: TraceEvent[]
  urlLoaderStart?: TraceEvent[]
  onReceiveResponse?: TraceEvent[]
  onRequestComplete?: TraceEvent[]
  onReceivedRedirect?: TraceEvent[]
  // Connection events
  connection?: TraceEvent[]
  keepAliveURLLoader?: TraceEvent[]
  // V8 and parsing events
  parseOnBackground?: TraceEvent[]
  compile?: TraceEvent[]
  evaluateScript?: TraceEvent[]
  other: TraceEvent[]
}

export default function RequestDebugger({ traceEvents }: RequestDebuggerProps) {
  const [selectedRequestId, setSelectedRequestId] = useState<string>('')
  const [searchUrl, setSearchUrl] = useState<string>('')

  // Extract all unique request IDs and URLs
  const requestData = useMemo(() => {
    const requests = new Map<string, { id: string; url: string; events: HTTPRequestEvents }>()
    const urlToRequestId = new Map<string, string[]>()

    // First pass: collect all request IDs and basic events (only by requestId matching)
    traceEvents.forEach(event => {
      const args = event.args as any
      const requestId = args?.data?.requestId || args?.requestId
      const url = args?.data?.url

      if (requestId) {
        // Only track requests that have requestId (ignore URL-only matching)
        if (url && !urlToRequestId.has(url)) {
          urlToRequestId.set(url, [])
        }
        if (url && !urlToRequestId.get(url)!.includes(requestId)) {
          urlToRequestId.get(url)!.push(requestId)
        }

        if (!requests.has(requestId)) {
          requests.set(requestId, {
            id: requestId,
            url: url || 'No URL',
            events: {
              receivedData: [],
              navigationRequest: [],
              willStartRequest: [],
              willProcessResponse: [],
              throttlingURLLoader: [],
              urlLoaderStart: [],
              onReceiveResponse: [],
              onRequestComplete: [],
              onReceivedRedirect: [],
              connection: [],
              keepAliveURLLoader: [],
              parseOnBackground: [],
              compile: [],
              evaluateScript: [],
              other: []
            }
          })
        }

        const request = requests.get(requestId)!
        
        switch (event.name) {
          case 'ResourceSendRequest':
            request.events.sendRequest = event
            break
          case 'ResourceReceiveResponse':
            request.events.receiveResponse = event
            break
          case 'ResourceReceivedData':
            request.events.receivedData.push(event)
            break
          case 'ResourceFinish':
          case 'ResourceFinishLoading':
            request.events.finishLoading = event
            break
          case 'ResourceWillSendRequest':
            request.events.willSendRequest = event
            break
          case 'ResourceDidReceiveResponse':
            request.events.didReceiveResponse = event
            break
          case 'ResourceDidFinishLoading':
            request.events.didFinishLoading = event
            break
          case 'ResourceDidFailLoading':
            request.events.didFailLoading = event
            break
          case 'ResourceChangedPriority':
            request.events.resourceChangedPriority = event
            break
          case 'ResourceChangePriority':
            request.events.resourceChangePriority = event
            break
          case 'ResourceMarkAsCached':
            request.events.resourceMarkAsCached = event
            break
          case 'PreloadRenderBlockingStatusChange':
            request.events.preloadRenderBlockingStatusChange = event
            break
          // Navigation events
          case 'NavigationRequest':
            request.events.navigationRequest = request.events.navigationRequest || []
            request.events.navigationRequest.push(event)
            break
          case 'WillStartRequest':
            request.events.willStartRequest = request.events.willStartRequest || []
            request.events.willStartRequest.push(event)
            break
          case 'WillProcessResponse':
            request.events.willProcessResponse = request.events.willProcessResponse || []
            request.events.willProcessResponse.push(event)
            break
          case 'DidCommitNavigation':
            request.events.didCommitNavigation = event
            break
          // URL Loader events
          case 'ThrottlingURLLoader':
            request.events.throttlingURLLoader = request.events.throttlingURLLoader || []
            request.events.throttlingURLLoader.push(event)
            break
          case 'OnReceiveResponse':
            request.events.onReceiveResponse = request.events.onReceiveResponse || []
            request.events.onReceiveResponse.push(event)
            break
          case 'OnRequestComplete':
            request.events.onRequestComplete = request.events.onRequestComplete || []
            request.events.onRequestComplete.push(event)
            break
          case 'OnReceivedRedirect':
            request.events.onReceivedRedirect = request.events.onReceivedRedirect || []
            request.events.onReceivedRedirect.push(event)
            break
          // Connection events
          case 'Connection':
            request.events.connection = request.events.connection || []
            request.events.connection.push(event)
            break
          case 'KeepAliveURLLoader':
            request.events.keepAliveURLLoader = request.events.keepAliveURLLoader || []
            request.events.keepAliveURLLoader.push(event)
            break
          case 'v8.parseOnBackground':
            request.events.parseOnBackground = request.events.parseOnBackground || []
            request.events.parseOnBackground.push(event)
            break
          case 'v8.compile':
            request.events.compile = request.events.compile || []
            request.events.compile.push(event)
            break
          case 'EvaluateScript':
            request.events.evaluateScript = request.events.evaluateScript || []
            request.events.evaluateScript.push(event)
            break
          default:
            if (event.name.startsWith('Resource') || 
                event.cat.includes('devtools.timeline') ||
                event.cat.includes('loading') ||
                event.cat.includes('v8')) {
              request.events.other.push(event)
            }
        }
      }
    })

    // Second pass: find related events ONLY by requestId matching (no URL matching)
    traceEvents.forEach(event => {
      const args = event.args as any
      const eventRequestId = args?.data?.requestId || args?.requestId

      // Only match events that have the exact same requestId
      if (eventRequestId && requests.has(eventRequestId)) {
        const request = requests.get(eventRequestId)!
        if (request) {
          switch (event.name) {
            case 'v8.parseOnBackground':
              if (!request.events.parseOnBackground?.some(e => e.ts === event.ts)) {
                request.events.parseOnBackground?.push(event)
              }
              break
            case 'v8.compile':
              if (!request.events.compile?.some(e => e.ts === event.ts)) {
                request.events.compile?.push(event)
              }
              break
            case 'EvaluateScript':
              if (!request.events.evaluateScript?.some(e => e.ts === event.ts)) {
                request.events.evaluateScript?.push(event)
              }
              break
            // Add additional network events that might have requestId but not URL
            case 'NavigationRequest':
              if (!request.events.navigationRequest?.some(e => e.ts === event.ts)) {
                request.events.navigationRequest = request.events.navigationRequest || []
                request.events.navigationRequest.push(event)
              }
              break
            case 'WillStartRequest':
              if (!request.events.willStartRequest?.some(e => e.ts === event.ts)) {
                request.events.willStartRequest = request.events.willStartRequest || []
                request.events.willStartRequest.push(event)
              }
              break
            case 'WillProcessResponse':
              if (!request.events.willProcessResponse?.some(e => e.ts === event.ts)) {
                request.events.willProcessResponse = request.events.willProcessResponse || []
                request.events.willProcessResponse.push(event)
              }
              break
            case 'ThrottlingURLLoader':
              if (!request.events.throttlingURLLoader?.some(e => e.ts === event.ts)) {
                request.events.throttlingURLLoader = request.events.throttlingURLLoader || []
                request.events.throttlingURLLoader.push(event)
              }
              break
            case 'OnReceiveResponse':
              if (!request.events.onReceiveResponse?.some(e => e.ts === event.ts)) {
                request.events.onReceiveResponse = request.events.onReceiveResponse || []
                request.events.onReceiveResponse.push(event)
              }
              break
            case 'OnRequestComplete':
              if (!request.events.onRequestComplete?.some(e => e.ts === event.ts)) {
                request.events.onRequestComplete = request.events.onRequestComplete || []
                request.events.onRequestComplete.push(event)
              }
              break
            case 'Connection':
              if (!request.events.connection?.some(e => e.ts === event.ts)) {
                request.events.connection = request.events.connection || []
                request.events.connection.push(event)
              }
              break
            default:
              if ((event.name.includes('URLLoader') || 
                   event.name.includes('BackgroundProcessor') ||
                   event.name.includes('ResourceRequest') ||
                   event.name.includes('MojoURLLoader') ||
                   event.name.includes('KeepAlive') ||
                   event.cat.includes('loading') ||
                   event.cat.includes('devtools.timeline') ||
                   event.cat.includes('v8')) &&
                  !request.events.other.some(e => e.ts === event.ts)) {
                request.events.other.push(event)
              }
          }
        }
      }
    })

    // Sort events by timestamp
    requests.forEach(request => {
      request.events.receivedData.sort((a, b) => a.ts - b.ts)
      request.events.navigationRequest?.sort((a, b) => a.ts - b.ts)
      request.events.willStartRequest?.sort((a, b) => a.ts - b.ts)
      request.events.willProcessResponse?.sort((a, b) => a.ts - b.ts)
      request.events.throttlingURLLoader?.sort((a, b) => a.ts - b.ts)
      request.events.urlLoaderStart?.sort((a, b) => a.ts - b.ts)
      request.events.onReceiveResponse?.sort((a, b) => a.ts - b.ts)
      request.events.onRequestComplete?.sort((a, b) => a.ts - b.ts)
      request.events.onReceivedRedirect?.sort((a, b) => a.ts - b.ts)
      request.events.connection?.sort((a, b) => a.ts - b.ts)
      request.events.keepAliveURLLoader?.sort((a, b) => a.ts - b.ts)
      request.events.parseOnBackground?.sort((a, b) => a.ts - b.ts)
      request.events.compile?.sort((a, b) => a.ts - b.ts)
      request.events.evaluateScript?.sort((a, b) => a.ts - b.ts)
      request.events.other.sort((a, b) => a.ts - b.ts)
    })

    return Array.from(requests.values())
  }, [traceEvents])

  // Filter requests based on search
  const filteredRequests = useMemo(() => {
    if (!searchUrl) return requestData
    return requestData.filter(req => 
      req.url.toLowerCase().includes(searchUrl.toLowerCase()) ||
      req.id.toLowerCase().includes(searchUrl.toLowerCase())
    )
  }, [requestData, searchUrl])

  const selectedRequest = requestData.find(req => req.id === selectedRequestId)

  const formatTimestamp = (ts: number, baseTimestamp?: number) => {
    const fullTimestamp = ts.toLocaleString() + ' μs'
    if (baseTimestamp && ts !== baseTimestamp) {
      const offset = ts - baseTimestamp
      const offsetMs = offset / 1000
      const offsetSign = offset >= 0 ? '+' : ''
      return `${fullTimestamp} (${offsetSign}${offset.toLocaleString()} μs = ${offsetSign}${offsetMs.toFixed(3)} ms)`
    }
    return fullTimestamp + ' (baseline)'
  }


  const formatTiming = (timing: any) => {
    if (!timing) return null
    
    return (
      <div style={{ fontSize: '12px', fontFamily: 'monospace', marginTop: '10px' }}>
        <Tooltip type={TooltipType.NETWORK_TIMING}>
          <strong>Network Timing (from ResourceReceiveResponse):</strong>
        </Tooltip>
        <div style={{ marginLeft: '10px', marginTop: '5px' }}>
          <div><strong>requestTime:</strong> {timing.requestTime} seconds</div>
          <div><strong>dnsStart:</strong> {timing.dnsStart} ms</div>
          <div><strong>dnsEnd:</strong> {timing.dnsEnd} ms</div>
          <div><strong>connectStart:</strong> {timing.connectStart} ms</div>
          <div><strong>connectEnd:</strong> {timing.connectEnd} ms</div>
          <div><strong>sslStart:</strong> {timing.sslStart} ms</div>
          <div><strong>sslEnd:</strong> {timing.sslEnd} ms</div>
          <div><strong>sendStart:</strong> {timing.sendStart} ms</div>
          <div><strong>sendEnd:</strong> {timing.sendEnd} ms</div>
          <div><strong>receiveHeadersStart:</strong> {timing.receiveHeadersStart} ms</div>
          <div><strong>receiveHeadersEnd:</strong> {timing.receiveHeadersEnd} ms</div>
        </div>
      </div>
    )
  }

  const calculateDurations = (events: HTTPRequestEvents) => {
    if (!events.sendRequest || !events.receiveResponse) return null

    const args = events.receiveResponse.args as any
    const timing = args?.data?.timing
    const lastDataEvent = events.receivedData[events.receivedData.length - 1]

    return (
      <div style={{ 
        backgroundColor: '#f8f9fa', 
        padding: '15px', 
        borderRadius: '5px', 
        marginTop: '15px',
        fontSize: '13px'
      }}>
        <strong>Duration Calculations:</strong>
        
        {timing && (
          <div style={{ marginTop: '10px' }}>
            <div><strong>Chrome DevTools Method (sendStart to receiveHeadersEnd):</strong></div>
            <div style={{ marginLeft: '10px', color: '#007bff' }}>
              {timing.receiveHeadersEnd - timing.sendStart} ms
            </div>
          </div>
        )}

        {timing && timing.connectStart >= 0 && lastDataEvent && (
          <div style={{ marginTop: '10px' }}>
            <div><strong>Our Method - New Connection (connectStart to last data):</strong></div>
            <div style={{ marginLeft: '10px', color: '#28a745' }}>
              {(lastDataEvent.ts - (timing.requestTime * 1000000 + timing.connectStart * 1000)) / 1000} ms
            </div>
          </div>
        )}

        {timing && timing.connectStart < 0 && lastDataEvent && (
          <div style={{ marginTop: '10px' }}>
            <div><strong>Our Method - Reused Connection (sendStart to last data):</strong></div>
            <div style={{ marginLeft: '10px', color: '#ffc107' }}>
              {(lastDataEvent.ts - (timing.requestTime * 1000000 + timing.sendStart * 1000)) / 1000} ms
            </div>
          </div>
        )}

        {timing && (
          <div style={{ marginTop: '10px' }}>
            <div><strong>Fallback Method (receiveHeadersEnd):</strong></div>
            <div style={{ marginLeft: '10px', color: '#dc3545' }}>
              {timing.receiveHeadersEnd} ms
            </div>
          </div>
        )}

        <div style={{ marginTop: '15px', fontSize: '12px', color: '#666' }}>
          <strong>Trace Event Timestamps:</strong>
          <div>Send Request: {formatTimestamp(events.sendRequest.ts)}</div>
          <div>Receive Response: {formatTimestamp(events.receiveResponse.ts)}</div>
          {lastDataEvent && <div>Last Data Chunk: {formatTimestamp(lastDataEvent.ts)}</div>}
          {events.finishLoading && <div>Finish Loading: {formatTimestamp(events.finishLoading.ts)}</div>}
        </div>
      </div>
    )
  }

  return (
    <div style={{ padding: '20px', fontFamily: 'system-ui, sans-serif' }}>
      <h2>Request Timeline Debugger</h2>
      
      {/* Search Controls */}
      <div style={{ 
        backgroundColor: '#f8f9fa', 
        padding: '20px', 
        borderRadius: '8px',
        marginBottom: '20px'
      }}>
        <div style={{ marginBottom: '15px' }}>
          <label style={{ fontWeight: 'bold', display: 'block', marginBottom: '5px' }}>
            Search by URL or Request ID:
          </label>
          <input
            type="text"
            placeholder="e.g., rum-standalone.js or 5254.2"
            value={searchUrl}
            onChange={(e) => setSearchUrl(e.target.value)}
            style={{
              padding: '8px 12px',
              border: '1px solid #ced4da',
              borderRadius: '4px',
              fontSize: '14px',
              width: '400px'
            }}
          />
        </div>
        
        <div>
          <label style={{ fontWeight: 'bold', display: 'block', marginBottom: '5px' }}>
            Select Request:
          </label>
          <select
            value={selectedRequestId}
            onChange={(e) => setSelectedRequestId(e.target.value)}
            style={{
              padding: '8px 12px',
              border: '1px solid #ced4da',
              borderRadius: '4px',
              fontSize: '14px',
              width: '100%',
              maxWidth: '800px'
            }}
          >
            <option value="">-- Select a request to debug --</option>
            {filteredRequests.map(req => (
              <option key={req.id} value={req.id}>
                {req.id} - {req.url.length > 80 ? req.url.substring(0, 80) + '...' : req.url}
              </option>
            ))}
          </select>
        </div>
      </div>

      {selectedRequest && (
        <div style={{ 
          backgroundColor: 'white', 
          border: '1px solid #dee2e6', 
          borderRadius: '8px',
          padding: '20px'
        }}>
          <h3>
            <Tooltip type={TooltipType.REQUEST_DETAILS}>
              Request Details: {selectedRequest.id}
            </Tooltip>
          </h3>
          <div style={{ marginBottom: '15px', wordBreak: 'break-all', fontSize: '14px' }}>
            <strong>URL:</strong> {selectedRequest.url}
          </div>

          {/* Duration Calculations */}
          <div style={{ marginBottom: '20px' }}>
            <Tooltip type={TooltipType.DURATION_CALCULATIONS}>
              <div></div>
            </Tooltip>
            {calculateDurations(selectedRequest.events)}
          </div>

          {/* Event Details */}
          <div style={{ marginTop: '30px' }}>
            <h4>
              <Tooltip type={TooltipType.ALL_EVENTS}>
                All Events for this Request:
              </Tooltip>
            </h4>
            
            {(() => {
              const baseTimestamp = selectedRequest.events.sendRequest?.ts
              return (
                <>
            
                {selectedRequest.events.sendRequest && (
                  <div style={{ marginBottom: '20px', padding: '10px', backgroundColor: '#e3f2fd', borderRadius: '4px' }}>
                    <Tooltip type={TooltipType.RESOURCE_SEND_REQUEST}>
                      <strong>ResourceSendRequest</strong>
                    </Tooltip>
                    {' '}- {formatTimestamp(selectedRequest.events.sendRequest.ts, baseTimestamp)}
                    <pre style={{ fontSize: '12px', marginTop: '10px', overflow: 'auto' }}>
                      {JSON.stringify(selectedRequest.events.sendRequest.args, null, 2)}
                    </pre>
                  </div>
                )}

                {selectedRequest.events.receiveResponse && (
                  <div style={{ marginBottom: '20px', padding: '10px', backgroundColor: '#e8f5e8', borderRadius: '4px' }}>
                    <Tooltip type={TooltipType.RESOURCE_RECEIVE_RESPONSE}>
                      <strong>ResourceReceiveResponse</strong>
                    </Tooltip>
                    {' '}- {formatTimestamp(selectedRequest.events.receiveResponse.ts, baseTimestamp)}
                    {formatTiming((selectedRequest.events.receiveResponse.args as any)?.data?.timing)}
                    <pre style={{ fontSize: '12px', marginTop: '10px', overflow: 'auto' }}>
                      {JSON.stringify(selectedRequest.events.receiveResponse.args, null, 2)}
                    </pre>
                  </div>
                )}

                {selectedRequest.events.receivedData.map((event, index) => (
                  <div key={index} style={{ marginBottom: '20px', padding: '10px', backgroundColor: '#fff3e0', borderRadius: '4px' }}>
                    <Tooltip type={TooltipType.RESOURCE_RECEIVED_DATA}>
                      <strong>ResourceReceivedData #{index + 1}</strong>
                    </Tooltip>
                    {' '}- {formatTimestamp(event.ts, baseTimestamp)}
                    {index === selectedRequest.events.receivedData.length - 1 && (
                      <span style={{ color: '#ff9800', fontWeight: 'bold', marginLeft: '10px' }}>← LAST DATA CHUNK</span>
                    )}
                    <pre style={{ fontSize: '12px', marginTop: '10px', overflow: 'auto' }}>
                      {JSON.stringify(event.args, null, 2)}
                    </pre>
                  </div>
                ))}

                {selectedRequest.events.finishLoading && (
                  <div style={{ marginBottom: '20px', padding: '10px', backgroundColor: '#fce4ec', borderRadius: '4px' }}>
                    <strong>ResourceFinish</strong> - {formatTimestamp(selectedRequest.events.finishLoading.ts, baseTimestamp)}
                    <pre style={{ fontSize: '12px', marginTop: '10px', overflow: 'auto' }}>
                      {JSON.stringify(selectedRequest.events.finishLoading.args, null, 2)}
                    </pre>
                  </div>
                )}

                {/* Additional Event Types */}
                {selectedRequest.events.parseOnBackground && selectedRequest.events.parseOnBackground.length > 0 && (
                  <div style={{ marginTop: '20px' }}>
                    <h5>
                      <Tooltip type={TooltipType.V8_PARSE_EVENTS}>
                        V8 Parse Events:
                      </Tooltip>
                    </h5>
                    {selectedRequest.events.parseOnBackground.map((event, index) => (
                      <div key={index} style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#e1f5fe', borderRadius: '4px' }}>
                        <strong>{event.name}</strong> - {formatTimestamp(event.ts, baseTimestamp)}
                        {(event as any).dur && <span style={{ marginLeft: '10px', color: '#0277bd' }}>Duration: {((event as any).dur / 1000).toFixed(2)}ms</span>}
                        <pre style={{ fontSize: '11px', marginTop: '10px', overflow: 'auto' }}>
                          {JSON.stringify(event.args, null, 2)}
                        </pre>
                      </div>
                    ))}
                  </div>
                )}

                {selectedRequest.events.compile && selectedRequest.events.compile.length > 0 && (
                  <div style={{ marginTop: '20px' }}>
                    <h5>
                      <Tooltip type={TooltipType.V8_COMPILE_EVENTS}>
                        V8 Compile Events:
                      </Tooltip>
                    </h5>
                    {selectedRequest.events.compile.map((event, index) => (
                      <div key={index} style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#f3e5f5', borderRadius: '4px' }}>
                        <strong>{event.name}</strong> - {formatTimestamp(event.ts, baseTimestamp)}
                        {(event as any).dur && <span style={{ marginLeft: '10px', color: '#7b1fa2' }}>Duration: {((event as any).dur / 1000).toFixed(2)}ms</span>}
                        <pre style={{ fontSize: '11px', marginTop: '10px', overflow: 'auto' }}>
                          {JSON.stringify(event.args, null, 2)}
                        </pre>
                      </div>
                    ))}
                  </div>
                )}

                {selectedRequest.events.evaluateScript && selectedRequest.events.evaluateScript.length > 0 && (
                  <div style={{ marginTop: '20px' }}>
                    <h5>
                      <Tooltip type={TooltipType.SCRIPT_EVALUATION}>
                        Script Evaluation Events:
                      </Tooltip>
                    </h5>
                    {selectedRequest.events.evaluateScript.map((event, index) => (
                      <div key={index} style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#e8f5e8', borderRadius: '4px' }}>
                        <strong>{event.name}</strong> - {formatTimestamp(event.ts, baseTimestamp)}
                        {(event as any).dur && <span style={{ marginLeft: '10px', color: '#2e7d32' }}>Duration: {((event as any).dur / 1000).toFixed(2)}ms</span>}
                        <pre style={{ fontSize: '11px', marginTop: '10px', overflow: 'auto' }}>
                          {JSON.stringify(event.args, null, 2)}
                        </pre>
                      </div>
                    ))}
                  </div>
                )}

                {/* Additional Network Events */}
                {selectedRequest.events.willSendRequest && (
                  <div style={{ marginBottom: '20px', padding: '10px', backgroundColor: '#fff8e1', borderRadius: '4px' }}>
                    <strong>ResourceWillSendRequest</strong> - {formatTimestamp(selectedRequest.events.willSendRequest.ts, baseTimestamp)}
                    <pre style={{ fontSize: '12px', marginTop: '10px', overflow: 'auto' }}>
                      {JSON.stringify(selectedRequest.events.willSendRequest.args, null, 2)}
                    </pre>
                  </div>
                )}

                {selectedRequest.events.didReceiveResponse && (
                  <div style={{ marginBottom: '20px', padding: '10px', backgroundColor: '#f1f8e9', borderRadius: '4px' }}>
                    <strong>ResourceDidReceiveResponse</strong> - {formatTimestamp(selectedRequest.events.didReceiveResponse.ts, baseTimestamp)}
                    <pre style={{ fontSize: '12px', marginTop: '10px', overflow: 'auto' }}>
                      {JSON.stringify(selectedRequest.events.didReceiveResponse.args, null, 2)}
                    </pre>
                  </div>
                )}

                {selectedRequest.events.didFinishLoading && (
                  <div style={{ marginBottom: '20px', padding: '10px', backgroundColor: '#f9fbe7', borderRadius: '4px' }}>
                    <strong>ResourceDidFinishLoading</strong> - {formatTimestamp(selectedRequest.events.didFinishLoading.ts, baseTimestamp)}
                    <pre style={{ fontSize: '12px', marginTop: '10px', overflow: 'auto' }}>
                      {JSON.stringify(selectedRequest.events.didFinishLoading.args, null, 2)}
                    </pre>
                  </div>
                )}

                {selectedRequest.events.resourceChangedPriority && (
                  <div style={{ marginBottom: '20px', padding: '10px', backgroundColor: '#fff3e0', borderRadius: '4px' }}>
                    <strong>ResourceChangedPriority</strong> - {formatTimestamp(selectedRequest.events.resourceChangedPriority.ts, baseTimestamp)}
                    <pre style={{ fontSize: '12px', marginTop: '10px', overflow: 'auto' }}>
                      {JSON.stringify(selectedRequest.events.resourceChangedPriority.args, null, 2)}
                    </pre>
                  </div>
                )}

                {selectedRequest.events.resourceChangePriority && (
                  <div style={{ marginBottom: '20px', padding: '10px', backgroundColor: '#fff3e0', borderRadius: '4px' }}>
                    <strong>ResourceChangePriority</strong> - {formatTimestamp(selectedRequest.events.resourceChangePriority.ts, baseTimestamp)}
                    <pre style={{ fontSize: '12px', marginTop: '10px', overflow: 'auto' }}>
                      {JSON.stringify(selectedRequest.events.resourceChangePriority.args, null, 2)}
                    </pre>
                  </div>
                )}

                {selectedRequest.events.resourceMarkAsCached && (
                  <div style={{ marginBottom: '20px', padding: '10px', backgroundColor: '#e8f5e8', borderRadius: '4px' }}>
                    <strong>ResourceMarkAsCached</strong> - {formatTimestamp(selectedRequest.events.resourceMarkAsCached.ts, baseTimestamp)}
                    <pre style={{ fontSize: '12px', marginTop: '10px', overflow: 'auto' }}>
                      {JSON.stringify(selectedRequest.events.resourceMarkAsCached.args, null, 2)}
                    </pre>
                  </div>
                )}

                {selectedRequest.events.preloadRenderBlockingStatusChange && (
                  <div style={{ marginBottom: '20px', padding: '10px', backgroundColor: '#fce4ec', borderRadius: '4px' }}>
                    <strong>PreloadRenderBlockingStatusChange</strong> - {formatTimestamp(selectedRequest.events.preloadRenderBlockingStatusChange.ts, baseTimestamp)}
                    <pre style={{ fontSize: '12px', marginTop: '10px', overflow: 'auto' }}>
                      {JSON.stringify(selectedRequest.events.preloadRenderBlockingStatusChange.args, null, 2)}
                    </pre>
                  </div>
                )}

                {/* Navigation Events */}
                {selectedRequest.events.navigationRequest && selectedRequest.events.navigationRequest.length > 0 && (
                  <div style={{ marginTop: '20px' }}>
                    <h5>Navigation Request Events:</h5>
                    {selectedRequest.events.navigationRequest.map((event, index) => (
                      <div key={index} style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#e3f2fd', borderRadius: '4px' }}>
                        <strong>{event.name}</strong> - {formatTimestamp(event.ts, baseTimestamp)}
                        {(event as any).dur && <span style={{ marginLeft: '10px', color: '#0277bd' }}>Duration: {((event as any).dur / 1000).toFixed(2)}ms</span>}
                        <pre style={{ fontSize: '11px', marginTop: '10px', overflow: 'auto' }}>
                          {JSON.stringify(event.args, null, 2)}
                        </pre>
                      </div>
                    ))}
                  </div>
                )}

                {selectedRequest.events.willStartRequest && selectedRequest.events.willStartRequest.length > 0 && (
                  <div style={{ marginTop: '20px' }}>
                    <h5>Will Start Request Events:</h5>
                    {selectedRequest.events.willStartRequest.map((event, index) => (
                      <div key={index} style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#fff8e1', borderRadius: '4px' }}>
                        <strong>{event.name}</strong> - {formatTimestamp(event.ts, baseTimestamp)}
                        <pre style={{ fontSize: '11px', marginTop: '10px', overflow: 'auto' }}>
                          {JSON.stringify(event.args, null, 2)}
                        </pre>
                      </div>
                    ))}
                  </div>
                )}

                {selectedRequest.events.willProcessResponse && selectedRequest.events.willProcessResponse.length > 0 && (
                  <div style={{ marginTop: '20px' }}>
                    <h5>Will Process Response Events:</h5>
                    {selectedRequest.events.willProcessResponse.map((event, index) => (
                      <div key={index} style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#f1f8e9', borderRadius: '4px' }}>
                        <strong>{event.name}</strong> - {formatTimestamp(event.ts, baseTimestamp)}
                        <pre style={{ fontSize: '11px', marginTop: '10px', overflow: 'auto' }}>
                          {JSON.stringify(event.args, null, 2)}
                        </pre>
                      </div>
                    ))}
                  </div>
                )}

                {selectedRequest.events.didCommitNavigation && (
                  <div style={{ marginBottom: '20px', padding: '10px', backgroundColor: '#e8f5e8', borderRadius: '4px' }}>
                    <strong>DidCommitNavigation</strong> - {formatTimestamp(selectedRequest.events.didCommitNavigation.ts, baseTimestamp)}
                    <pre style={{ fontSize: '12px', marginTop: '10px', overflow: 'auto' }}>
                      {JSON.stringify(selectedRequest.events.didCommitNavigation.args, null, 2)}
                    </pre>
                  </div>
                )}

                {/* URL Loader Events */}
                {selectedRequest.events.throttlingURLLoader && selectedRequest.events.throttlingURLLoader.length > 0 && (
                  <div style={{ marginTop: '20px' }}>
                    <h5>
                      <Tooltip type={TooltipType.THROTTLING_URL_LOADER}>
                        Throttling URL Loader Events ({selectedRequest.events.throttlingURLLoader.length}):
                      </Tooltip>
                    </h5>
                    {selectedRequest.events.throttlingURLLoader.map((event, index) => (
                      <div key={index} style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#fff3e0', borderRadius: '4px' }}>
                        <strong>{event.name}</strong> - {formatTimestamp(event.ts, baseTimestamp)}
                        {(event as any).dur && <span style={{ marginLeft: '10px', color: '#f57c00' }}>Duration: {((event as any).dur / 1000).toFixed(2)}ms</span>}
                        <div style={{ fontSize: '11px', color: '#666', marginTop: '5px' }}>Category: {event.cat}</div>
                        <pre style={{ fontSize: '11px', marginTop: '10px', overflow: 'auto' }}>
                          {JSON.stringify(event.args, null, 2)}
                        </pre>
                      </div>
                    ))}
                  </div>
                )}

                {selectedRequest.events.onReceiveResponse && selectedRequest.events.onReceiveResponse.length > 0 && (
                  <div style={{ marginTop: '20px' }}>
                    <h5>URL Loader OnReceiveResponse Events:</h5>
                    {selectedRequest.events.onReceiveResponse.map((event, index) => (
                      <div key={index} style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#e8f5e8', borderRadius: '4px' }}>
                        <strong>{event.name}</strong> - {formatTimestamp(event.ts, baseTimestamp)}
                        <pre style={{ fontSize: '11px', marginTop: '10px', overflow: 'auto' }}>
                          {JSON.stringify(event.args, null, 2)}
                        </pre>
                      </div>
                    ))}
                  </div>
                )}

                {selectedRequest.events.onRequestComplete && selectedRequest.events.onRequestComplete.length > 0 && (
                  <div style={{ marginTop: '20px' }}>
                    <h5>URL Loader OnRequestComplete Events:</h5>
                    {selectedRequest.events.onRequestComplete.map((event, index) => (
                      <div key={index} style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#fce4ec', borderRadius: '4px' }}>
                        <strong>{event.name}</strong> - {formatTimestamp(event.ts, baseTimestamp)}
                        <pre style={{ fontSize: '11px', marginTop: '10px', overflow: 'auto' }}>
                          {JSON.stringify(event.args, null, 2)}
                        </pre>
                      </div>
                    ))}
                  </div>
                )}

                {selectedRequest.events.onReceivedRedirect && selectedRequest.events.onReceivedRedirect.length > 0 && (
                  <div style={{ marginTop: '20px' }}>
                    <h5>Redirect Events:</h5>
                    {selectedRequest.events.onReceivedRedirect.map((event, index) => (
                      <div key={index} style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#fff8e1', borderRadius: '4px' }}>
                        <strong>{event.name}</strong> - {formatTimestamp(event.ts, baseTimestamp)}
                        <pre style={{ fontSize: '11px', marginTop: '10px', overflow: 'auto' }}>
                          {JSON.stringify(event.args, null, 2)}
                        </pre>
                      </div>
                    ))}
                  </div>
                )}

                {/* Connection Events */}
                {selectedRequest.events.connection && selectedRequest.events.connection.length > 0 && (
                  <div style={{ marginTop: '20px' }}>
                    <h5>Connection Events:</h5>
                    {selectedRequest.events.connection.map((event, index) => (
                      <div key={index} style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#e1f5fe', borderRadius: '4px' }}>
                        <strong>{event.name}</strong> - {formatTimestamp(event.ts, baseTimestamp)}
                        {(event as any).dur && <span style={{ marginLeft: '10px', color: '#0277bd' }}>Duration: {((event as any).dur / 1000).toFixed(2)}ms</span>}
                        <pre style={{ fontSize: '11px', marginTop: '10px', overflow: 'auto' }}>
                          {JSON.stringify(event.args, null, 2)}
                        </pre>
                      </div>
                    ))}
                  </div>
                )}

                {selectedRequest.events.keepAliveURLLoader && selectedRequest.events.keepAliveURLLoader.length > 0 && (
                  <div style={{ marginTop: '20px' }}>
                    <h5>Keep-Alive URL Loader Events:</h5>
                    {selectedRequest.events.keepAliveURLLoader.map((event, index) => (
                      <div key={index} style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#f3e5f5', borderRadius: '4px' }}>
                        <strong>{event.name}</strong> - {formatTimestamp(event.ts, baseTimestamp)}
                        <pre style={{ fontSize: '11px', marginTop: '10px', overflow: 'auto' }}>
                          {JSON.stringify(event.args, null, 2)}
                        </pre>
                      </div>
                    ))}
                  </div>
                )}

                {selectedRequest.events.other.length > 0 && (
                  <div style={{ marginTop: '20px' }}>
                    <h5>Other Related Events ({selectedRequest.events.other.length}):</h5>
                    {selectedRequest.events.other.map((event, index) => (
                      <div key={index} style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
                        <strong>{event.name}</strong> - {formatTimestamp(event.ts, baseTimestamp)}
                        {(event as any).dur && <span style={{ marginLeft: '10px', color: '#666' }}>Duration: {((event as any).dur / 1000).toFixed(2)}ms</span>}
                        <div style={{ fontSize: '11px', color: '#666', marginTop: '5px' }}>Category: {event.cat}</div>
                        <pre style={{ fontSize: '11px', marginTop: '10px', overflow: 'auto' }}>
                          {JSON.stringify(event.args, null, 2)}
                        </pre>
                      </div>
                    ))}
                  </div>
                )}
                
                </>
              )
            })()}
          </div>
        </div>
      )}
    </div>
  )
}