import React, { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  loadJamTrack,
  checkJamTrackSync,
  closeJamTrack,
  setJamTrackState,
  setDownloadState,
  cleanupJamTrackCallbacks
} from '../../store/features/mediaSlice';
import { setOpenJamTrack, clearOpenJamTrack } from '../../store/features/sessionUISlice';
import { setAvailableMixdowns, setActiveMixdown } from '../../store/features/activeSessionSlice';
import { useJamServerContext } from '../../context/JamServerContext';

// Error types for comprehensive error handling
const ERROR_TYPES = {
  FILE: 'file',         // Red - critical
  NETWORK: 'network',   // Red - critical
  DOWNLOAD: 'download', // Red - critical
  PLAYBACK: 'playback', // Yellow - warning
  GENERAL: 'general'    // Yellow - warning
};

const JKSessionJamTrackPlayer = ({
  isOpen,
  onClose,
  isPopup = false,
  jamTrack,
  jamClient,
  session,
  currentUser,
  initialMixdownId = null,
  autoPlay = false
}) => {
  // Local state
  const [error, setError] = useState(null);
  const [isLoadingSync, setIsLoadingSync] = useState(false);
  const [isOperating, setIsOperating] = useState(false);
  const [selectedMixdownId, setSelectedMixdownId] = useState(initialMixdownId);

  // Context
  const { subscribe, unsubscribe } = useJamServerContext();

  // Create jamServer object with subscribe/unsubscribe for thunks
  const jamServer = useMemo(() => ({
    subscribe,
    unsubscribe
  }), [subscribe, unsubscribe]);

  // Redux state
  const dispatch = useDispatch();
  const jamTrackState = useSelector(state => state.media.jamTrackState);
  const downloadState = useSelector(state => state.media.downloadState);
  const availableMixdowns = useSelector(state => state.activeSession.availableMixdowns);

  // Refs
  const fqIdRef = useRef(null);
  const mountedRef = useRef(true);
  const pendingSeekRef = useRef(null);
  const consecutiveFailuresRef = useRef(0);

  // Helper: Build fqId
  const buildFqId = useCallback(async () => {
    if (!jamClient || !jamTrack) return null;
    const sampleRate = await jamClient.GetSampleRate();
    return `${jamTrack.id}-${sampleRate === 48 ? '48' : '44'}`;
  }, [jamClient, jamTrack]);

  // Initialization
  useEffect(() => {
    if (!isOpen && !isPopup) return;
    if (!jamClient || !jamTrack) return;

    const initializePlayer = async () => {
      try {
        setIsLoadingSync(true);
        setError(null);

        // Edge case validation: null jamClient
        if (!jamClient) {
          setError({ type: ERROR_TYPES.GENERAL, message: 'Native client not available. Please ensure JamKazam is running.' });
          return;
        }

        // Edge case validation: invalid jamTrack
        if (!jamTrack || !jamTrack.id) {
          setError({ type: ERROR_TYPES.FILE, message: 'Invalid JamTrack data' });
          return;
        }

        // Build fqId
        const fqId = await buildFqId();
        fqIdRef.current = fqId;

        // Check sync state
        const syncResult = await dispatch(checkJamTrackSync({ jamTrack, jamClient })).unwrap();

        if (!syncResult.isSynchronized) {
          // Download flow will be triggered by loadJamTrack (no diagnostic logging)
        }

        // Use mixdowns from jamTrack object (fetched from REST API with packages)
        try {
          const mixdowns = jamTrack.mixdowns;

          if (mixdowns && mixdowns.length > 0) {
            // Organize into hierarchy: master, custom mixes, stems
            const organized = {
              master: mixdowns.find(m => m.type === 'master') || null,
              customMixes: mixdowns.filter(m => m.type === 'custom' || m.type === 'custom-mix'),
              stems: mixdowns.filter(m => m.type === 'stem')
            };

            dispatch(setAvailableMixdowns(mixdowns));

            // Set initial mixdown if not already selected
            if (!selectedMixdownId) {
              const defaultMixdown = organized.master || (mixdowns[0] || null);
              if (defaultMixdown) {
                setSelectedMixdownId(defaultMixdown.id);
                dispatch(setActiveMixdown(defaultMixdown));
              }
            } else {
              // Find and set the initially selected mixdown
              const mixdown = mixdowns.find(m => m.id === selectedMixdownId);
              if (mixdown) {
                dispatch(setActiveMixdown(mixdown));
              }
            }
          }
        } catch (err) {
          console.error('[JamTrack] Failed to load mixdowns:', err);
          // Non-fatal - can still play default mixdown
        }

        // Set open in Redux
        dispatch(setOpenJamTrack(jamTrack.id));

        // Load and play if autoPlay
        if (autoPlay) {
          await dispatch(loadJamTrack({
            jamTrack,
            mixdownId: selectedMixdownId,
            autoPlay: true,
            jamClient,
            jamServer
          })).unwrap();
        }

      } catch (err) {
        console.error('[JamTrack] Initialization error:', err);
        setError({ type: ERROR_TYPES.GENERAL, message: err.message || 'Failed to initialize JamTrack' });
      } finally {
        if (mountedRef.current) {
          setIsLoadingSync(false);
        }
      }
    };

    initializePlayer();
  }, [isOpen, isPopup, jamTrack, jamClient, autoPlay, selectedMixdownId, dispatch, buildFqId]);

  // Cleanup on unmount
  useEffect(() => {
    return () => {
      mountedRef.current = false;

      if (fqIdRef.current && jamClient) {
        dispatch(closeJamTrack({ fqId: fqIdRef.current, jamClient }));
        dispatch(clearOpenJamTrack());
      }

      // Clean up download callbacks to prevent memory leaks
      cleanupJamTrackCallbacks();
    };
  }, [dispatch, jamClient]);

  // Playback control handlers
  const handlePlay = useCallback(async () => {
    if (isOperating || !jamClient || !fqIdRef.current) return;

    try {
      setIsOperating(true);
      setError(null);

      // If not playing yet, load JamTrack
      if (!jamTrackState.isPlaying) {
        await dispatch(loadJamTrack({
          jamTrack,
          mixdownId: selectedMixdownId,
          autoPlay: true,
          jamClient,
          jamServer
        })).unwrap();
      } else if (jamTrackState.isPaused) {
        // Resume from pause
        await jamClient.JamTrackResume(fqIdRef.current);

        // Apply pending seek if exists (UAT-003 fix)
        if (pendingSeekRef.current !== null) {
          await jamClient.JamTrackSeekMs(fqIdRef.current, pendingSeekRef.current);
          pendingSeekRef.current = null;
        }

        dispatch(setJamTrackState({ isPaused: false, isPlaying: true }));
      }
    } catch (err) {
      console.error('[JamTrack] Play error:', err);
      setError({ type: ERROR_TYPES.PLAYBACK, message: 'Failed to play JamTrack' });
    } finally {
      if (mountedRef.current) {
        setIsOperating(false);
      }
    }
  }, [isOperating, jamClient, jamTrack, jamTrackState, selectedMixdownId, dispatch]);

  const handlePause = useCallback(async () => {
    if (isOperating || !jamClient || !fqIdRef.current) return;

    try {
      setIsOperating(true);
      setError(null);

      await jamClient.JamTrackPause(fqIdRef.current);
      dispatch(setJamTrackState({ isPaused: true, isPlaying: false }));
    } catch (err) {
      console.error('[JamTrack] Pause error:', err);
      setError({ type: ERROR_TYPES.PLAYBACK, message: 'Failed to pause JamTrack' });
    } finally {
      if (mountedRef.current) {
        setIsOperating(false);
      }
    }
  }, [isOperating, jamClient, dispatch]);

  const handleStop = useCallback(async () => {
    if (isOperating || !jamClient || !fqIdRef.current) return;

    try {
      setIsOperating(true);
      setError(null);

      await jamClient.JamTrackStop(fqIdRef.current);
      dispatch(setJamTrackState({
        isPlaying: false,
        isPaused: false,
        currentPositionMs: 0
      }));
    } catch (err) {
      console.error('[JamTrack] Stop error:', err);
      setError({ type: ERROR_TYPES.PLAYBACK, message: 'Failed to stop JamTrack' });
    } finally {
      if (mountedRef.current) {
        setIsOperating(false);
      }
    }
  }, [isOperating, jamClient, dispatch]);

  // Seek handler
  const handleSeek = useCallback(async (newPositionMs) => {
    if (isOperating || !jamClient || !fqIdRef.current) return;

    try {
      setError(null);

      // UAT-003 fix: if paused, store pending seek
      if (jamTrackState.isPaused) {
        pendingSeekRef.current = newPositionMs;
        dispatch(setJamTrackState({ currentPositionMs: newPositionMs }));
        return;
      }

      // If playing, seek immediately
      await jamClient.JamTrackSeekMs(fqIdRef.current, newPositionMs);
      dispatch(setJamTrackState({ currentPositionMs: newPositionMs }));
    } catch (err) {
      console.error('[JamTrack] Seek error:', err);
      setError({ type: ERROR_TYPES.PLAYBACK, message: 'Failed to seek' });
    }
  }, [isOperating, jamClient, jamTrackState.isPaused, dispatch]);

  // Mixdown change handler
  const handleMixdownChange = useCallback(async (mixdownId) => {
    if (isOperating || !jamClient || !fqIdRef.current) return;

    try {
      setIsOperating(true);
      setError(null);

      // Find the new mixdown
      const mixdown = availableMixdowns.find(m => m.id === mixdownId);
      if (!mixdown) {
        throw new Error('Mixdown not found');
      }

      // Update local state
      setSelectedMixdownId(mixdownId);
      dispatch(setActiveMixdown(mixdown));

      // If currently playing, stop and restart with new mixdown
      if (jamTrackState.isPlaying || jamTrackState.isPaused) {
        await jamClient.JamTrackStop(fqIdRef.current);

        await dispatch(loadJamTrack({
          jamTrack,
          mixdownId,
          autoPlay: true,
          jamClient,
          jamServer
        })).unwrap();
      }

    } catch (err) {
      console.error('[JamTrack] Mixdown change error:', err);
      setError({ type: ERROR_TYPES.PLAYBACK, message: 'Failed to change mixdown' });
    } finally {
      if (mountedRef.current) {
        setIsOperating(false);
      }
    }
  }, [isOperating, jamClient, jamTrack, jamTrackState, availableMixdowns, dispatch]);

  // Download cancel handler
  const handleCancelDownload = useCallback(async () => {
    if (!jamClient || !fqIdRef.current) return;

    try {
      await jamClient.JamTrackCancelDownload(fqIdRef.current);
      dispatch(setDownloadState({ state: 'idle', progress: 0 }));
    } catch (err) {
      console.error('[JamTrack] Cancel download error:', err);
      setError({ type: ERROR_TYPES.DOWNLOAD, message: 'Failed to cancel download' });
    }
  }, [jamClient, dispatch]);

  // Download retry handler
  const handleRetryDownload = useCallback(async () => {
    if (isOperating || !jamClient) return;

    try {
      setIsOperating(true);
      setError(null);

      // Clear error state
      dispatch(setDownloadState({ state: 'idle', error: null }));

      // Retry load (will trigger download if not synced)
      await dispatch(loadJamTrack({
        jamTrack,
        mixdownId: selectedMixdownId,
        autoPlay: false,
        jamClient,
        jamServer
      })).unwrap();

    } catch (err) {
      console.error('[JamTrack] Retry download error:', err);
      setError({ type: ERROR_TYPES.DOWNLOAD, message: 'Retry failed' });
    } finally {
      if (mountedRef.current) {
        setIsOperating(false);
      }
    }
  }, [isOperating, jamClient, jamTrack, selectedMixdownId, dispatch]);

  // Error retry handler
  const handleRetryError = useCallback(async () => {
    if (!error || isOperating) return;

    setError(null);

    // Retry based on error type
    if (error.type === ERROR_TYPES.DOWNLOAD || error.type === ERROR_TYPES.FILE) {
      await handleRetryDownload();
    } else if (error.type === ERROR_TYPES.NETWORK) {
      // Re-initialize player
      if (jamTrack && jamClient) {
        const fqId = await buildFqId();
        fqIdRef.current = fqId;
        await dispatch(loadJamTrack({ jamTrack, mixdownId: selectedMixdownId, autoPlay: false, jamClient, jamServer }));
      }
    }
  }, [error, isOperating, jamTrack, jamClient, jamServer, selectedMixdownId, handleRetryDownload, buildFqId, dispatch]);

  // Helper: Format milliseconds to MM:SS
  const formatTime = useCallback((ms) => {
    if (!ms || isNaN(ms)) return '00:00';
    const totalSeconds = Math.floor(ms / 1000);
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;
    return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
  }, []);

  // Memoized formatted time values for performance
  const formattedPosition = useMemo(
    () => formatTime(jamTrackState.currentPositionMs),
    [jamTrackState.currentPositionMs, formatTime]
  );

  const formattedDuration = useMemo(
    () => formatTime(jamTrackState.durationMs),
    [jamTrackState.durationMs, formatTime]
  );

  // Memoized progress percentage for UI
  const progressPercent = useMemo(() => {
    if (!jamTrackState.durationMs || jamTrackState.durationMs === 0) return 0;
    return Math.round((jamTrackState.currentPositionMs / jamTrackState.durationMs) * 100);
  }, [jamTrackState.currentPositionMs, jamTrackState.durationMs]);

  // Polling for position and duration
  useEffect(() => {
    if (!jamClient || !fqIdRef.current || !jamTrackState.isPlaying) return;

    // Check if tab is visible
    const isVisible = document.visibilityState === 'visible';
    const pollInterval = isVisible ? 500 : 2000;

    const intervalId = setInterval(async () => {
      try {
        // Fetch position and duration
        const positionStr = await jamClient.JamTrackGetPositionMs(fqIdRef.current);
        const durationStr = await jamClient.JamTrackGetDurationMs(fqIdRef.current);

        const position = parseInt(positionStr, 10);
        const duration = parseInt(durationStr, 10);

        // Conditional update: only update if values changed
        if (
          position !== jamTrackState.currentPositionMs ||
          duration !== jamTrackState.durationMs
        ) {
          dispatch(setJamTrackState({
            currentPositionMs: position,
            durationMs: duration,
            lastUpdate: Date.now()
          }));
        }

        // End-of-track handling
        if (duration > 0 && position >= duration) {
          await jamClient.JamTrackStop(fqIdRef.current);
          dispatch(setJamTrackState({
            isPlaying: false,
            isPaused: false,
            currentPositionMs: 0
          }));
        }

        // Reset error counter on success
        consecutiveFailuresRef.current = 0;
      } catch (err) {
        console.error('[JamTrack] Polling error:', err);
        consecutiveFailuresRef.current += 1;

        // After 3 consecutive failures, show error and stop polling
        if (consecutiveFailuresRef.current >= 3) {
          setError({ type: ERROR_TYPES.NETWORK, message: 'Lost connection to native client. Check if JamKazam is running.' });
          // Stop polling by setting isPlaying to false
          dispatch(setJamTrackState({ isPlaying: false }));
        }
      }
    }, pollInterval);

    return () => clearInterval(intervalId);
  }, [jamClient, jamTrackState.isPlaying, jamTrackState.currentPositionMs, jamTrackState.durationMs, dispatch]);

  // Listen for visibility changes to recreate interval
  useEffect(() => {
    const handleVisibilityChange = () => {
      // Trigger polling effect to restart with new interval
      // This is handled by the dependency array
    };

    document.addEventListener('visibilitychange', handleVisibilityChange);
    return () => document.removeEventListener('visibilitychange', handleVisibilityChange);
  }, []);

  if (!isOpen && !isPopup) return null;

  return (
    <>
      <style>
        {`
          @keyframes spin {
            to { transform: rotate(360deg); }
          }
        `}
      </style>
      <div style={{
      width: '420px',
      minHeight: '220px',
      display: 'flex',
      flexDirection: 'column',
      fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", sans-serif',
      backgroundColor: '#f5f5f7',
      borderRadius: '8px',
      boxShadow: '0 10px 40px rgba(0, 0, 0, 0.3)'
    }}>
     

      {/* Content Area */}
      <div style={{ padding: '20px 24px', background: '#ffffff', flex: 1 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: '20px' }}>
          {/* Error Banner */}
          {error && (
            <div style={{
              padding: '12px',
              backgroundColor: (error.type === ERROR_TYPES.FILE || error.type === ERROR_TYPES.NETWORK) ? '#f8d7da' : '#fff3cd',
              color: (error.type === ERROR_TYPES.FILE || error.type === ERROR_TYPES.NETWORK) ? '#721c24' : '#856404',
              border: `1px solid ${(error.type === ERROR_TYPES.FILE || error.type === ERROR_TYPES.NETWORK) ? '#f5c6cb' : '#ffeaa7'}`,
              borderRadius: '4px',
              display: 'flex',
              flexDirection: 'column',
              gap: '8px'
            }}>
              <div><strong>{error.type.toUpperCase()} ERROR:</strong> {error.message}</div>
              <div style={{ display: 'flex', gap: '8px' }}>
                <button
                  onClick={() => setError(null)}
                  style={{
                    padding: '4px 12px',
                    border: '1px solid #ccc',
                    borderRadius: '4px',
                    backgroundColor: 'white',
                    cursor: 'pointer',
                    fontSize: '12px'
                  }}
                >
                  Dismiss
                </button>
                {(error.type === ERROR_TYPES.NETWORK || error.type === ERROR_TYPES.DOWNLOAD || error.type === ERROR_TYPES.FILE) && (
                  <button
                    onClick={handleRetryError}
                    style={{
                      padding: '4px 12px',
                      border: '1px solid #007aff',
                      borderRadius: '4px',
                      backgroundColor: '#007aff',
                      color: 'white',
                      cursor: 'pointer',
                      fontSize: '12px'
                    }}
                  >
                    Retry
                  </button>
                )}
              </div>
            </div>
          )}

          {/* Download/Sync State Banner */}
          {/* <div>{JSON.stringify(downloadState)}</div> */}
          {downloadState.state !== 'idle' && downloadState.state !== 'synchronized' && (
            <div style={{
              background: '#f0f8ff',
              padding: '12px 16px',
              border: '1px solid #cce7ff',
              borderRadius: '6px'
            }}>
              <div style={{ margin: '0 0 8px 0', fontSize: '13px', fontWeight: '600', color: '#1d1d1f' }}>
                {downloadState.state === 'checking' && 'Checking sync status...'}
                {downloadState.state === 'packaging' && 'Your JamTrack is currently being created in the JamKazam server'}
                {downloadState.state === 'downloading' && 'Downloading JamTrack...'}
                {downloadState.state === 'keying' && 'Requesting decryption keys...'}
                {downloadState.state === 'error' && 'Download Failed'}
              </div>

              {downloadState.state === 'packaging' && (
                <>
                  <div style={{ margin: '4px 0', fontSize: '12px', color: '#6e6e73' }}>
                    {downloadState.signing_state === 'SIGNED' && 'Package ready, starting download...'}
                    {downloadState.signing_state !== 'SIGNED' && downloadState.signing_state && `Status: ${downloadState.signing_state}`}
                    {!downloadState.signing_state && 'Preparing your JamTrack...'}
                  </div>
                  {downloadState.packaging_steps > 0 && (
                    <div style={{ margin: '4px 0', fontSize: '12px', color: '#6e6e73' }}>
                      Step {downloadState.current_packaging_step} of {downloadState.packaging_steps}
                    </div>
                  )}
                  <div style={{
                    display: 'inline-block',
                    width: '16px',
                    height: '16px',
                    border: '2px solid #e5e5ea',
                    borderTopColor: '#007aff',
                    borderRadius: '50%',
                    animation: 'spin 0.8s linear infinite',
                    marginTop: '8px'
                  }}></div>
                </>
              )}

              {downloadState.state === 'downloading' && (
                <>
                  <progress
                    value={downloadState.progress}
                    max="100"
                    style={{
                      width: '100%',
                      height: '6px',
                      marginTop: '8px',
                      borderRadius: '3px'
                    }}
                  />
                  <div style={{ margin: '4px 0', fontSize: '12px', color: '#6e6e73' }}>
                    {downloadState.progress}%
                  </div>
                  {downloadState.totalSteps > 0 && (
                    <div style={{ margin: '4px 0', fontSize: '12px', color: '#6e6e73' }}>
                      Step {downloadState.currentStep} of {downloadState.totalSteps}
                    </div>
                  )}
                  <button
                    onClick={handleCancelDownload}
                    style={{
                      padding: '4px 12px',
                      fontSize: '12px',
                      border: '1px solid #d1d1d6',
                      borderRadius: '4px',
                      background: 'white',
                      cursor: 'pointer',
                      marginTop: '8px'
                    }}
                  >
                    Cancel
                  </button>
                </>
              )}

              {downloadState.state === 'keying' && (
                <>
                  <div style={{ margin: '4px 0', fontSize: '12px', color: '#6e6e73' }}>
                    Finalizing download...
                  </div>
                  <div style={{
                    display: 'inline-block',
                    width: '16px',
                    height: '16px',
                    border: '2px solid #e5e5ea',
                    borderTopColor: '#007aff',
                    borderRadius: '50%',
                    animation: 'spin 0.8s linear infinite',
                    marginTop: '8px'
                  }}></div>
                </>
              )}

              {downloadState.state === 'error' && (
                <>
                  <div style={{ color: '#c41e3a', margin: '4px 0', fontSize: '12px' }}>
                    {downloadState.error?.message || 'Download failed'}
                  </div>
                  <button
                    onClick={handleRetryDownload}
                    style={{
                      padding: '4px 12px',
                      fontSize: '12px',
                      border: '1px solid #d1d1d6',
                      borderRadius: '4px',
                      background: 'white',
                      cursor: 'pointer',
                      marginTop: '8px'
                    }}
                  >
                    Retry
                  </button>
                </>
              )}
            </div>
          )}

          {/* Loading indicator */}
          {isLoadingSync && (
            <div style={{ textAlign: 'center', color: '#6c757d', fontSize: '14px' }}>
              Loading track...
            </div>
          )}

          {/* Controls Section - only show when track is synchronized with backend */}
          {(downloadState.state === 'synchronized') && !isLoadingSync && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
              {/* Circular Buttons and Seek Bar */}
              <div style={{ display: 'flex', alignItems: 'center', gap: '12px' }}>
                {/* Play Button - Circular */}
                <button
                  onClick={handlePlay}
                  disabled={isOperating || isLoadingSync}
                  style={{
                    width: '36px',
                    height: '36px',
                    borderRadius: '50%',
                    border: 'none',
                    backgroundColor: (jamTrackState.isPlaying && !jamTrackState.isPaused) ? '#6c757d' : '#5b9bd5',
                    color: 'white',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    cursor: (isOperating || isLoadingSync) ? 'not-allowed' : 'pointer',
                    opacity: (isOperating || isLoadingSync) ? 0.5 : 1,
                    outline: 'none',
                    flexShrink: 0
                  }}
                >
                  {jamTrackState.isPlaying && !jamTrackState.isPaused ? (
                    <svg width="12" height="14" viewBox="0 0 12 14" fill="currentColor">
                      <rect x="0" y="0" width="4" height="14" />
                      <rect x="8" y="0" width="4" height="14" />
                    </svg>
                  ) : (
                    <svg width="12" height="14" viewBox="0 0 12 14" fill="currentColor">
                      <path d="M0 0L12 7L0 14V0Z" />
                    </svg>
                  )}
                </button>

                {/* Stop Button - Circular */}
                <button
                  onClick={handleStop}
                  disabled={isOperating || (!jamTrackState.isPlaying && !jamTrackState.isPaused)}
                  style={{
                    width: '36px',
                    height: '36px',
                    borderRadius: '50%',
                    border: 'none',
                    backgroundColor: '#b0b0b0',
                    color: 'white',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    cursor: (isOperating || (!jamTrackState.isPlaying && !jamTrackState.isPaused)) ? 'not-allowed' : 'pointer',
                    opacity: (isOperating || (!jamTrackState.isPlaying && !jamTrackState.isPaused)) ? 0.5 : 1,
                    outline: 'none',
                    flexShrink: 0
                  }}
                >
                  <svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor">
                    <rect x="0" y="0" width="12" height="12" />
                  </svg>
                </button>

                {/* Time and Seek Bar */}
                <div style={{ display: 'flex', alignItems: 'center', flex: 1, gap: '8px' }}>
                  <span style={{ fontSize: '14px', color: '#666', minWidth: '35px', fontFamily: 'monospace' }}>
                    {formattedPosition}
                  </span>
                  <input
                    type="range"
                    min="0"
                    max={jamTrackState.durationMs || 100}
                    value={jamTrackState.currentPositionMs || 0}
                    onChange={(e) => handleSeek(parseInt(e.target.value, 10))}
                    disabled={isOperating || !jamTrackState.durationMs}
                    style={{
                      flex: 1,
                      height: '4px',
                      borderRadius: '2px',
                      outline: 'none',
                      background: `linear-gradient(to right, #5b9bd5 0%, #5b9bd5 ${progressPercent}%, #ddd ${progressPercent}%, #ddd 100%)`,
                      WebkitAppearance: 'none',
                      cursor: (isOperating || !jamTrackState.durationMs) ? 'not-allowed' : 'pointer'
                    }}
                  />
                  <span style={{ fontSize: '14px', color: '#666', minWidth: '35px', fontFamily: 'monospace' }}>
                    {formattedDuration}
                  </span>
                </div>
              </div>

              {/* Mix Selector */}
              {availableMixdowns.length > 0 && (
                <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                    <span style={{ fontSize: '13px', color: '#6e6e73', fontWeight: '500' }}>
                      Mix:
                    </span>
                    <select
                      value={selectedMixdownId || ''}
                      onChange={(e) => handleMixdownChange(parseInt(e.target.value, 10))}
                      disabled={isOperating || isLoadingSync}
                      style={{
                        flex: 1,
                        padding: '6px 12px',
                        fontSize: '13px',
                        border: '1px solid #d1d1d6',
                        borderRadius: '6px',
                        background: 'white',
                        color: '#1d1d1f',
                        cursor: 'pointer',
                        outline: 'none'
                      }}
                    >
                      {availableMixdowns
                        .slice()
                        .sort((a, b) => {
                          // Sort order: master first, then custom mixes, then stems
                          if (a.type === 'master') return -1;
                          if (b.type === 'master') return 1;
                          if (a.type === 'custom' || a.type === 'custom-mix') return -1;
                          if (b.type === 'custom' || b.type === 'custom-mix') return 1;
                          return a.name.localeCompare(b.name);
                        })
                        .map(mixdown => (
                          <option key={mixdown.id} value={mixdown.id}>
                            {mixdown.name}
                          </option>
                        ))
                      }
                    </select>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <a
                      onClick={() => window.open(`/jamtracks/${jamTrack?.id}`, '_blank', 'noopener,noreferrer')}
                      style={{
                        fontSize: '12px',
                        color: '#007aff',
                        textDecoration: 'none',
                        cursor: 'pointer'
                      }}
                    >
                      create custom mix
                    </a>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* Close Button */}
          <div style={{ display: 'flex', justifyContent: 'center', marginTop: '8px' }}>
            <button
              onClick={onClose}
              style={{
                padding: '8px 24px',
                border: '1px solid #ccc',
                borderRadius: '4px',
                backgroundColor: 'white',
                color: '#666',
                cursor: 'pointer',
                fontSize: '14px',
                outline: 'none'
              }}
            >
              Close
            </button>
          </div>
        </div>
      </div>
    </div>
    </>
  );
};

export default React.memo(JKSessionJamTrackPlayer);
