import { useRouter } from 'next/navigation';
import React, { useEffect, useRef, useState } from 'react';

import { useStores } from '@/app/(root)/AppProviders';
// import UploadMediaModal from './MarketplaceUploadMediaModal';
import { ModalTypes } from '@/components/modal/constants/ModalTypes';
import { toast } from '@/components/toast/Toast';
import { useModalContext } from '@/context/ModalContext';
import type { components } from '@/lib/gen';

import MarketplaceListingPreview from '../shared/MarketplaceListingPreview';

// Use generated API types
type ProjectResponse = components['schemas']['ProjectResponse'];

// Note: ProjectMessage types are handled by the API based on sender_role

// Utility functions for color handling
const getHashValue = (seed: string) => {
  const x = Math.sin(
    seed.split('').reduce((acc, char) => {
      return acc + char.charCodeAt(0);
    }, 0) * 10000
  );
  return x - Math.floor(x);
};

// Color palette from studio
const songSectionColors = {
  chorus: '#FF6A00',
  preChorus: '#02AF4A',
  verse: '#DE1677',
  bridge: '#D4BB03',
  outro: '#02AF4A',
  intro: '#02AF4A',
  hook: '#7251F7',
  instrumental: '#208BFF',
  song: '#02AF4A',
};

const colors = Object.values(songSectionColors);

const _pickRandomColor = (seed: string) => {
  const hashValue = getHashValue(seed);
  return colors[Math.floor(hashValue * colors.length) % colors.length];
};

// Time range color palette with vibrant alert-style tonal variations
const timeRangeColorSets = [
  { base: '#ff6b6b', light: '#ff9f9f', dark: '#e53e3e' }, // Vibrant red
  { base: '#4ecdc4', light: '#6dd5ce', dark: '#38b2ac' }, // Vibrant teal
  { base: '#45b7d1', light: '#6bc5d8', dark: '#3182ce' }, // Vibrant blue
  { base: '#96ceb4', light: '#a8d4c1', dark: '#68d391' }, // Vibrant green
  { base: '#feca57', light: '#fed47a', dark: '#f6ad55' }, // Vibrant yellow
  { base: '#a78bfa', light: '#c4b5fd', dark: '#8b5cf6' }, // Vibrant purple
  { base: '#fb7185', light: '#fda4af', dark: '#f43f5e' }, // Vibrant pink
  { base: '#06b6d4', light: '#22d3ee', dark: '#0891b2' }, // Vibrant cyan
];

// Get consistent tonal color set for a time range message based on its ID
const getTimeRangeColorSet = (messageId: string) => {
  const hashValue = getHashValue(messageId);
  return timeRangeColorSets[
    Math.floor(hashValue * timeRangeColorSets.length) %
      timeRangeColorSets.length
  ];
};

// Get unique color for time range based on its position in the project's time ranges
const _getUniqueTimeRangeColorSet = (
  messageId: string,
  allTimeRangeMessages: any[] // eslint-disable-line @typescript-eslint/no-explicit-any
) => {
  const timeRangeMessages = allTimeRangeMessages.filter(
    (msg) => msg.time_range
  );
  const messageIndex = timeRangeMessages.findIndex(
    (msg) => msg.id === messageId
  );

  // If message not found, fall back to ID-based assignment
  if (messageIndex === -1) {
    return getTimeRangeColorSet(messageId);
  }

  // Use index to ensure unique colors within the project
  return timeRangeColorSets[messageIndex % timeRangeColorSets.length];
};

// Timeline component with selection pane (like studio)
const TimelineWithSelectionPane = ({
  audioUrl,
  className = '',
  onSelectionChange,
  selection,
  clipId: _clipId,
  isLarge = false,
  timeRangeComments = [],
  onAddTimeRangeComment: _onAddTimeRangeComment,
  data: _data,
  initialPlaybackPosition = 0,
  autoPlay = false,
  externalAudioRef,
  externalIsPlaying,
}: {
  audioUrl: string;
  className?: string;
  onSelectionChange?: (change: { start: number; end?: number } | null) => void;
  selection?: { start: number; end?: number };
  clipId?: string;
  isLarge?: boolean;
  timeRangeComments?: Array<{
    start: number;
    end: number;
    content: string;
    mediaReferences?: Array<{
      id: string;
      type: 'audio' | 'image';
      url: string;
      name: string;
    }>;
  }>;
  onAddTimeRangeComment?: (comment: string) => void;
  data?: any; // eslint-disable-line @typescript-eslint/no-explicit-any
  initialPlaybackPosition?: number;
  autoPlay?: boolean;
  externalAudioRef?: React.RefObject<HTMLAudioElement | null>;
  externalIsPlaying?: boolean;
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const internalAudioRef = useRef<HTMLAudioElement>(null);
  const audioRef = externalAudioRef || internalAudioRef;
  const [isLoading, setIsLoading] = useState(true);
  const [waveformData, setWaveformData] = useState<number[]>([]);
  const [duration, setDuration] = useState<number>(0);
  const [isDragging, setIsDragging] = useState(false);
  const [startPosition, setStartPosition] = useState<number | null>(null);
  const [endPosition, setEndPosition] = useState<number | null>(null);
  const [inputStartPosition, setInputStartPosition] = useState<number | null>(
    null
  );
  const [waveformColor, setWaveformColor] = useState<string>('#726e6c');

  // Audio playback state
  const [isPlaying, setIsPlaying] = useState(externalIsPlaying ?? false);
  const [progress, setProgress] = useState(0);

  // Sync isPlaying with external state
  useEffect(() => {
    if (externalIsPlaying !== undefined) {
      setIsPlaying(externalIsPlaying);
    }
  }, [externalIsPlaying]);

  // Set duration and track progress from external audio
  useEffect(() => {
    if (!externalAudioRef?.current) return;

    const audio = externalAudioRef.current;

    const updateDuration = () => {
      if (audio.duration) {
        setDuration(audio.duration);
      }
    };

    const handleTimeUpdate = () => {
      if (audio.duration) {
        setProgress(audio.currentTime / audio.duration);
      }
    };

    const handleEnded = () => {
      setProgress(0);
    };

    // Set duration if already loaded
    updateDuration();

    // Listen for events
    audio.addEventListener('loadedmetadata', updateDuration);
    audio.addEventListener('timeupdate', handleTimeUpdate);
    audio.addEventListener('ended', handleEnded);

    return () => {
      audio.removeEventListener('loadedmetadata', updateDuration);
      audio.removeEventListener('timeupdate', handleTimeUpdate);
      audio.removeEventListener('ended', handleEnded);
    };
  }, [externalAudioRef]);

  // Set waveform to purple color
  useEffect(() => {
    setWaveformColor('#7251F7'); // Purple color
  }, []);

  // Audio playback effects
  useEffect(() => {
    if (!audioRef.current) return;

    const audio = audioRef.current;

    const handleTimeUpdate = () => {
      if (audio.duration) {
        setProgress(audio.currentTime / audio.duration);
      }
    };

    const handleEnded = () => {
      setIsPlaying(false);
      setProgress(0);
    };

    audio.addEventListener('timeupdate', handleTimeUpdate);
    audio.addEventListener('ended', handleEnded);

    return () => {
      audio.removeEventListener('timeupdate', handleTimeUpdate);
      audio.removeEventListener('ended', handleEnded);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // Handle initial playback position and auto-play (only if using internal audio)
  useEffect(() => {
    if (externalAudioRef || !audioRef.current || !duration) return;

    const audio = audioRef.current;

    // Set initial position
    if (initialPlaybackPosition > 0 && initialPlaybackPosition < duration) {
      audio.currentTime = initialPlaybackPosition;
      setProgress(initialPlaybackPosition / duration);
    }

    // Auto-play if requested
    if (autoPlay) {
      audio.play().catch((error) => {
        console.error('Auto-play failed:', error);
      });
      setIsPlaying(true);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [duration, initialPlaybackPosition, autoPlay, externalAudioRef]);

  // Generate waveform data from real audio
  useEffect(() => {
    if (!audioUrl) return;

    const generateWaveform = async () => {
      try {
        setIsLoading(true);

        // Fetch and analyze real audio using Web Audio API
        const response = await fetch(audioUrl);
        const arrayBuffer = await response.arrayBuffer();
        const audioContext = new (window.AudioContext ||
          (window as unknown as { webkitAudioContext: typeof AudioContext })
            .webkitAudioContext)();
        const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);

        setDuration(audioBuffer.duration);

        // Generate waveform data with high resolution (1000 data points)
        const channelData = audioBuffer.getChannelData(0);
        const samples = channelData.length;
        const dataPoints = 1000;
        const blockSize = Math.floor(samples / dataPoints);
        const waveform: number[] = [];

        for (let i = 0; i < dataPoints; i++) {
          const start = i * blockSize;
          const end = start + blockSize;
          let sumSquares = 0;
          let maxAmplitude = 0;

          // Calculate RMS (Root Mean Square) for better visual representation
          for (let j = start; j < end; j++) {
            const amplitude = Math.abs(channelData[j]);
            sumSquares += amplitude * amplitude;
            maxAmplitude = Math.max(maxAmplitude, amplitude);
          }

          // Use RMS with some peak emphasis for visual detail
          const rms = Math.sqrt(sumSquares / blockSize);
          const combined = rms * 0.7 + maxAmplitude * 0.3;
          waveform.push(combined);
        }

        // Normalize to 0.1-0.9 range for consistent visual quality
        const maxValue = Math.max(...waveform, 0.0001);
        const minValue = Math.min(...waveform, 0);
        const range = maxValue - minValue || 1;

        const normalizedWaveform = waveform.map(
          (value) => ((value - minValue) / range) * 0.8 + 0.1
        );

        setWaveformData(normalizedWaveform);
      } catch (error) {
        console.error('Error generating waveform:', error);
        setWaveformData([]);
      } finally {
        setIsLoading(false);
      }
    };

    generateWaveform();
  }, [audioUrl, isLarge]);

  useEffect(() => {
    if (!waveformData.length || !canvasRef.current) return;

    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    if (!ctx) return;

    const width = canvas.width;
    const height = canvas.height;
    const centerY = height / 2;

    // Clear canvas
    ctx.clearRect(0, 0, width, height);

    // Draw waveform as area chart with gradient
    const gradient = ctx.createLinearGradient(0, 0, 0, height);
    gradient.addColorStop(0, waveformColor);
    gradient.addColorStop(1, waveformColor + '80');
    ctx.fillStyle = gradient;
    ctx.beginPath();

    // Start at the left edge
    ctx.moveTo(0, centerY);

    // Draw the top half of the waveform
    waveformData.forEach((value, index) => {
      const x = (index / (waveformData.length - 1)) * width;
      const amplitude = (value / Math.max(...waveformData)) * (height * 0.4);
      const y = centerY - amplitude;
      ctx.lineTo(x, y);
    });

    // Draw the bottom half of the waveform (mirrored)
    for (let i = waveformData.length - 1; i >= 0; i--) {
      const x = (i / (waveformData.length - 1)) * width;
      const amplitude =
        (waveformData[i] / Math.max(...waveformData)) * (height * 0.4);
      const y = centerY + amplitude;
      ctx.lineTo(x, y);
    }

    // Close the path back to the start
    ctx.lineTo(0, centerY);
    ctx.closePath();
    ctx.fill();

    // Draw progress line
    if (progress > 0) {
      ctx.fillStyle = '#ffffff';
      const progressX = progress * width;
      ctx.fillRect(progressX - 1, 0, 2, height);
    }

    // Draw time range comments as indicators
    timeRangeComments.forEach((comment, index) => {
      const startX = (comment.start / duration) * width;
      const endX = (comment.end / duration) * width;

      // Use unique color set based on position
      const colorSet = timeRangeColorSets[index % timeRangeColorSets.length];

      // Comment indicator background
      ctx.fillStyle = colorSet.base + '40'; // 25% opacity
      ctx.fillRect(startX, 0, endX - startX, height);

      // Comment indicator border
      ctx.strokeStyle = colorSet.base;
      ctx.lineWidth = 2;
      ctx.strokeRect(startX, 0, endX - startX, height);

      // Comment indicator dot at the top
      ctx.fillStyle = colorSet.base;
      ctx.beginPath();
      ctx.arc(startX + (endX - startX) / 2, 8, 4, 0, 2 * Math.PI);
      ctx.fill();
    });

    // Draw selection overlay
    if (selection && selection.start !== undefined) {
      const startX = (selection.start / duration) * width;
      const endX = selection.end ? (selection.end / duration) * width : startX;

      // Selection background
      ctx.fillStyle = 'rgba(255, 255, 255, 0.2)';
      ctx.fillRect(startX, 0, endX - startX, height);

      // Selection border
      ctx.strokeStyle = '#ffffff';
      ctx.lineWidth = 2;
      ctx.strokeRect(startX, 0, endX - startX, height);
    }

    // Draw current drag selection
    if (isDragging && startPosition !== null && endPosition !== null) {
      const startX = Math.min(startPosition, endPosition);
      const endX = Math.max(startPosition, endPosition);

      // Drag selection background
      ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
      ctx.fillRect(startX, 0, endX - startX, height);

      // Drag selection border
      ctx.strokeStyle = '#ffffff';
      ctx.lineWidth = 2;
      ctx.strokeRect(startX, 0, endX - startX, height);
    }
  }, [
    waveformData,
    selection,
    isDragging,
    startPosition,
    endPosition,
    duration,
    waveformColor,
    progress,
    timeRangeComments,
  ]);

  const handleMouseDown = (e: React.MouseEvent<HTMLCanvasElement>) => {
    if (!canvasRef.current) return;

    const _rect = canvasRef.current.getBoundingClientRect();
    const x = e.clientX - _rect.left;
    const relativeX = (x / _rect.width) * canvasRef.current.width;

    setInputStartPosition(relativeX);
    setStartPosition(relativeX);
    setEndPosition(relativeX);
    setIsDragging(true);
  };

  const handleMouseMove = (e: React.MouseEvent<HTMLCanvasElement>) => {
    if (!isDragging || !canvasRef.current || inputStartPosition === null)
      return;

    const _rect = canvasRef.current.getBoundingClientRect();
    const x = e.clientX - _rect.left;
    const relativeX = (x / _rect.width) * canvasRef.current.width;

    setEndPosition(relativeX);
  };

  const handleMouseUp = () => {
    if (
      !isDragging ||
      !canvasRef.current ||
      inputStartPosition === null ||
      endPosition === null
    ) {
      setIsDragging(false);
      return;
    }

    const _rect = canvasRef.current.getBoundingClientRect();
    const start = Math.min(inputStartPosition, endPosition);
    const end = Math.max(inputStartPosition, endPosition);

    const startTime = (start / canvasRef.current.width) * duration;
    const endTime = (end / canvasRef.current.width) * duration;

    onSelectionChange?.({
      start: startTime,
      end: endTime,
    });

    setIsDragging(false);
  };

  const handleCanvasClick = (e: React.MouseEvent<HTMLCanvasElement>) => {
    if (!canvasRef.current || isDragging) return;

    const _rect = canvasRef.current.getBoundingClientRect();
    const x = e.clientX - _rect.left;
    const relativeX = (x / _rect.width) * canvasRef.current.width;
    const clickTime = (relativeX / canvasRef.current.width) * duration;

    // Seek to clicked position
    if (audioRef.current) {
      audioRef.current.currentTime = clickTime;
      setProgress(clickTime);
    }
  };

  const togglePlayPause = async () => {
    if (!audioRef.current) return;

    if (isPlaying) {
      audioRef.current.pause();
      setIsPlaying(false);
    } else {
      try {
        await audioRef.current.play();
        setIsPlaying(true);
      } catch (error) {
        console.error('Playback failed:', error);
        setIsPlaying(false);
      }
    }
  };

  if (isLoading) {
    return (
      <div className={`space-y-4 ${className}`}>
        <div className='flex items-center gap-3'>
          {/* Placeholder for play button */}
          <div className='h-10 w-10' />

          {/* Loading state matching canvas dimensions */}
          <div
            className='flex flex-1 items-center justify-center rounded'
            style={{ height: isLarge ? 128 : 64 }}
          >
            <div className='flex items-center gap-2 text-foreground-secondary'>
              <svg
                className='h-4 w-4 animate-spin'
                fill='none'
                viewBox='0 0 24 24'
              >
                <circle
                  className='opacity-25'
                  cx='12'
                  cy='12'
                  r='10'
                  stroke='currentColor'
                  strokeWidth='4'
                />
                <path
                  className='opacity-75'
                  fill='currentColor'
                  d='M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z'
                />
              </svg>
              Loading waveform...
            </div>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={`space-y-4 ${className}`}>
      {/* Play Button and Timeline */}
      <div className='flex items-center gap-3'>
        {/* Play Button */}
        <button
          onClick={togglePlayPause}
          className='flex h-10 w-10 items-center justify-center rounded-full bg-accent-brand text-white transition-colors hover:bg-accent-brand/90'
        >
          {isPlaying ? (
            <svg className='h-5 w-5' fill='currentColor' viewBox='0 0 24 24'>
              <path d='M6 4h4v16H6V4zm8 0h4v16h-4V4z' />
            </svg>
          ) : (
            <svg
              className='ml-0.5 h-5 w-5'
              fill='currentColor'
              viewBox='0 0 24 24'
            >
              <path d='M8 5v14l11-7z' />
            </svg>
          )}
        </button>

        {/* Timeline Canvas */}
        <div className='relative flex-1'>
          <canvas
            ref={canvasRef}
            width={800}
            height={isLarge ? 128 : 64}
            className='w-full cursor-crosshair rounded'
            onMouseDown={handleMouseDown}
            onMouseMove={handleMouseMove}
            onMouseUp={handleMouseUp}
            onClick={handleCanvasClick}
          />

          {/* Time markers for large version */}
          {isLarge && (
            <div className='absolute right-0 bottom-0 left-0 flex justify-between px-2 pb-1 text-xs text-foreground-tertiary'>
              <span>0:00</span>
              <span>
                {Math.floor(duration / 60)}:
                {(duration % 60).toFixed(0).padStart(2, '0')}
              </span>
            </div>
          )}
        </div>
      </div>

      {/* Hidden Audio Element (only render if not using external audio) */}
      {!externalAudioRef && (
        <audio
          ref={audioRef}
          src={audioUrl}
          preload='metadata'
          onTimeUpdate={() => {
            if (audioRef.current?.duration) {
              setProgress(
                audioRef.current.currentTime / audioRef.current.duration
              );
            }
          }}
          onPlay={() => setIsPlaying(true)}
          onPause={() => setIsPlaying(false)}
          onEnded={() => {
            setIsPlaying(false);
            setProgress(0);
          }}
          onLoadedMetadata={() => {
            if (audioRef.current) {
              setDuration(audioRef.current.duration);
            }
          }}
        />
      )}
    </div>
  );
};

const MarketplaceCreateProjectModal: React.FC = () => {
  const { closeModal, getModalData } = useModalContext();
  const data = getModalData(ModalTypes.MARKETPLACE_CREATE_PROJECT);
  const router = useRouter();
  const { apiClient, session, playbar } = useStores();

  const onClose = () => {
    closeModal(ModalTypes.MARKETPLACE_CREATE_PROJECT);
  };

  const [_message, _setMessage] = useState('');
  const [projectBounty, setProjectBounty] = useState(20);
  const [isLoading, setIsLoading] = useState(false);
  const [attachedMedia, setAttachedMedia] = useState<
    Array<{ id: string; type: 'audio' | 'image'; url: string; name: string }>
  >([]);
  const [userCreditBalance, setUserCreditBalance] = useState(1000); // Default fallback

  // Waveform selection state
  const [waveformSelection, setWaveformSelection] = useState<{
    start: number;
    end?: number;
  } | null>(null);
  const [timeRangePrompts, setTimeRangePrompts] = useState<
    Array<{
      start: number;
      end: number;
      content: string;
      addedAt: number; // Timestamp for sorting
      mediaReferences?: Array<{
        id: string;
        type: 'audio' | 'image';
        url: string;
        name: string;
      }>;
    }>
  >([]);
  const [generalPrompts, setGeneralPrompts] = useState<
    Array<{
      content: string;
      addedAt: number; // Timestamp for sorting
      mediaReferences?: Array<{
        id: string;
        type: 'audio' | 'image';
        url: string;
        name: string;
      }>;
    }>
  >([]);
  const [requestsPage, setRequestsPage] = useState(1);
  const [_showInitialPrompt, _setShowInitialPrompt] = useState(true);
  const [generalMessageText, setGeneralMessageText] = useState('');
  const [isSubmittingGeneralMessage, setIsSubmittingGeneralMessage] =
    useState(false);
  const [pendingMediaReferences, setPendingMediaReferences] = useState<
    Array<{ id: string; type: 'audio' | 'image'; url: string; name: string }>
  >([]);
  const [showHowItWorks, setShowHowItWorks] = useState(false);
  const [currentStep, setCurrentStep] = useState(1); // 1 = specific requests, 2 = timeline, 3 = project bounty, 4 = instructions, 5 = listing preview
  const [artisticDirection, setArtisticDirection] = useState('');
  const [listingSummary, setListingSummary] = useState('');
  const [timelineDays, setTimelineDays] = useState(7); // Default to 7 days
  const [projectTitle, setProjectTitle] = useState(data?.clipTitle || '');

  // Persistent audio state across steps
  const audioRef = useRef<HTMLAudioElement>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const capturedPositionRef = useRef<number>(0);
  const capturedClipIdRef = useRef<string | null>(null);
  const hasCapturedPlaybarRef = useRef(false);

  // Capture playbar position and stop playbar audio when modal opens
  useEffect(() => {
    if (data && !hasCapturedPlaybarRef.current) {
      // Mark as captured to prevent running twice
      hasCapturedPlaybarRef.current = true;

      // Capture current playback position and clip ID in refs for immediate use
      capturedPositionRef.current = playbar.currentTime || 0;
      capturedClipIdRef.current = playbar.clip?.id || null;
      // Immediately unset to stop playback
      playbar.unsetClip();
    }

    // Reset capture flag when modal closes so it can re-capture on next open
    if (!data) {
      hasCapturedPlaybarRef.current = false;
    }
    // Only run once when modal opens (when data becomes available)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [data]);

  // Initialize persistent audio with auto-play
  useEffect(() => {
    if (!audioRef.current || !data?.clipUrl) return;

    const audio = audioRef.current;
    const capturedPosition = capturedPositionRef.current;
    const capturedClipId = capturedClipIdRef.current;

    const handleLoadedMetadata = () => {
      // Only restore position and auto-play if the clip that was playing is the same as the current clip
      const isSameClip = capturedClipId === data.clipId;

      if (capturedPosition > 0 && isSameClip) {
        // Set initial position
        audio.currentTime = capturedPosition;

        // Auto-play since it's the same clip that was already playing
        audio.play().catch((error) => {
          console.error('Auto-play failed:', error);
        });
        setIsPlaying(true);
      }
    };

    const handlePlay = () => setIsPlaying(true);
    const handlePause = () => setIsPlaying(false);

    // If metadata is already loaded, set position immediately
    if (audio.readyState >= 1) {
      handleLoadedMetadata();
    } else {
      audio.addEventListener('loadedmetadata', handleLoadedMetadata);
    }

    audio.addEventListener('play', handlePlay);
    audio.addEventListener('pause', handlePause);

    return () => {
      audio.removeEventListener('loadedmetadata', handleLoadedMetadata);
      audio.removeEventListener('play', handlePlay);
      audio.removeEventListener('pause', handlePause);
    };
  }, [data?.clipUrl, data?.clipId]);

  // Spacebar to toggle play/pause (works across all steps)
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (
        e.code === 'Space' &&
        !(document.activeElement instanceof HTMLInputElement) &&
        !(document.activeElement instanceof HTMLTextAreaElement)
      ) {
        e.preventDefault();
        if (!audioRef.current) return;

        if (isPlaying) {
          audioRef.current.pause();
          setIsPlaying(false);
        } else {
          audioRef.current
            .play()
            .then(() => {
              setIsPlaying(true);
            })
            .catch((error) => {
              console.error('Playback failed:', error);
              setIsPlaying(false);
            });
        }
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [isPlaying]);

  // Auto-attach the original clip when modal opens
  useEffect(() => {
    if (data) {
      setAttachedMedia([
        {
          id: data.clipId,
          type: 'audio',
          url: data.clipUrl,
          name: data.clipTitle || 'Original Clip',
        },
      ]);
      // Set project title from clip title only on initial load
      setProjectTitle(data.clipTitle || '');
    }
  }, [data]); // Only run when data changes, not when projectTitle changes

  // Fetch user credit balance and adjust bounty if needed
  useEffect(() => {
    // Get user credit balance from session store
    const actualBalance = session.credits || 0;
    const maxBounty = Math.min(2000, actualBalance);
    setUserCreditBalance(actualBalance);

    // Ensure project bounty is at least 20 and not more than max bounty
    if (projectBounty < 20) {
      setProjectBounty(20);
    } else if (projectBounty > maxBounty) {
      setProjectBounty(Math.max(20, maxBounty));
    }
  }, [projectBounty, session.credits]);

  const _removeAttachedMedia = (id: string) => {
    setAttachedMedia((prev) => prev.filter((media) => media.id !== id));
  };

  const _handleFileDrop = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    const files = e.dataTransfer.files;
    if (!files || !data) return;

    const referenceMediaCount = attachedMedia.filter(
      (media) => media.id !== data.clipId
    ).length;
    const remainingSlots = 4 - referenceMediaCount;
    const filesToAdd = Array.from(files).slice(0, remainingSlots);

    filesToAdd.forEach((file) => {
      const url = URL.createObjectURL(file);
      const type = file.type.startsWith('audio/') ? 'audio' : 'image';
      setAttachedMedia((prev) => [
        ...prev,
        {
          id: `upload_${Date.now()}_${Math.random()}`,
          type,
          url,
          name: file.name,
        },
      ]);
    });
  };

  const _handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
    e.preventDefault();
  };

  // Waveform selection handlers
  const handleWaveformSelectionChange = (
    selection: { start: number; end?: number } | null
  ) => {
    setWaveformSelection(selection);
  };

  const handleAddTimeRangePrompt = async (content: string) => {
    if (!waveformSelection || !content.trim()) return;

    // Check 10 request limit
    if (timeRangePrompts.length + generalPrompts.length >= 10) {
      alert('Maximum of 10 requests allowed per project');
      return;
    }

    const newPrompt = {
      start: waveformSelection.start,
      end: waveformSelection.end || waveformSelection.start,
      content: content.trim(),
      addedAt: Date.now(), // Track when added for sorting
      mediaReferences:
        pendingMediaReferences.length > 0
          ? [...pendingMediaReferences]
          : undefined,
    };

    setTimeRangePrompts((prev) => [...prev, newPrompt]);
    setWaveformSelection(null); // Clear selection after adding prompt
    setGeneralMessageText(''); // Clear input text
    setPendingMediaReferences([]); // Clear pending media
    _setShowInitialPrompt(false);
    // Reset to last page to show the newly added prompt
    const totalPrompts = timeRangePrompts.length + generalPrompts.length + 1;
    const totalPages = Math.ceil(totalPrompts / 3);
    setRequestsPage(totalPages);
  };

  const handleRemoveTimeRangePrompt = (index: number) => {
    setTimeRangePrompts((prev) => prev.filter((_, i) => i !== index));
  };

  const handleAddGeneralPrompt = async () => {
    if (!generalMessageText.trim()) return;

    // Check 10 request limit
    if (timeRangePrompts.length + generalPrompts.length >= 10) {
      toast({
        title: 'Request limit reached',
        description: 'Maximum of 10 requests allowed per project',
        status: 'warning',
        duration: 4000,
        isClosable: true,
      });
      return;
    }

    setIsSubmittingGeneralMessage(true);
    try {
      const newPrompt = {
        content: generalMessageText.trim(),
        addedAt: Date.now(), // Track when added for sorting
        mediaReferences:
          pendingMediaReferences.length > 0
            ? [...pendingMediaReferences]
            : undefined,
      };

      setGeneralPrompts((prev) => [...prev, newPrompt]);
      setGeneralMessageText(''); // Clear input text
      setPendingMediaReferences([]); // Clear pending media
      _setShowInitialPrompt(false);
      // Reset to last page to show the newly added prompt
      const totalPrompts = timeRangePrompts.length + generalPrompts.length + 1;
      const totalPages = Math.ceil(totalPrompts / 3);
      setRequestsPage(totalPages);
    } catch (error) {
      console.error('Error adding general prompt:', error);
    } finally {
      setIsSubmittingGeneralMessage(false);
    }
  };

  const handleRemoveGeneralPrompt = (index: number) => {
    setGeneralPrompts((prev) => prev.filter((_, i) => i !== index));
  };

  const handleRemovePendingMedia = (id: string) => {
    setPendingMediaReferences((prev) =>
      prev.filter((media) => media.id !== id)
    );
  };

  const handleNext = () => {
    if (timeRangePrompts.length === 0 && generalPrompts.length === 0) {
      toast({
        title: 'No requests added',
        description:
          'Please add at least one specific request for your project.',
        status: 'warning',
        duration: 4000,
        isClosable: true,
      });
      return;
    }
    setCurrentStep(2); // Go to Timeline step
  };

  // Helper function to get first 20 words with ellipsis
  const getFirstNWords = (text: string, n: number = 20): string => {
    if (!text.trim()) return '';
    const words = text.trim().split(/\s+/);
    if (words.length <= n) return text.trim();
    return words.slice(0, n).join(' ') + '...';
  };

  // Auto-populate summary from artistic direction when moving to step 5
  useEffect(() => {
    if (
      currentStep === 5 &&
      artisticDirection.trim() &&
      !listingSummary.trim()
    ) {
      setListingSummary(getFirstNWords(artisticDirection, 20));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [currentStep]); // Only run when step changes to 5

  const _handleBack = () => {
    setCurrentStep(1);
  };

  const handleSubmit = async () => {
    if (!data) return;

    // Check if user has enough credits
    if (projectBounty > userCreditBalance) {
      toast({
        title: 'Insufficient credits',
        description: `You have ${userCreditBalance} credits but need ${projectBounty} credits for this project.`,
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
      return;
    }

    setIsLoading(true);

    try {
      // Prepare initial messages
      const initialMessages = [];

      // Add general prompts as initial messages
      if (generalPrompts.length > 0) {
        for (const generalPrompt of generalPrompts) {
          initialMessages.push({
            content: generalPrompt.content,
            // No time_range for general messages
          });
        }
      }

      // Add time range prompts as initial messages
      if (timeRangePrompts.length > 0) {
        for (const timeRangePrompt of timeRangePrompts) {
          initialMessages.push({
            content: timeRangePrompt.content,
            time_range: {
              start: timeRangePrompt.start,
              end: timeRangePrompt.end,
            },
          });
        }
      }

      // Calculate deadline from timeline days
      // Ensure timelineDays is valid (at least 1 day)
      const validTimelineDays = Math.max(1, Math.min(90, timelineDays || 7));
      const deadlineDate = new Date();
      deadlineDate.setDate(deadlineDate.getDate() + validTimelineDays);
      deadlineDate.setHours(23, 59, 59, 999); // Set to end of day

      const projectResponse = await apiClient.POST(
        '/api/marketplace/projects/',
        {
          body: {
            title: projectTitle.trim() || data.clipTitle,
            description: artisticDirection.trim() || '', // Full description (artistic direction/instructions)
            summary: listingSummary.trim() || '', // Marketplace summary
            credit_bounty: projectBounty,
            original_clip_id: data.clipId,
            deadline: deadlineDate.toISOString(),
            initial_messages: initialMessages,
          },
        }
      );

      // Type guard to check for error response
      if ('error' in projectResponse && projectResponse.error) {
        throw new Error('Failed to create project. Please try again.');
      }

      // Type guard to check for successful response
      if (!('data' in projectResponse) || !projectResponse.data) {
        throw new Error('Server error. Please try again.');
      }

      const projectId = (projectResponse.data as ProjectResponse).id;

      // Refresh session credits after successful project creation
      await session.loadSubscriptionInfo();

      // Redirect to project page and then close modal
      router.push(`/marketplace/project/${projectId}`);
      // Small delay to ensure navigation starts before closing modal
      setTimeout(() => {
        onClose();
      }, 100);
    } catch (err) {
      console.error('Error creating project:', err);
      const errorMessage =
        err instanceof Error ? err.message : 'Failed to create project';
      toast({
        title: 'Failed to create project',
        description: errorMessage,
        status: 'error',
        duration: 5000,
        isClosable: true,
      });
    } finally {
      setIsLoading(false);
    }
  };

  if (!data) return null;

  return (
    <div className='fixed inset-0 z-50 flex items-center justify-center'>
      {/* Hidden persistent audio element that plays across all steps */}
      {data?.clipUrl && (
        <audio
          ref={audioRef}
          src={data.clipUrl}
          preload='metadata'
          className='hidden'
        />
      )}

      {/* Backdrop */}
      <div
        className='absolute inset-0 bg-black/50 backdrop-blur-sm'
        onClick={onClose}
        onKeyDown={(e) => e.key === 'Escape' && onClose()}
        role='button'
        tabIndex={0}
        aria-label='Close modal'
      />

      {/* Modal */}
      <div className='relative mx-4 flex h-[85vh] w-full max-w-6xl flex-col rounded-2xl bg-background-primary'>
        {/* Scrollable Content Area */}
        <div className='flex-1 overflow-y-auto p-8 pb-24'>
          {/* Header */}
          <div className='mb-6'>
            <div className='flex items-center justify-between'>
              <div className='flex items-center gap-4'>
                <h2 className='text-lg font-semibold text-foreground-primary'>
                  Get Help from the Marketplace
                </h2>
                <button
                  onClick={() => setShowHowItWorks(!showHowItWorks)}
                  className='text-xs font-medium text-pink-500 transition-colors hover:text-pink-600'
                >
                  How it works
                </button>

                {/* Audio Playing Indicator - Only show on steps 2, 3, 4 */}
                {currentStep !== 1 && (
                  <button
                    onClick={() => {
                      if (!audioRef.current) return;
                      if (isPlaying) {
                        audioRef.current.pause();
                        setIsPlaying(false);
                      } else {
                        audioRef.current
                          .play()
                          .then(() => {
                            setIsPlaying(true);
                          })
                          .catch((error) => {
                            console.error('Playback failed:', error);
                            setIsPlaying(false);
                          });
                      }
                    }}
                    className='flex cursor-pointer items-center gap-0.5 transition-opacity hover:opacity-80'
                    aria-label={isPlaying ? 'Pause audio' : 'Play audio'}
                  >
                    {isPlaying ? (
                      <>
                        {[0, 1, 2, 3].map((i) => (
                          <div
                            key={i}
                            className='w-0.5 rounded-full'
                            style={{
                              backgroundColor: '#7251F7',
                              height: '12px',
                              animation: `audioBar 0.6s ease-in-out infinite ${i * 0.1}s`,
                            }}
                          />
                        ))}
                        <style>{`
                          @keyframes audioBar {
                            0%, 100% { height: 4px; opacity: 0.6; }
                            50% { height: 12px; opacity: 1; }
                          }
                        `}</style>
                      </>
                    ) : (
                      <div className='h-3 w-3' />
                    )}
                  </button>
                )}
              </div>

              <button
                onClick={onClose}
                className='text-foreground-secondary transition-colors hover:text-foreground-primary'
              >
                <svg
                  className='h-6 w-6'
                  fill='none'
                  stroke='currentColor'
                  viewBox='0 0 24 24'
                >
                  <path
                    strokeLinecap='round'
                    strokeLinejoin='round'
                    strokeWidth={2}
                    d='M6 18L18 6M6 6l12 12'
                  />
                </svg>
              </button>
            </div>

            {/* Horizontal Divider */}
            <div className='mt-4 border-t border-border-primary' />

            {/* Step Indicator */}
            <div className='mt-4 flex items-center justify-center'>
              <div className='flex items-center gap-4'>
                <div
                  className={`flex items-center gap-2 ${currentStep >= 1 ? 'text-foreground-primary' : 'text-foreground-tertiary'}`}
                >
                  <div
                    className={`flex h-8 w-8 items-center justify-center rounded-full text-sm font-medium ${
                      currentStep >= 1
                        ? 'bg-pink-500 text-white'
                        : 'bg-background-secondary text-foreground-tertiary'
                    }`}
                  >
                    1
                  </div>
                  <span className='text-sm font-medium'>Specific Requests</span>
                </div>
                <div
                  className={`h-0.5 w-8 ${currentStep >= 2 ? 'bg-pink-500' : 'bg-background-secondary'}`}
                />
                <div
                  className={`flex items-center gap-2 ${currentStep >= 2 ? 'text-foreground-primary' : 'text-foreground-tertiary'}`}
                >
                  <div
                    className={`flex h-8 w-8 items-center justify-center rounded-full text-sm font-medium ${
                      currentStep >= 2
                        ? 'bg-pink-500 text-white'
                        : 'bg-background-secondary text-foreground-tertiary'
                    }`}
                  >
                    2
                  </div>
                  <span className='text-sm font-medium'>Timeline</span>
                </div>
                <div
                  className={`h-0.5 w-8 ${currentStep >= 3 ? 'bg-pink-500' : 'bg-background-secondary'}`}
                />
                <div
                  className={`flex items-center gap-2 ${currentStep >= 3 ? 'text-foreground-primary' : 'text-foreground-tertiary'}`}
                >
                  <div
                    className={`flex h-8 w-8 items-center justify-center rounded-full text-sm font-medium ${
                      currentStep >= 3
                        ? 'bg-pink-500 text-white'
                        : 'bg-background-secondary text-foreground-tertiary'
                    }`}
                  >
                    3
                  </div>
                  <span className='text-sm font-medium'>Project Bounty</span>
                </div>
                <div
                  className={`h-0.5 w-8 ${currentStep >= 4 ? 'bg-pink-500' : 'bg-background-secondary'}`}
                />
                <div
                  className={`flex items-center gap-2 ${currentStep >= 4 ? 'text-foreground-primary' : 'text-foreground-tertiary'}`}
                >
                  <div
                    className={`flex h-8 w-8 items-center justify-center rounded-full text-sm font-medium ${
                      currentStep >= 4
                        ? 'bg-pink-500 text-white'
                        : 'bg-background-secondary text-foreground-tertiary'
                    }`}
                  >
                    4
                  </div>
                  <span className='text-sm font-medium'>Your Vision</span>
                </div>
                <div
                  className={`h-0.5 w-8 ${currentStep >= 5 ? 'bg-pink-500' : 'bg-background-secondary'}`}
                />
                <div
                  className={`flex items-center gap-2 ${currentStep >= 5 ? 'text-foreground-primary' : 'text-foreground-tertiary'}`}
                >
                  <div
                    className={`flex h-8 w-8 items-center justify-center rounded-full text-sm font-medium ${
                      currentStep >= 5
                        ? 'bg-pink-500 text-white'
                        : 'bg-background-secondary text-foreground-tertiary'
                    }`}
                  >
                    5
                  </div>
                  <span className='text-sm font-medium'>Listing Preview</span>
                </div>
              </div>
            </div>

            {/* Horizontal Divider */}
            <div className='mt-6 border-t border-border-primary' />
          </div>

          {/* How it works content */}
          {showHowItWorks && (
            <div className='mx-auto mb-6 max-w-2xl rounded-xl border border-pink-500/20 bg-pink-500/10 p-6'>
              <h3 className='mb-3 text-sm font-semibold text-foreground-primary'>
                How it works:
              </h3>
              <ul className='space-y-2 text-sm text-foreground-secondary'>
                <li className='flex items-start gap-2'>
                  <svg
                    className='mt-0.5 h-4 w-4 flex-shrink-0 text-pink-500'
                    fill='currentColor'
                    viewBox='0 0 20 20'
                  >
                    <path
                      fillRule='evenodd'
                      d='M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z'
                      clipRule='evenodd'
                    />
                  </svg>
                  <span>
                    Select specific time ranges on the waveform that you need
                    help with.
                  </span>
                </li>
                <li className='flex items-start gap-2'>
                  <svg
                    className='mt-0.5 h-4 w-4 flex-shrink-0 text-pink-500'
                    fill='currentColor'
                    viewBox='0 0 20 20'
                  >
                    <path
                      fillRule='evenodd'
                      d='M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z'
                      clipRule='evenodd'
                    />
                  </svg>
                  <span>
                    Add general instructions for the entire song (optional)
                  </span>
                </li>
                <li className='flex items-start gap-2'>
                  <svg
                    className='mt-0.5 h-4 w-4 flex-shrink-0 text-pink-500'
                    fill='currentColor'
                    viewBox='0 0 20 20'
                  >
                    <path
                      fillRule='evenodd'
                      d='M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z'
                      clipRule='evenodd'
                    />
                  </svg>
                  <span>
                    Editors will see your requests and submit their work
                  </span>
                </li>
                <li className='flex items-start gap-2'>
                  <svg
                    className='mt-0.5 h-4 w-4 flex-shrink-0 text-pink-500'
                    fill='currentColor'
                    viewBox='0 0 20 20'
                  >
                    <path
                      fillRule='evenodd'
                      d='M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z'
                      clipRule='evenodd'
                    />
                  </svg>
                  <span>
                    Credits are only transferred when you're satisfied
                  </span>
                </li>
              </ul>
            </div>
          )}

          {/* Step 1: Specific Requests */}
          {currentStep === 1 && (
            <div className='space-y-6'>
              <div className='mb-8 text-center'>
                <h3 className='mb-2 text-xl font-semibold text-foreground-primary'>
                  What do you need help with?
                </h3>
                <p className='text-sm text-foreground-secondary'>
                  Use the chat to describe what you need help with.
                </p>
              </div>

              <div className='grid grid-cols-1 gap-8 lg:grid-cols-3'>
                {/* Left Column - Waveform and Comments */}
                <div className='space-y-6 lg:col-span-2'>
                  {/* Original Audio Waveform */}
                  {data?.clipUrl && (
                    <div>
                      <div className='mb-3 flex items-center gap-2'>
                        <svg
                          className='h-5 w-5 text-accent-brand'
                          fill='currentColor'
                          viewBox='0 0 24 24'
                        >
                          <path d='M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z' />
                        </svg>
                        <h3 className='text-lg font-semibold text-foreground-primary'>
                          {data.clipTitle || 'Original Audio'}
                        </h3>
                      </div>
                      <div className='rounded-xl border border-border-primary bg-background-secondary p-4'>
                        <TimelineWithSelectionPane
                          audioUrl={data.clipUrl}
                          clipId={data.clipId}
                          selection={waveformSelection || undefined}
                          onSelectionChange={handleWaveformSelectionChange}
                          isLarge={true}
                          className='w-full'
                          timeRangeComments={timeRangePrompts}
                          onAddTimeRangeComment={handleAddTimeRangePrompt}
                          data={data}
                          initialPlaybackPosition={capturedPositionRef.current}
                          autoPlay={capturedPositionRef.current > 0}
                          externalAudioRef={audioRef}
                          externalIsPlaying={isPlaying}
                        />
                      </div>
                    </div>
                  )}

                  {/* Time Range Display */}
                  {waveformSelection && (
                    <div className='mb-3 rounded-lg border border-accent-brand/20 bg-accent-brand/5 p-3'>
                      <div className='mb-2 flex items-center justify-between'>
                        <div className='flex items-center gap-2'>
                          <div className='h-2 w-2 rounded-full bg-accent-brand'></div>
                          <span className='text-sm font-medium text-foreground-primary'>
                            Selected:{' '}
                            {(() => {
                              const start = waveformSelection.start;
                              const end =
                                waveformSelection.end ||
                                waveformSelection.start;
                              // If start and end are the same (or very close), show just one timestamp
                              if (Math.abs(start - end) < 0.01) {
                                return `${start.toFixed(1)}s`;
                              }
                              return `${start.toFixed(1)}s - ${end.toFixed(1)}s`;
                            })()}
                          </span>
                        </div>
                        <button
                          onClick={() => {
                            setWaveformSelection(null);
                            setPendingMediaReferences([]);
                          }}
                          className='text-xs text-foreground-tertiary transition-colors hover:text-foreground-primary'
                        >
                          ✕ Clear
                        </button>
                      </div>

                      {/* Pending Media References */}
                      {pendingMediaReferences.length > 0 && (
                        <div className='mt-2'>
                          <div className='mb-2 text-xs text-foreground-secondary'>
                            Audio references:
                          </div>
                          <div className='flex flex-wrap gap-2'>
                            {pendingMediaReferences.map((media) => (
                              <div
                                key={media.id}
                                className='flex items-center gap-1 rounded bg-background-primary px-2 py-1 text-xs'
                              >
                                <span className='text-foreground-secondary'>
                                  {media.name}
                                </span>
                                <button
                                  onClick={() =>
                                    handleRemovePendingMedia(media.id)
                                  }
                                  className='text-foreground-tertiary transition-colors hover:text-accent-red-on-primary'
                                >
                                  ✕
                                </button>
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  )}

                  {/* Single Line Message Input */}
                  <div className='relative'>
                    <input
                      type='text'
                      value={generalMessageText}
                      onChange={(e) => setGeneralMessageText(e.target.value)}
                      disabled={
                        timeRangePrompts.length + generalPrompts.length >= 10
                      }
                      placeholder={
                        timeRangePrompts.length + generalPrompts.length >= 10
                          ? 'Maximum 10 requests reached'
                          : waveformSelection
                            ? 'Describe what needs work in this section...'
                            : timeRangePrompts.length > 0 ||
                                generalPrompts.length > 0
                              ? 'Add any general notes or requirements...'
                              : 'What do you need help with?'
                      }
                      className='w-full rounded-lg border border-border-primary bg-transparent px-3 py-2 pr-10 text-sm text-foreground-primary placeholder-foreground-secondary focus:border-accent-brand focus:outline-none disabled:cursor-not-allowed disabled:opacity-50'
                      onKeyDown={(e) => {
                        if (e.key === 'Enter') {
                          e.preventDefault();
                          if (waveformSelection) {
                            handleAddTimeRangePrompt(generalMessageText);
                          } else {
                            handleAddGeneralPrompt();
                          }
                        }
                      }}
                    />

                    {/* Send button positioned at right of input */}
                    <div className='absolute top-1/2 right-0 flex -translate-y-1/2'>
                      <button
                        onClick={() => {
                          if (waveformSelection) {
                            handleAddTimeRangePrompt(generalMessageText);
                          } else {
                            handleAddGeneralPrompt();
                          }
                        }}
                        disabled={
                          !generalMessageText.trim() ||
                          isSubmittingGeneralMessage ||
                          timeRangePrompts.length + generalPrompts.length >= 10
                        }
                        className='flex h-8 w-8 items-center justify-center rounded-lg bg-accent-brand text-white transition-colors hover:bg-accent-brand/90 disabled:cursor-not-allowed disabled:opacity-50'
                      >
                        {isSubmittingGeneralMessage ? (
                          <svg
                            className='h-4 w-4 animate-spin'
                            fill='none'
                            viewBox='0 0 24 24'
                          >
                            <circle
                              className='opacity-25'
                              cx='12'
                              cy='12'
                              r='10'
                              stroke='currentColor'
                              strokeWidth='4'
                            />
                            <path
                              className='opacity-75'
                              fill='currentColor'
                              d='M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z'
                            />
                          </svg>
                        ) : (
                          <svg
                            className='h-4 w-4 rotate-45'
                            fill='none'
                            stroke='currentColor'
                            viewBox='0 0 24 24'
                          >
                            <path
                              strokeLinecap='round'
                              strokeLinejoin='round'
                              strokeWidth={2}
                              d='M12 19l9 2-9-18-9 18 9-2zm0 0v-8'
                            />
                          </svg>
                        )}
                      </button>
                    </div>
                  </div>
                </div>

                {/* Right Column - Instructions */}
                <div className='space-y-6'>
                  {/* Instructions */}
                  <div className='rounded-xl p-6'>
                    {(() => {
                      // Combine all prompts and sort by addedAt timestamp
                      const allPrompts = [
                        ...timeRangePrompts.map((p, i) => ({
                          ...p,
                          type: 'timeRange' as const,
                          originalIndex: i,
                        })),
                        ...generalPrompts.map((p, i) => ({
                          ...p,
                          type: 'general' as const,
                          originalIndex: i,
                        })),
                      ].sort((a, b) => a.addedAt - b.addedAt);

                      const itemsPerPage = 3;
                      const totalPages = Math.ceil(
                        allPrompts.length / itemsPerPage
                      );
                      const startIndex = (requestsPage - 1) * itemsPerPage;
                      const endIndex = startIndex + itemsPerPage;
                      const displayedPrompts = allPrompts.slice(
                        startIndex,
                        endIndex
                      );

                      return (
                        <div className='space-y-3'>
                          {/* Displayed Prompts */}
                          {displayedPrompts.map((prompt, displayIndex) => {
                            const globalIndex = startIndex + displayIndex;
                            const colorSet =
                              timeRangeColorSets[
                                globalIndex % timeRangeColorSets.length
                              ];

                            return (
                              <div
                                key={`${prompt.type}-${prompt.originalIndex}`}
                                className='rounded-lg border border-border-primary/50 bg-background-primary p-3'
                              >
                                <div className='mb-2 flex items-center justify-between'>
                                  <div className='flex items-center gap-2'>
                                    {prompt.type === 'timeRange' ? (
                                      <>
                                        <div
                                          className='h-2 w-2 rounded-full'
                                          style={{
                                            backgroundColor: colorSet.base,
                                          }}
                                        />
                                        <span className='text-xs font-medium text-foreground-primary'>
                                          {(() => {
                                            const start = prompt.start;
                                            const end = prompt.end;
                                            // If start and end are the same (or very close), show just one timestamp
                                            if (Math.abs(start - end) < 0.01) {
                                              return `${start.toFixed(1)}s`;
                                            }
                                            return `${start.toFixed(1)}s - ${end.toFixed(1)}s`;
                                          })()}
                                        </span>
                                      </>
                                    ) : (
                                      <>
                                        <div className='h-2 w-2 rounded-full bg-foreground-tertiary'></div>
                                        <span className='text-xs font-medium text-foreground-primary'>
                                          General
                                        </span>
                                      </>
                                    )}
                                  </div>
                                  <button
                                    onClick={() => {
                                      if (prompt.type === 'timeRange') {
                                        handleRemoveTimeRangePrompt(
                                          prompt.originalIndex
                                        );
                                      } else {
                                        handleRemoveGeneralPrompt(
                                          prompt.originalIndex
                                        );
                                      }
                                      // Reset to page 1 if current page becomes empty
                                      if (
                                        requestsPage > 1 &&
                                        displayedPrompts.length === 1
                                      ) {
                                        setRequestsPage(requestsPage - 1);
                                      }
                                    }}
                                    className='text-xs text-foreground-tertiary transition-colors hover:text-red-500'
                                  >
                                    ✕
                                  </button>
                                </div>
                                <p className='mb-2 text-sm text-foreground-secondary'>
                                  {prompt.content}
                                </p>

                                {/* Media References */}
                                {prompt.mediaReferences &&
                                  prompt.mediaReferences.length > 0 && (
                                    <div className='mt-2'>
                                      <div className='mb-1 text-xs text-foreground-tertiary'>
                                        Audio references:
                                      </div>
                                      <div className='flex flex-wrap gap-1'>
                                        {prompt.mediaReferences.map((media) => (
                                          <div
                                            key={media.id}
                                            className='flex items-center gap-1 rounded bg-background-secondary px-2 py-1 text-xs'
                                          >
                                            {media.type === 'audio' ? (
                                              <svg
                                                className='h-3 w-3 text-accent-brand'
                                                fill='currentColor'
                                                viewBox='0 0 24 24'
                                              >
                                                <path d='M12 3v10.55c-.59-.34-1.27-.55-2-.55-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4V7h4V3h-6z' />
                                              </svg>
                                            ) : (
                                              <svg
                                                className='h-3 w-3 text-accent-brand'
                                                fill='currentColor'
                                                viewBox='0 0 24 24'
                                              >
                                                <path d='M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z' />
                                              </svg>
                                            )}
                                            <span className='max-w-20 truncate text-foreground-secondary'>
                                              {media.name}
                                            </span>
                                          </div>
                                        ))}
                                      </div>
                                    </div>
                                  )}
                              </div>
                            );
                          })}

                          {/* Placeholder Cards - Always show 3 placeholders */}
                          {Array.from({
                            length: Math.max(0, 3 - displayedPrompts.length),
                          }).map((_, index) => (
                            <div
                              key={`placeholder-${index}`}
                              className='h-16 rounded-lg border-2 border-dashed border-border-primary/60'
                            ></div>
                          ))}

                          {/* Pagination Controls */}
                          {totalPages > 1 && (
                            <div className='flex items-center justify-center gap-3 pt-2'>
                              <button
                                onClick={() =>
                                  setRequestsPage(Math.max(1, requestsPage - 1))
                                }
                                disabled={requestsPage === 1}
                                className='flex h-8 w-8 items-center justify-center rounded-lg border border-border-primary bg-background-primary text-foreground-primary transition-colors hover:bg-background-secondary disabled:cursor-not-allowed disabled:opacity-50'
                                aria-label='Previous page'
                              >
                                <svg
                                  className='h-4 w-4'
                                  fill='none'
                                  stroke='currentColor'
                                  viewBox='0 0 24 24'
                                >
                                  <path
                                    strokeLinecap='round'
                                    strokeLinejoin='round'
                                    strokeWidth={2}
                                    d='M15 19l-7-7 7-7'
                                  />
                                </svg>
                              </button>
                              <span className='text-xs text-foreground-secondary'>
                                Page {requestsPage} of {totalPages}
                              </span>
                              <button
                                onClick={() =>
                                  setRequestsPage(
                                    Math.min(totalPages, requestsPage + 1)
                                  )
                                }
                                disabled={requestsPage === totalPages}
                                className='flex h-8 w-8 items-center justify-center rounded-lg border border-border-primary bg-background-primary text-foreground-primary transition-colors hover:bg-background-secondary disabled:cursor-not-allowed disabled:opacity-50'
                                aria-label='Next page'
                              >
                                <svg
                                  className='h-4 w-4'
                                  fill='none'
                                  stroke='currentColor'
                                  viewBox='0 0 24 24'
                                >
                                  <path
                                    strokeLinecap='round'
                                    strokeLinejoin='round'
                                    strokeWidth={2}
                                    d='M9 5l7 7-7 7'
                                  />
                                </svg>
                              </button>
                            </div>
                          )}
                        </div>
                      );
                    })()}
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Step 2: Timeline */}
          {currentStep === 2 && (
            <div className='flex min-h-[calc(85vh-300px)] items-center justify-center'>
              <div className='mx-auto w-full max-w-2xl space-y-6'>
                <div className='mb-8 text-center'>
                  <h3 className='mb-2 text-xl font-semibold text-foreground-primary'>
                    When do you need this by?
                  </h3>
                  <p className='text-sm text-foreground-secondary'>
                    Set a timeline for when you need this project completed.
                  </p>
                </div>

                <div className='space-y-6'>
                  {/* Timeline Days Input */}
                  <div className='space-y-4'>
                    <div className='flex items-center justify-center gap-4'>
                      <input
                        type='number'
                        min='1'
                        max='90'
                        value={timelineDays}
                        onChange={(e) =>
                          setTimelineDays(parseInt(e.target.value) || 1)
                        }
                        className='w-24 rounded-lg border border-border-primary bg-transparent px-4 py-3 text-center text-2xl font-semibold text-foreground-primary focus:border-accent-brand focus:outline-none'
                      />
                      <span className='text-lg text-foreground-secondary'>
                        {timelineDays === 1 ? 'day' : 'days'}
                      </span>
                    </div>

                    {/* Quick select buttons */}
                    <div className='flex justify-center gap-2'>
                      {[3, 7, 14, 30].map((days) => (
                        <button
                          key={days}
                          type='button'
                          onClick={() => setTimelineDays(days)}
                          className={`rounded-lg border px-3 py-1.5 text-xs font-medium transition-colors ${
                            timelineDays === days
                              ? 'border-accent-brand bg-accent-brand/10 text-accent-brand'
                              : 'border-border-primary bg-background-primary text-foreground-secondary hover:bg-background-secondary'
                          }`}
                        >
                          {days} {days === 1 ? 'day' : 'days'}
                        </button>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Step 3: Project Bounty */}
          {currentStep === 3 && (
            <div className='flex min-h-[calc(85vh-300px)] items-center justify-center'>
              <div className='mx-auto w-full max-w-2xl space-y-6'>
                <div className='mb-8 text-center'>
                  <h3 className='mb-2 text-xl font-semibold text-foreground-primary'>
                    Project Bounty
                  </h3>
                  <p className='text-sm text-foreground-secondary'>
                    Set how many credits you'll pay upon completion. Credits are
                    held in escrow until the project is finished.
                  </p>
                </div>

                <div className='space-y-6'>
                  {/* Project Bounty */}
                  <div className='rounded-lg border border-border-primary bg-background-secondary p-6'>
                    <div className='mb-6 flex items-center justify-between'>
                      <div>
                        <h4 className='text-lg font-medium text-foreground-primary'>
                          Credit Bounty
                        </h4>
                        <p className='text-sm text-foreground-secondary'>
                          Credits awarded when project is completed
                        </p>
                      </div>
                      <div className='text-right'>
                        <div className='text-3xl font-bold text-accent-brand'>
                          {projectBounty} credits
                        </div>
                      </div>
                    </div>

                    {/* Project Bounty Slider */}
                    <div>
                      <div className='mb-4 flex items-center justify-between'>
                        <label
                          htmlFor='bounty-slider'
                          className='text-sm font-medium text-foreground-primary'
                        >
                          Adjust Bounty
                        </label>
                        <span className='text-sm font-semibold text-accent-brand'>
                          {projectBounty} credits
                        </span>
                      </div>
                      {(() => {
                        const maxBounty = Math.min(2000, userCreditBalance);
                        const denominator = Math.max(1, maxBounty - 20);
                        const gradientPercent =
                          ((projectBounty - 20) / denominator) * 100;

                        return (
                          <>
                            <input
                              id='bounty-slider'
                              type='range'
                              min='20'
                              max={Math.max(20, maxBounty)}
                              step='10'
                              value={Math.min(
                                projectBounty,
                                Math.max(20, maxBounty)
                              )}
                              onChange={(e) => {
                                const newValue = Number(e.target.value);
                                // Round to nearest 10
                                const roundedValue =
                                  Math.round(newValue / 10) * 10;
                                setProjectBounty(
                                  Math.min(roundedValue, maxBounty)
                                );
                              }}
                              className='h-3 w-full cursor-pointer appearance-none rounded-lg bg-background-primary'
                              style={{
                                background: `linear-gradient(to right, #ec4899 0%, #ec4899 ${gradientPercent}%, #374151 ${gradientPercent}%, #374151 100%)`,
                                WebkitAppearance: 'none',
                                appearance: 'none',
                              }}
                            />
                            <style>{`
                          #bounty-slider::-webkit-slider-thumb {
                            appearance: none;
                            width: 20px;
                            height: 20px;
                            border-radius: 50%;
                            background: #ec4899;
                            cursor: pointer;
                          }
                          #bounty-slider::-moz-range-thumb {
                            width: 20px;
                            height: 20px;
                            border-radius: 50%;
                            background: #ec4899;
                            cursor: pointer;
                            border: none;
                          }
                        `}</style>
                          </>
                        );
                      })()}
                      <div className='mt-2 flex justify-between text-sm text-foreground-secondary'>
                        <span>20 credits</span>
                        <span>{Math.min(2000, userCreditBalance)} credits</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Step 4: Instructions */}
          {currentStep === 4 && (
            <div className='flex min-h-[calc(85vh-300px)] items-center justify-center'>
              <div className='mx-auto w-full max-w-2xl space-y-6'>
                <div className='mb-8 text-center'>
                  <h3 className='mb-2 text-xl font-semibold text-foreground-primary'>
                    Your Vision
                  </h3>
                  <p className='text-sm text-foreground-secondary'>
                    Share the story behind your track, your artistic vision, and
                    any context that will help editors deliver the best results.
                  </p>
                </div>

                <div className='space-y-6'>
                  <div>
                    <textarea
                      id='artistic-direction'
                      value={artisticDirection}
                      onChange={(e) => setArtisticDirection(e.target.value)}
                      rows={4}
                      className='w-full resize-none rounded-lg border border-border-primary bg-transparent px-3 py-2 text-sm text-foreground-primary placeholder-foreground-tertiary focus:border-pink-500 focus:outline-none'
                    />
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* Step 5: Listing Preview */}
          {currentStep === 5 && (
            <div className='flex min-h-[calc(85vh-300px)] items-center justify-center'>
              <div className='mx-auto w-full max-w-4xl space-y-6'>
                <div className='mb-8 text-center'>
                  <h3 className='mb-2 text-xl font-semibold text-foreground-primary'>
                    Listing Preview
                  </h3>
                  <p className='text-sm text-foreground-secondary'>
                    Provide a title and summary that will be shown to editors in
                    the marketplace.
                  </p>
                </div>

                <div className='space-y-6'>
                  <div className='grid grid-cols-1 gap-6 lg:grid-cols-2'>
                    {/* Left Column - Input Fields */}
                    <div className='space-y-6'>
                      {/* Project Title */}
                      <div>
                        <label
                          htmlFor='project-title'
                          className='mb-2 block text-sm font-medium text-foreground-primary'
                        >
                          Project Title <span className='text-red-400'>*</span>
                        </label>
                        <p className='mb-2 text-xs text-foreground-secondary'>
                          A descriptive title to grab the attention of editors.
                        </p>
                        <input
                          id='project-title'
                          type='text'
                          value={projectTitle}
                          onChange={(e) => setProjectTitle(e.target.value)}
                          placeholder='e.g. Mix graduation song'
                          required
                          className='w-full rounded-lg border border-border-primary bg-transparent px-3 py-2 text-sm text-foreground-primary placeholder-foreground-tertiary focus:border-pink-500 focus:outline-none'
                        />
                      </div>

                      {/* Project Summary */}
                      <div>
                        <label
                          htmlFor='project-summary'
                          className='mb-2 block text-sm font-medium text-foreground-primary'
                        >
                          Marketplace Summary{' '}
                          <span className='text-red-400'>*</span>
                        </label>
                        <p className='mb-2 text-xs text-foreground-secondary'>
                          A concise and clear summary of your asks that will
                          appear in marketplace listings.
                        </p>
                        <textarea
                          id='project-summary'
                          value={listingSummary}
                          onChange={(e) => setListingSummary(e.target.value)}
                          rows={6}
                          placeholder='e.g. Need vocals louder and clearer with reverb'
                          required
                          className='w-full resize-none rounded-lg border border-border-primary bg-transparent px-3 py-2 text-sm text-foreground-primary placeholder-foreground-tertiary focus:border-pink-500 focus:outline-none'
                        />
                      </div>
                    </div>

                    {/* Right Column - Preview */}
                    <MarketplaceListingPreview
                      title={projectTitle}
                      summary={listingSummary}
                      creditBounty={projectBounty}
                      timelineDays={timelineDays}
                      status='OPEN'
                    />
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* Fixed Bottom Navigation */}
        <div className='absolute inset-x-0 bottom-0 flex items-center justify-between border-t border-border-primary bg-background-primary px-8 py-4'>
          {currentStep > 1 ? (
            <button
              onClick={() => setCurrentStep(currentStep - 1)}
              className='rounded-lg border border-border-primary bg-background-primary px-4 py-2 text-sm font-medium text-foreground-primary transition-colors hover:bg-background-secondary'
            >
              Back
            </button>
          ) : (
            <div />
          )}

          {currentStep < 5 ? (
            <button
              onClick={() => {
                if (currentStep === 1) {
                  handleNext();
                } else {
                  setCurrentStep(currentStep + 1);
                }
              }}
              disabled={
                currentStep === 1 &&
                timeRangePrompts.length === 0 &&
                generalPrompts.length === 0
              }
              className='rounded-lg border border-accent-brand bg-accent-brand px-4 py-2 text-sm font-medium text-white transition-colors hover:bg-accent-brand/90 disabled:cursor-not-allowed disabled:opacity-50'
            >
              Next
            </button>
          ) : (
            <button
              onClick={handleSubmit}
              disabled={
                isLoading || !projectTitle.trim() || !listingSummary.trim()
              }
              className='flex items-center justify-center rounded-lg border border-accent-brand bg-accent-brand px-6 py-2 text-sm font-medium text-white transition-colors hover:bg-accent-brand/90 disabled:cursor-not-allowed disabled:opacity-50'
            >
              {isLoading ? (
                <div className='flex items-center justify-center gap-2'>
                  <svg
                    className='h-4 w-4 animate-spin'
                    fill='none'
                    viewBox='0 0 24 24'
                  >
                    <circle
                      className='opacity-25'
                      cx='12'
                      cy='12'
                      r='10'
                      stroke='currentColor'
                      strokeWidth='4'
                    />
                    <path
                      className='opacity-75'
                      fill='currentColor'
                      d='M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z'
                    />
                  </svg>
                  Creating...
                </div>
              ) : (
                'Create Project'
              )}
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

export default MarketplaceCreateProjectModal;
